diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9f89d4d01..a9bf7f463 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -65,12 +65,12 @@ jobs: # Instead of testing against the pre-built image, we can build # an image from the currently checked-out repo contents by doing a # li'l update in the action.yml file to point to the current Dockerfile. - - name: Replace Docker image value in action.yml - uses: jacobtomlinson/gha-find-replace@v3 - with: - find: 'image:.*' - replace: "image: 'Dockerfile'" - include: rdme-repo/action.yml + # - name: Replace Docker image value in action.yml + # uses: jacobtomlinson/gha-find-replace@v3 + # with: + # find: 'image:.*' + # replace: "image: 'Dockerfile'" + # include: rdme-repo/action.yml - name: Run `openapi:validate` command uses: ./rdme-repo/ diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index 7f84a753d..3a91d8259 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -45,12 +45,12 @@ jobs: # Instead of testing against the pre-built image, we can build # an image from the currently checked-out repo contents by doing a # li'l update in the action.yml file to point to the current Dockerfile. - - name: Replace Docker image value in action.yml - uses: jacobtomlinson/gha-find-replace@v3 - with: - find: 'image:.*' - replace: "image: 'Dockerfile'" - include: action.yml + # - name: Replace Docker image value in action.yml + # uses: jacobtomlinson/gha-find-replace@v3 + # with: + # find: 'image:.*' + # replace: "image: 'Dockerfile'" + # include: action.yml # And finally, with our updated documentation, # we run the `rdme` GitHub Action to sync the Markdown file diff --git a/action.yml b/action.yml index fea1d97a6..9edcf352a 100644 --- a/action.yml +++ b/action.yml @@ -12,8 +12,5 @@ outputs: rdme: description: The rdme command result output runs: - using: docker - image: docker://ghcr.io/readmeio/rdme:8.7.0-next.2 - args: - - docker-gha - - ${{ inputs.rdme }} + using: node20 + main: rollup-output.cjs diff --git a/rollup-output.cjs b/rollup-output.cjs new file mode 100644 index 000000000..ec334032a --- /dev/null +++ b/rollup-output.cjs @@ -0,0 +1,240057 @@ +'use strict'; + +var require$$0$7 = require('os'); +var require$$0$8 = require('fs'); +var crypto = require('crypto'); +var require$$0$b = require('path'); +var require$$0$a = require('http'); +var require$$1$4 = require('https'); +var require$$0$f = require('net'); +var require$$1$3 = require('tls'); +var require$$2$3 = require('events'); +var require$$5$1 = require('assert'); +var require$$0$9 = require('util'); +var process$3 = require('node:process'); +var os$5 = require('node:os'); +var tty = require('node:tty'); +var childProcess$1 = require('node:child_process'); +var urlLib = require('node:url'); +var path$c = require('node:path'); +var node_util = require('node:util'); +var require$$0$c = require('constants'); +var Stream$3 = require('stream'); +var http$a = require('node:http'); +var https$8 = require('node:https'); +var EventEmitter$3 = require('node:events'); +var node_buffer = require('node:buffer'); +var Stream$4 = require('node:stream'); +var crypto$1 = require('node:crypto'); +var require$$0$d = require('buffer'); +var zlib$1 = require('zlib'); +var net = require('node:net'); +var node_tls = require('node:tls'); +var node_dns = require('node:dns'); +var require$$3$4 = require('http2'); +var require$$0$e = require('url'); +var fs$i = require('node:fs'); +var zlib$2 = require('node:zlib'); +var require$$1$5 = require('tty'); +var require$$0$g = require('readline'); +var require$$0$h = require('child_process'); +var fs$j = require('node:fs/promises'); +var readline = require('node:readline'); +var require$$0$i = require('querystring'); +var vm = require('vm'); +var require$$0$j = require('punycode'); + +var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null; +function _interopNamespaceDefault(e) { + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n.default = e; + return Object.freeze(n); +} + +var require$$0__namespace = /*#__PURE__*/_interopNamespaceDefault(require$$0$9); + +var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + +function getDefaultExportFromCjs (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; +} + +function getAugmentedNamespace(n) { + if (n.__esModule) return n; + var f = n.default; + if (typeof f == "function") { + var a = function a () { + if (this instanceof a) { + return Reflect.construct(f, arguments, this.constructor); + } + return f.apply(this, arguments); + }; + a.prototype = f.prototype; + } else a = {}; + Object.defineProperty(a, '__esModule', {value: true}); + Object.keys(n).forEach(function (k) { + var d = Object.getOwnPropertyDescriptor(n, k); + Object.defineProperty(a, k, d.get ? d : { + enumerable: true, + get: function () { + return n[k]; + } + }); + }); + return a; +} + +var core$c = {}; + +var command$1 = {}; + +var utils$a = {}; + +// We use any as a valid input type +/* eslint-disable @typescript-eslint/no-explicit-any */ +Object.defineProperty(utils$a, "__esModule", { value: true }); +utils$a.toCommandProperties = utils$a.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$a.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$a.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$1, "__esModule", { value: true }); +command$1.issue = command$1.issueCommand = void 0; +const os$4 = __importStar$1(require$$0$7); +const utils_1$g = utils$a; +/** + * 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$1(command, properties, message); + process.stdout.write(cmd.toString() + os$4.EOL); +} +command$1.issueCommand = issueCommand; +function issue(name, message = '') { + issueCommand(name, {}, message); +} +command$1.issue = issue; +const CMD_STRING = '::'; +let Command$1 = 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$g.toCommandValue(s) + .replace(/%/g, '%25') + .replace(/\r/g, '%0D') + .replace(/\n/g, '%0A'); +} +function escapeProperty(s) { + return utils_1$g.toCommandValue(s) + .replace(/%/g, '%25') + .replace(/\r/g, '%0D') + .replace(/\n/g, '%0A') + .replace(/:/g, '%3A') + .replace(/,/g, '%2C'); +} + +var fileCommand = {}; + +const rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate + +let poolPtr = rnds8Pool.length; +function rng() { + if (poolPtr > rnds8Pool.length - 16) { + crypto.randomFillSync(rnds8Pool); + poolPtr = 0; + } + + return rnds8Pool.slice(poolPtr, poolPtr += 16); +} + +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$1(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 + */ + +const byteToHex = []; + +for (let i = 0; i < 256; ++i) { + byteToHex.push((i + 0x100).toString(16).substr(1)); +} + +function stringify$6(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 + const uuid = (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(); // 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$1(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 + +let _nodeId; + +let _clockseq; // Previous uuid creation time + + +let _lastMSecs = 0; +let _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details + +function v1(options, buf, offset) { + let i = buf && offset || 0; + const b = buf || new Array(16); + options = options || {}; + let node = options.node || _nodeId; + let 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) { + const seedBytes = options.random || (options.rng || rng)(); + + 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. + + + let 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 + + let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs) + + const 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` + + const 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` + + const 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 (let n = 0; n < 6; ++n) { + b[i + n] = node[n]; + } + + return buf || stringify$6(b); +} + +function parse$m(uuid) { + if (!validate$1(uuid)) { + throw TypeError('Invalid UUID'); + } + + let v; + const 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 + + const bytes = []; + + for (let i = 0; i < str.length; ++i) { + bytes.push(str.charCodeAt(i)); + } + + return bytes; +} + +const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; +const URL$8 = '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$m(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])` + + + let 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 (let i = 0; i < 16; ++i) { + buf[offset + i] = bytes[i]; + } + + return buf; + } + + return stringify$6(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$8; + return generateUUID; +} + +function md5(bytes) { + if (Array.isArray(bytes)) { + bytes = Buffer.from(bytes); + } else if (typeof bytes === 'string') { + bytes = Buffer.from(bytes, 'utf8'); + } + + return crypto.createHash('md5').update(bytes).digest(); +} + +const v3 = v35('v3', 0x30, md5); +var v3$1 = v3; + +function v4(options, buf, offset) { + 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 stringify$6(rnds); +} + +function sha1(bytes) { + if (Array.isArray(bytes)) { + bytes = Buffer.from(bytes); + } else if (typeof bytes === 'string') { + bytes = Buffer.from(bytes, 'utf8'); + } + + return crypto.createHash('sha1').update(bytes).digest(); +} + +const v5 = v35('v5', 0x50, sha1); +var v5$1 = v5; + +var nil = '00000000-0000-0000-0000-000000000000'; + +function version$3(uuid) { + if (!validate$1(uuid)) { + throw TypeError('Invalid UUID'); + } + + return parseInt(uuid.substr(14, 1), 16); +} + +var esmNode = /*#__PURE__*/Object.freeze({ + __proto__: null, + NIL: nil, + parse: parse$m, + stringify: stringify$6, + v1: v1, + v3: v3$1, + v4: v4, + v5: v5$1, + validate: validate$1, + version: version$3 +}); + +var require$$2$2 = /*@__PURE__*/getAugmentedNamespace(esmNode); + +// 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$h = __importStar(require$$0$8); +const os$3 = __importStar(require$$0$7); +const uuid_1 = require$$2$2; +const utils_1$f = utils$a; +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$h.existsSync(filePath)) { + throw new Error(`Missing file at path: ${filePath}`); + } + fs$h.appendFileSync(filePath, `${utils_1$f.toCommandValue(message)}${os$3.EOL}`, { + encoding: 'utf8' + }); +} +fileCommand.issueFileCommand = issueFileCommand; +function prepareKeyValueMessage(key, value) { + const delimiter = `ghadelimiter_${uuid_1.v4()}`; + const convertedValue = utils_1$f.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$3.EOL}${convertedValue}${os$3.EOL}${delimiter}`; +} +fileCommand.prepareKeyValueMessage = prepareKeyValueMessage; + +var oidcUtils = {}; + +var lib$j = {}; + +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) { + try { + return new URL(proxyVar); + } + catch (_a) { + if (!proxyVar.startsWith('http://') && !proxyVar.startsWith('https://')) + return new URL(`http://${proxyVar}`); + } + } + else { + return undefined; + } +} +proxy.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; +} +proxy.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]')); +} + +var tunnel$1 = {}; + +var tls$4 = require$$1$3; +var http$9 = require$$0$a; +var https$7 = require$$1$4; +var events = require$$2$3; +var util$g = require$$0$9; + + +tunnel$1.httpOverHttp = httpOverHttp; +tunnel$1.httpsOverHttp = httpsOverHttp; +tunnel$1.httpOverHttps = httpOverHttps; +tunnel$1.httpsOverHttps = httpsOverHttps; + + +function httpOverHttp(options) { + var agent = new TunnelingAgent(options); + agent.request = http$9.request; + return agent; +} + +function httpsOverHttp(options) { + var agent = new TunnelingAgent(options); + agent.request = http$9.request; + agent.createSocket = createSecureSocket; + agent.defaultPort = 443; + return agent; +} + +function httpOverHttps(options) { + var agent = new TunnelingAgent(options); + agent.request = https$7.request; + return agent; +} + +function httpsOverHttps(options) { + var agent = new TunnelingAgent(options); + agent.request = https$7.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$9.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$g.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$6('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$6('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$6('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$6('tunneling connection has established'); + self.sockets[self.sockets.indexOf(placeholder)] = socket; + return cb(socket); + } + + function onError(cause) { + connectReq.removeAllListeners(); + + debug$6('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$4.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$6; +if (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) { + debug$6 = 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$6 = function() {}; +} +tunnel$1.debug = debug$6; // for test + +var 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(require$$0$a); + const https = __importStar(require$$1$4); + const pm = __importStar(proxy); + const tunnel$1 = __importStar(tunnel); + 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()); + }); + })); + }); + } + readBodyBuffer() { + return __awaiter(this, void 0, void 0, function* () { + return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () { + const chunks = []; + this.message.on('data', (chunk) => { + chunks.push(chunk); + }); + this.message.on('end', () => { + resolve(Buffer.concat(chunks)); + }); + })); + }); + } + } + 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$1.httpsOverHttps : tunnel$1.httpsOverHttp; + } + else { + tunnelAgent = overHttps ? tunnel$1.httpOverHttps : tunnel$1.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$j)); + +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$j; + 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.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$7; + const fs_1 = require$$0$8; + 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}`; + } + /** + * 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$b); + /** + * 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$c; + 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$1; + const file_command_1 = fileCommand; + const utils_1 = utils$a; + const os = __importStar(require$$0$7); + const path = __importStar(require$$0$b); + 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$c)); + return core$c; +} + +var coreExports = requireCore(); + +const ANSI_BACKGROUND_OFFSET$1 = 10; + +const wrapAnsi16$1 = (offset = 0) => code => `\u001B[${code + offset}m`; + +const wrapAnsi256$1 = (offset = 0) => code => `\u001B[${38 + offset};5;${code}m`; + +const wrapAnsi16m$1 = (offset = 0) => (red, green, blue) => `\u001B[${38 + offset};2;${red};${green};${blue}m`; + +const styles$3 = { + modifier: { + reset: [0, 0], + // 21 isn't widely supported and 22 does the same thing + bold: [1, 22], + dim: [2, 22], + italic: [3, 23], + underline: [4, 24], + overline: [53, 55], + inverse: [7, 27], + hidden: [8, 28], + strikethrough: [9, 29], + }, + color: { + black: [30, 39], + red: [31, 39], + green: [32, 39], + yellow: [33, 39], + blue: [34, 39], + magenta: [35, 39], + cyan: [36, 39], + white: [37, 39], + + // Bright color + blackBright: [90, 39], + gray: [90, 39], // Alias of `blackBright` + grey: [90, 39], // Alias of `blackBright` + redBright: [91, 39], + greenBright: [92, 39], + yellowBright: [93, 39], + blueBright: [94, 39], + magentaBright: [95, 39], + cyanBright: [96, 39], + whiteBright: [97, 39], + }, + bgColor: { + bgBlack: [40, 49], + bgRed: [41, 49], + bgGreen: [42, 49], + bgYellow: [43, 49], + bgBlue: [44, 49], + bgMagenta: [45, 49], + bgCyan: [46, 49], + bgWhite: [47, 49], + + // Bright color + bgBlackBright: [100, 49], + bgGray: [100, 49], // Alias of `bgBlackBright` + bgGrey: [100, 49], // Alias of `bgBlackBright` + bgRedBright: [101, 49], + bgGreenBright: [102, 49], + bgYellowBright: [103, 49], + bgBlueBright: [104, 49], + bgMagentaBright: [105, 49], + bgCyanBright: [106, 49], + bgWhiteBright: [107, 49], + }, +}; + +Object.keys(styles$3.modifier); +const foregroundColorNames$1 = Object.keys(styles$3.color); +const backgroundColorNames$1 = Object.keys(styles$3.bgColor); +[...foregroundColorNames$1, ...backgroundColorNames$1]; + +function assembleStyles$1() { + const codes = new Map(); + + for (const [groupName, group] of Object.entries(styles$3)) { + for (const [styleName, style] of Object.entries(group)) { + styles$3[styleName] = { + open: `\u001B[${style[0]}m`, + close: `\u001B[${style[1]}m`, + }; + + group[styleName] = styles$3[styleName]; + + codes.set(style[0], style[1]); + } + + Object.defineProperty(styles$3, groupName, { + value: group, + enumerable: false, + }); + } + + Object.defineProperty(styles$3, 'codes', { + value: codes, + enumerable: false, + }); + + styles$3.color.close = '\u001B[39m'; + styles$3.bgColor.close = '\u001B[49m'; + + styles$3.color.ansi = wrapAnsi16$1(); + styles$3.color.ansi256 = wrapAnsi256$1(); + styles$3.color.ansi16m = wrapAnsi16m$1(); + styles$3.bgColor.ansi = wrapAnsi16$1(ANSI_BACKGROUND_OFFSET$1); + styles$3.bgColor.ansi256 = wrapAnsi256$1(ANSI_BACKGROUND_OFFSET$1); + styles$3.bgColor.ansi16m = wrapAnsi16m$1(ANSI_BACKGROUND_OFFSET$1); + + // From https://github.com/Qix-/color-convert/blob/3f0e0d4e92e235796ccb17f6e85c72094a651f49/conversions.js + Object.defineProperties(styles$3, { + rgbToAnsi256: { + value(red, green, blue) { + // We use the extended greyscale palette here, with the exception of + // black and white. normal palette only has 4 greyscale shades. + if (red === green && green === blue) { + if (red < 8) { + return 16; + } + + if (red > 248) { + return 231; + } + + return Math.round(((red - 8) / 247) * 24) + 232; + } + + return 16 + + (36 * Math.round(red / 255 * 5)) + + (6 * Math.round(green / 255 * 5)) + + Math.round(blue / 255 * 5); + }, + enumerable: false, + }, + hexToRgb: { + value(hex) { + const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16)); + if (!matches) { + return [0, 0, 0]; + } + + let [colorString] = matches; + + if (colorString.length === 3) { + colorString = [...colorString].map(character => character + character).join(''); + } + + const integer = Number.parseInt(colorString, 16); + + return [ + /* eslint-disable no-bitwise */ + (integer >> 16) & 0xFF, + (integer >> 8) & 0xFF, + integer & 0xFF, + /* eslint-enable no-bitwise */ + ]; + }, + enumerable: false, + }, + hexToAnsi256: { + value: hex => styles$3.rgbToAnsi256(...styles$3.hexToRgb(hex)), + enumerable: false, + }, + ansi256ToAnsi: { + value(code) { + if (code < 8) { + return 30 + code; + } + + if (code < 16) { + return 90 + (code - 8); + } + + let red; + let green; + let blue; + + if (code >= 232) { + red = (((code - 232) * 10) + 8) / 255; + green = red; + blue = red; + } else { + code -= 16; + + const remainder = code % 36; + + red = Math.floor(code / 36) / 5; + green = Math.floor(remainder / 6) / 5; + blue = (remainder % 6) / 5; + } + + const value = Math.max(red, green, blue) * 2; + + if (value === 0) { + return 30; + } + + // eslint-disable-next-line no-bitwise + let result = 30 + ((Math.round(blue) << 2) | (Math.round(green) << 1) | Math.round(red)); + + if (value === 2) { + result += 60; + } + + return result; + }, + enumerable: false, + }, + rgbToAnsi: { + value: (red, green, blue) => styles$3.ansi256ToAnsi(styles$3.rgbToAnsi256(red, green, blue)), + enumerable: false, + }, + hexToAnsi: { + value: hex => styles$3.ansi256ToAnsi(styles$3.hexToAnsi256(hex)), + enumerable: false, + }, + }); + + return styles$3; +} + +const ansiStyles$8 = assembleStyles$1(); + +// From: https://github.com/sindresorhus/has-flag/blob/main/index.js +/// function hasFlag(flag, argv = globalThis.Deno?.args ?? process.argv) { +function hasFlag$3(flag, argv = globalThis.Deno ? globalThis.Deno.args : process$3.argv) { + const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); + const position = argv.indexOf(prefix + flag); + const terminatorPosition = argv.indexOf('--'); + return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); +} + +const {env: env$1} = process$3; + +let flagForceColor; +if ( + hasFlag$3('no-color') + || hasFlag$3('no-colors') + || hasFlag$3('color=false') + || hasFlag$3('color=never') +) { + flagForceColor = 0; +} else if ( + hasFlag$3('color') + || hasFlag$3('colors') + || hasFlag$3('color=true') + || hasFlag$3('color=always') +) { + flagForceColor = 1; +} + +function envForceColor() { + if ('FORCE_COLOR' in env$1) { + if (env$1.FORCE_COLOR === 'true') { + return 1; + } + + if (env$1.FORCE_COLOR === 'false') { + return 0; + } + + return env$1.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env$1.FORCE_COLOR, 10), 3); + } +} + +function translateLevel(level) { + if (level === 0) { + return false; + } + + return { + level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3, + }; +} + +function _supportsColor(haveStream, {streamIsTTY, sniffFlags = true} = {}) { + const noFlagForceColor = envForceColor(); + if (noFlagForceColor !== undefined) { + flagForceColor = noFlagForceColor; + } + + const forceColor = sniffFlags ? flagForceColor : noFlagForceColor; + + if (forceColor === 0) { + return 0; + } + + if (sniffFlags) { + if (hasFlag$3('color=16m') + || hasFlag$3('color=full') + || hasFlag$3('color=truecolor')) { + return 3; + } + + if (hasFlag$3('color=256')) { + return 2; + } + } + + // Check for Azure DevOps pipelines. + // Has to be above the `!streamIsTTY` check. + if ('TF_BUILD' in env$1 && 'AGENT_NAME' in env$1) { + return 1; + } + + if (haveStream && !streamIsTTY && forceColor === undefined) { + return 0; + } + + const min = forceColor || 0; + + if (env$1.TERM === 'dumb') { + return min; + } + + if (process$3.platform === 'win32') { + // Windows 10 build 10586 is the first Windows release that supports 256 colors. + // Windows 10 build 14931 is the first release that supports 16m/TrueColor. + const osRelease = os$5.release().split('.'); + if ( + Number(osRelease[0]) >= 10 + && Number(osRelease[2]) >= 10_586 + ) { + return Number(osRelease[2]) >= 14_931 ? 3 : 2; + } + + return 1; + } + + if ('CI' in env$1) { + if ('GITHUB_ACTIONS' in env$1 || 'GITEA_ACTIONS' in env$1) { + return 3; + } + + if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'BUILDKITE', 'DRONE'].some(sign => sign in env$1) || env$1.CI_NAME === 'codeship') { + return 1; + } + + return min; + } + + if ('TEAMCITY_VERSION' in env$1) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$1.TEAMCITY_VERSION) ? 1 : 0; + } + + if (env$1.COLORTERM === 'truecolor') { + return 3; + } + + if (env$1.TERM === 'xterm-kitty') { + return 3; + } + + if ('TERM_PROGRAM' in env$1) { + const version = Number.parseInt((env$1.TERM_PROGRAM_VERSION || '').split('.')[0], 10); + + switch (env$1.TERM_PROGRAM) { + case 'iTerm.app': { + return version >= 3 ? 3 : 2; + } + + case 'Apple_Terminal': { + return 2; + } + // No default + } + } + + if (/-256(color)?$/i.test(env$1.TERM)) { + return 2; + } + + if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$1.TERM)) { + return 1; + } + + if ('COLORTERM' in env$1) { + return 1; + } + + return min; +} + +function createSupportsColor(stream, options = {}) { + const level = _supportsColor(stream, { + streamIsTTY: stream && stream.isTTY, + ...options, + }); + + return translateLevel(level); +} + +const supportsColor = { + stdout: createSupportsColor({isTTY: tty.isatty(1)}), + stderr: createSupportsColor({isTTY: tty.isatty(2)}), +}; + +// TODO: When targeting Node.js 16, use `String.prototype.replaceAll`. +function stringReplaceAll$2(string, substring, replacer) { + let index = string.indexOf(substring); + if (index === -1) { + return string; + } + + const substringLength = substring.length; + let endIndex = 0; + let returnValue = ''; + do { + returnValue += string.slice(endIndex, index) + substring + replacer; + endIndex = index + substringLength; + index = string.indexOf(substring, endIndex); + } while (index !== -1); + + returnValue += string.slice(endIndex); + return returnValue; +} + +function stringEncaseCRLFWithFirstIndex$2(string, prefix, postfix, index) { + let endIndex = 0; + let returnValue = ''; + do { + const gotCR = string[index - 1] === '\r'; + returnValue += string.slice(endIndex, (gotCR ? index - 1 : index)) + prefix + (gotCR ? '\r\n' : '\n') + postfix; + endIndex = index + 1; + index = string.indexOf('\n', endIndex); + } while (index !== -1); + + returnValue += string.slice(endIndex); + return returnValue; +} + +const {stdout: stdoutColor$1, stderr: stderrColor$1} = supportsColor; + +const GENERATOR = Symbol('GENERATOR'); +const STYLER = Symbol('STYLER'); +const IS_EMPTY = Symbol('IS_EMPTY'); + +// `supportsColor.level` → `ansiStyles.color[name]` mapping +const levelMapping$1 = [ + 'ansi', + 'ansi', + 'ansi256', + 'ansi16m', +]; + +const styles$2 = Object.create(null); + +const applyOptions$1 = (object, options = {}) => { + if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) { + throw new Error('The `level` option should be an integer from 0 to 3'); + } + + // Detect level if not set manually + const colorLevel = stdoutColor$1 ? stdoutColor$1.level : 0; + object.level = options.level === undefined ? colorLevel : options.level; +}; + +const chalkFactory$1 = options => { + const chalk = (...strings) => strings.join(' '); + applyOptions$1(chalk, options); + + Object.setPrototypeOf(chalk, createChalk.prototype); + + return chalk; +}; + +function createChalk(options) { + return chalkFactory$1(options); +} + +Object.setPrototypeOf(createChalk.prototype, Function.prototype); + +for (const [styleName, style] of Object.entries(ansiStyles$8)) { + styles$2[styleName] = { + get() { + const builder = createBuilder$1(this, createStyler$1(style.open, style.close, this[STYLER]), this[IS_EMPTY]); + Object.defineProperty(this, styleName, {value: builder}); + return builder; + }, + }; +} + +styles$2.visible = { + get() { + const builder = createBuilder$1(this, this[STYLER], true); + Object.defineProperty(this, 'visible', {value: builder}); + return builder; + }, +}; + +const getModelAnsi = (model, level, type, ...arguments_) => { + if (model === 'rgb') { + if (level === 'ansi16m') { + return ansiStyles$8[type].ansi16m(...arguments_); + } + + if (level === 'ansi256') { + return ansiStyles$8[type].ansi256(ansiStyles$8.rgbToAnsi256(...arguments_)); + } + + return ansiStyles$8[type].ansi(ansiStyles$8.rgbToAnsi(...arguments_)); + } + + if (model === 'hex') { + return getModelAnsi('rgb', level, type, ...ansiStyles$8.hexToRgb(...arguments_)); + } + + return ansiStyles$8[type][model](...arguments_); +}; + +const usedModels$1 = ['rgb', 'hex', 'ansi256']; + +for (const model of usedModels$1) { + styles$2[model] = { + get() { + const {level} = this; + return function (...arguments_) { + const styler = createStyler$1(getModelAnsi(model, levelMapping$1[level], 'color', ...arguments_), ansiStyles$8.color.close, this[STYLER]); + return createBuilder$1(this, styler, this[IS_EMPTY]); + }; + }, + }; + + const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); + styles$2[bgModel] = { + get() { + const {level} = this; + return function (...arguments_) { + const styler = createStyler$1(getModelAnsi(model, levelMapping$1[level], 'bgColor', ...arguments_), ansiStyles$8.bgColor.close, this[STYLER]); + return createBuilder$1(this, styler, this[IS_EMPTY]); + }; + }, + }; +} + +const proto$1 = Object.defineProperties(() => {}, { + ...styles$2, + level: { + enumerable: true, + get() { + return this[GENERATOR].level; + }, + set(level) { + this[GENERATOR].level = level; + }, + }, +}); + +const createStyler$1 = (open, close, parent) => { + let openAll; + let closeAll; + if (parent === undefined) { + openAll = open; + closeAll = close; + } else { + openAll = parent.openAll + open; + closeAll = close + parent.closeAll; + } + + return { + open, + close, + openAll, + closeAll, + parent, + }; +}; + +const createBuilder$1 = (self, _styler, _isEmpty) => { + // Single argument is hot path, implicit coercion is faster than anything + // eslint-disable-next-line no-implicit-coercion + const builder = (...arguments_) => applyStyle$1(builder, (arguments_.length === 1) ? ('' + arguments_[0]) : arguments_.join(' ')); + + // We alter the prototype because we must return a function, but there is + // no way to create a function with a different prototype + Object.setPrototypeOf(builder, proto$1); + + builder[GENERATOR] = self; + builder[STYLER] = _styler; + builder[IS_EMPTY] = _isEmpty; + + return builder; +}; + +const applyStyle$1 = (self, string) => { + if (self.level <= 0 || !string) { + return self[IS_EMPTY] ? '' : string; + } + + let styler = self[STYLER]; + + if (styler === undefined) { + return string; + } + + const {openAll, closeAll} = styler; + if (string.includes('\u001B')) { + while (styler !== undefined) { + // Replace any instances already present with a re-opening code + // otherwise only the part of the string until said closing code + // will be colored, and the rest will simply be 'plain'. + string = stringReplaceAll$2(string, styler.close, styler.open); + + styler = styler.parent; + } + } + + // We can move both next actions out of loop, because remaining actions in loop won't have + // any/visible effect on parts we add here. Close the styling before a linebreak and reopen + // after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92 + const lfIndex = string.indexOf('\n'); + if (lfIndex !== -1) { + string = stringEncaseCRLFWithFirstIndex$2(string, closeAll, openAll, lfIndex); + } + + return openAll + string + closeAll; +}; + +Object.defineProperties(createChalk.prototype, styles$2); + +const chalk$4 = createChalk(); +createChalk({level: stderrColor$1 ? stderrColor$1.level : 0}); + +var chalk$5 = chalk$4; + +var constants$3 = require$$0$c; + +var origCwd$1 = process.cwd; +var cwd$1 = null; + +var platform$2 = process.env.GRACEFUL_FS_PLATFORM || process.platform; + +process.cwd = function() { + if (!cwd$1) + cwd$1 = origCwd$1.call(process); + return cwd$1 +}; +try { + process.cwd(); +} catch (er) {} + +// This check is needed until node.js 12 is required +if (typeof process.chdir === 'function') { + var chdir$1 = process.chdir; + process.chdir = function (d) { + cwd$1 = null; + chdir$1.call(process, d); + }; + if (Object.setPrototypeOf) Object.setPrototypeOf(process.chdir, chdir$1); +} + +var polyfills$3 = patch$5; + +function patch$5 (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$3.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$2 === "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" || er.code === "EBUSY") + && 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$3.O_WRONLY | constants$3.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$3.O_WRONLY | constants$3.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$3.hasOwnProperty("O_SYMLINK") && fs.futimes) { + fs.lutimes = function (path, at, mt, cb) { + fs.open(path, constants$3.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$3.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$2 = Stream$3.Stream; + +var legacyStreams$1 = legacy$3; + +function legacy$3 (fs) { + return { + ReadStream: ReadStream, + WriteStream: WriteStream + } + + function ReadStream (path, options) { + if (!(this instanceof ReadStream)) return new ReadStream(path, options); + + Stream$2.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$2.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$2 = clone$c; + +var getPrototypeOf$2 = Object.getPrototypeOf || function (obj) { + return obj.__proto__ +}; + +function clone$c (obj) { + if (obj === null || typeof obj !== 'object') + return obj + + if (obj instanceof Object) + var copy = { __proto__: getPrototypeOf$2(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$f = require$$0$8; +var polyfills$2 = polyfills$3; +var legacy$2 = legacyStreams$1; +var clone$b = clone_1$2; + +var util$f = require$$0$9; + +/* istanbul ignore next - node 0.x polyfill */ +var gracefulQueue$1; +var previousSymbol$1; + +/* istanbul ignore else - node 0.x polyfill */ +if (typeof Symbol === 'function' && typeof Symbol.for === 'function') { + gracefulQueue$1 = Symbol.for('graceful-fs.queue'); + // This is used in testing by future versions + previousSymbol$1 = Symbol.for('graceful-fs.previous'); +} else { + gracefulQueue$1 = '___graceful-fs.queue'; + previousSymbol$1 = '___graceful-fs.previous'; +} + +function noop$7 () {} + +function publishQueue$1(context, queue) { + Object.defineProperty(context, gracefulQueue$1, { + get: function() { + return queue + } + }); +} + +var debug$5 = noop$7; +if (util$f.debuglog) + debug$5 = util$f.debuglog('gfs4'); +else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) + debug$5 = function() { + var m = util$f.format.apply(util$f, arguments); + m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: '); + console.error(m); + }; + +// Once time initialization +if (!fs$f[gracefulQueue$1]) { + // This queue can be shared by multiple loaded instances + var queue$2 = commonjsGlobal[gracefulQueue$1] || []; + publishQueue$1(fs$f, queue$2); + + // 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$f.close = (function (fs$close) { + function close (fd, cb) { + return fs$close.call(fs$f, fd, function (err) { + // This function uses the graceful-fs shared queue + if (!err) { + resetQueue$1(); + } + + if (typeof cb === 'function') + cb.apply(this, arguments); + }) + } + + Object.defineProperty(close, previousSymbol$1, { + value: fs$close + }); + return close + })(fs$f.close); + + fs$f.closeSync = (function (fs$closeSync) { + function closeSync (fd) { + // This function uses the graceful-fs shared queue + fs$closeSync.apply(fs$f, arguments); + resetQueue$1(); + } + + Object.defineProperty(closeSync, previousSymbol$1, { + value: fs$closeSync + }); + return closeSync + })(fs$f.closeSync); + + if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) { + process.on('exit', function() { + debug$5(fs$f[gracefulQueue$1]); + require$$5$1.equal(fs$f[gracefulQueue$1].length, 0); + }); + } +} + +if (!commonjsGlobal[gracefulQueue$1]) { + publishQueue$1(commonjsGlobal, fs$f[gracefulQueue$1]); +} + +var gracefulFs$1 = patch$4(clone$b(fs$f)); +if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs$f.__patched) { + gracefulFs$1 = patch$4(fs$f); + fs$f.__patched = true; +} + +function patch$4 (fs) { + // Everything that references the open() function needs to be in here + polyfills$2(fs); + fs.gracefulify = patch$4; + + 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$1([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$1([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$1([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$1([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$1([ + 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$2(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$1([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$1 (elem) { + debug$5('ENQUEUE', elem[0].name, elem[1]); + fs$f[gracefulQueue$1].push(elem); + retry$1(); +} + +// keep track of the timeout between retry() calls +var retryTimer$1; + +// 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$1 () { + var now = Date.now(); + for (var i = 0; i < fs$f[gracefulQueue$1].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$f[gracefulQueue$1][i].length > 2) { + fs$f[gracefulQueue$1][i][3] = now; // startTime + fs$f[gracefulQueue$1][i][4] = now; // lastTime + } + } + // call retry to make sure we're actively processing the queue + retry$1(); +} + +function retry$1 () { + // clear the timer and remove it to help prevent unintended concurrency + clearTimeout(retryTimer$1); + retryTimer$1 = undefined; + + if (fs$f[gracefulQueue$1].length === 0) + return + + var elem = fs$f[gracefulQueue$1].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$5('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$5('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$5('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$f[gracefulQueue$1].push(elem); + } + } + + // schedule our next run if one isn't already scheduled + if (retryTimer$1 === undefined) { + retryTimer$1 = setTimeout(retry$1, 0); + } +} + +var fs$g = /*@__PURE__*/getDefaultExportFromCjs(gracefulFs$1); + +const homeDirectory$1 = require$$0$7.homedir(); +const {env} = process; + +const xdgData = env.XDG_DATA_HOME || + (homeDirectory$1 ? require$$0$b.join(homeDirectory$1, '.local', 'share') : undefined); + +const xdgConfig = env.XDG_CONFIG_HOME || + (homeDirectory$1 ? require$$0$b.join(homeDirectory$1, '.config') : undefined); + +env.XDG_STATE_HOME || + (homeDirectory$1 ? require$$0$b.join(homeDirectory$1, '.local', 'state') : undefined); + +env.XDG_CACHE_HOME || (homeDirectory$1 ? require$$0$b.join(homeDirectory$1, '.cache') : undefined); + +env.XDG_RUNTIME_DIR || undefined; + +const xdgDataDirectories = (env.XDG_DATA_DIRS || '/usr/local/share/:/usr/share/').split(':'); + +if (xdgData) { + xdgDataDirectories.unshift(xdgData); +} + +const xdgConfigDirectories = (env.XDG_CONFIG_DIRS || '/etc/xdg').split(':'); + +if (xdgConfig) { + xdgConfigDirectories.unshift(xdgConfig); +} + +var writeFileAtomic$1 = {exports: {}}; + +var imurmurhash = {exports: {}}; + +/** + * @preserve + * JS Implementation of incremental MurmurHash3 (r150) (as of May 10, 2013) + * + * @author Jens Taylor + * @see http://github.com/homebrewing/brauhaus-diff + * @author Gary Court + * @see http://github.com/garycourt/murmurhash-js + * @author Austin Appleby + * @see http://sites.google.com/site/murmurhash/ + */ + +(function (module) { + (function(){ + var cache; + + // Call this function without `new` to use the cached object (good for + // single-threaded environments), or with `new` to create a new object. + // + // @param {string} key A UTF-16 or ASCII string + // @param {number} seed An optional positive integer + // @return {object} A MurmurHash3 object for incremental hashing + function MurmurHash3(key, seed) { + var m = this instanceof MurmurHash3 ? this : cache; + m.reset(seed); + if (typeof key === 'string' && key.length > 0) { + m.hash(key); + } + + if (m !== this) { + return m; + } + } + // Incrementally add a string to this hash + // + // @param {string} key A UTF-16 or ASCII string + // @return {object} this + MurmurHash3.prototype.hash = function(key) { + var h1, k1, i, top, len; + + len = key.length; + this.len += len; + + k1 = this.k1; + i = 0; + switch (this.rem) { + case 0: k1 ^= len > i ? (key.charCodeAt(i++) & 0xffff) : 0; + case 1: k1 ^= len > i ? (key.charCodeAt(i++) & 0xffff) << 8 : 0; + case 2: k1 ^= len > i ? (key.charCodeAt(i++) & 0xffff) << 16 : 0; + case 3: + k1 ^= len > i ? (key.charCodeAt(i) & 0xff) << 24 : 0; + k1 ^= len > i ? (key.charCodeAt(i++) & 0xff00) >> 8 : 0; + } + + this.rem = (len + this.rem) & 3; // & 3 is same as % 4 + len -= this.rem; + if (len > 0) { + h1 = this.h1; + while (1) { + k1 = (k1 * 0x2d51 + (k1 & 0xffff) * 0xcc9e0000) & 0xffffffff; + k1 = (k1 << 15) | (k1 >>> 17); + k1 = (k1 * 0x3593 + (k1 & 0xffff) * 0x1b870000) & 0xffffffff; + + h1 ^= k1; + h1 = (h1 << 13) | (h1 >>> 19); + h1 = (h1 * 5 + 0xe6546b64) & 0xffffffff; + + if (i >= len) { + break; + } + + k1 = ((key.charCodeAt(i++) & 0xffff)) ^ + ((key.charCodeAt(i++) & 0xffff) << 8) ^ + ((key.charCodeAt(i++) & 0xffff) << 16); + top = key.charCodeAt(i++); + k1 ^= ((top & 0xff) << 24) ^ + ((top & 0xff00) >> 8); + } + + k1 = 0; + switch (this.rem) { + case 3: k1 ^= (key.charCodeAt(i + 2) & 0xffff) << 16; + case 2: k1 ^= (key.charCodeAt(i + 1) & 0xffff) << 8; + case 1: k1 ^= (key.charCodeAt(i) & 0xffff); + } + + this.h1 = h1; + } + + this.k1 = k1; + return this; + }; + + // Get the result of this hash + // + // @return {number} The 32-bit hash + MurmurHash3.prototype.result = function() { + var k1, h1; + + k1 = this.k1; + h1 = this.h1; + + if (k1 > 0) { + k1 = (k1 * 0x2d51 + (k1 & 0xffff) * 0xcc9e0000) & 0xffffffff; + k1 = (k1 << 15) | (k1 >>> 17); + k1 = (k1 * 0x3593 + (k1 & 0xffff) * 0x1b870000) & 0xffffffff; + h1 ^= k1; + } + + h1 ^= this.len; + + h1 ^= h1 >>> 16; + h1 = (h1 * 0xca6b + (h1 & 0xffff) * 0x85eb0000) & 0xffffffff; + h1 ^= h1 >>> 13; + h1 = (h1 * 0xae35 + (h1 & 0xffff) * 0xc2b20000) & 0xffffffff; + h1 ^= h1 >>> 16; + + return h1 >>> 0; + }; + + // Reset the hash object for reuse + // + // @param {number} seed An optional positive integer + MurmurHash3.prototype.reset = function(seed) { + this.h1 = typeof seed === 'number' ? seed : 0; + this.rem = this.k1 = this.len = 0; + return this; + }; + + // A cached object to use. This can be safely used if you're in a single- + // threaded environment, otherwise you need to create new hashes to use. + cache = new MurmurHash3(); + + { + module.exports = MurmurHash3; + } + }()); +} (imurmurhash)); + +var imurmurhashExports = imurmurhash.exports; + +var signalExit$1 = {exports: {}}; + +var signals$2 = {exports: {}}; + +var hasRequiredSignals; + +function requireSignals () { + if (hasRequiredSignals) return signals$2.exports; + hasRequiredSignals = 1; + (function (module) { + // This is not the set of all possible signals. + // + // It IS, however, the set of all signals that trigger + // an exit on either Linux or BSD systems. Linux is a + // superset of the signal names supported on BSD, and + // the unknown signals just fail to register, so we can + // catch that easily enough. + // + // Don't bother with SIGKILL. It's uncatchable, which + // means that we can't fire any callbacks anyway. + // + // If a user does happen to register a handler on a non- + // fatal signal like SIGWINCH or something, and then + // exit, it'll end up firing `process.emit('exit')`, so + // the handler will be fired anyway. + // + // SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised + // artificially, inherently leave the process in a + // state from which it is not safe to try and enter JS + // listeners. + module.exports = [ + 'SIGABRT', + 'SIGALRM', + 'SIGHUP', + 'SIGINT', + 'SIGTERM' + ]; + + if (process.platform !== 'win32') { + module.exports.push( + 'SIGVTALRM', + 'SIGXCPU', + 'SIGXFSZ', + 'SIGUSR2', + 'SIGTRAP', + 'SIGSYS', + 'SIGQUIT', + 'SIGIOT' + // should detect profiler and enable/disable accordingly. + // see #21 + // 'SIGPROF' + ); + } + + if (process.platform === 'linux') { + module.exports.push( + 'SIGIO', + 'SIGPOLL', + 'SIGPWR', + 'SIGSTKFLT', + 'SIGUNUSED' + ); + } + } (signals$2)); + return signals$2.exports; +} + +// Note: since nyc uses this module to output coverage, any lines +// that are in the direct sync flow of nyc's outputCoverage are +// ignored, since we can never get coverage for them. +// grab a reference to node's real process object right away +var process$2 = commonjsGlobal.process; + +const processOk = function (process) { + return process && + typeof process === 'object' && + typeof process.removeListener === 'function' && + typeof process.emit === 'function' && + typeof process.reallyExit === 'function' && + typeof process.listeners === 'function' && + typeof process.kill === 'function' && + typeof process.pid === 'number' && + typeof process.on === 'function' +}; + +// some kind of non-node environment, just no-op +/* istanbul ignore if */ +if (!processOk(process$2)) { + signalExit$1.exports = function () { + return function () {} + }; +} else { + var assert$3 = require$$5$1; + var signals$1 = requireSignals(); + var isWin$2 = /^win/i.test(process$2.platform); + + var EE$1 = require$$2$3; + /* istanbul ignore if */ + if (typeof EE$1 !== 'function') { + EE$1 = EE$1.EventEmitter; + } + + var emitter; + if (process$2.__signal_exit_emitter__) { + emitter = process$2.__signal_exit_emitter__; + } else { + emitter = process$2.__signal_exit_emitter__ = new EE$1(); + emitter.count = 0; + emitter.emitted = {}; + } + + // Because this emitter is a global, we have to check to see if a + // previous version of this library failed to enable infinite listeners. + // I know what you're about to say. But literally everything about + // signal-exit is a compromise with evil. Get used to it. + if (!emitter.infinite) { + emitter.setMaxListeners(Infinity); + emitter.infinite = true; + } + + signalExit$1.exports = function (cb, opts) { + /* istanbul ignore if */ + if (!processOk(commonjsGlobal.process)) { + return function () {} + } + assert$3.equal(typeof cb, 'function', 'a callback must be provided for exit handler'); + + if (loaded === false) { + load$4(); + } + + var ev = 'exit'; + if (opts && opts.alwaysLast) { + ev = 'afterexit'; + } + + var remove = function () { + emitter.removeListener(ev, cb); + if (emitter.listeners('exit').length === 0 && + emitter.listeners('afterexit').length === 0) { + unload(); + } + }; + emitter.on(ev, cb); + + return remove + }; + + var unload = function unload () { + if (!loaded || !processOk(commonjsGlobal.process)) { + return + } + loaded = false; + + signals$1.forEach(function (sig) { + try { + process$2.removeListener(sig, sigListeners[sig]); + } catch (er) {} + }); + process$2.emit = originalProcessEmit; + process$2.reallyExit = originalProcessReallyExit; + emitter.count -= 1; + }; + signalExit$1.exports.unload = unload; + + var emit$1 = function emit (event, code, signal) { + /* istanbul ignore if */ + if (emitter.emitted[event]) { + return + } + emitter.emitted[event] = true; + emitter.emit(event, code, signal); + }; + + // { : , ... } + var sigListeners = {}; + signals$1.forEach(function (sig) { + sigListeners[sig] = function listener () { + /* istanbul ignore if */ + if (!processOk(commonjsGlobal.process)) { + return + } + // If there are no other listeners, an exit is coming! + // Simplest way: remove us and then re-send the signal. + // We know that this will kill the process, so we can + // safely emit now. + var listeners = process$2.listeners(sig); + if (listeners.length === emitter.count) { + unload(); + emit$1('exit', null, sig); + /* istanbul ignore next */ + emit$1('afterexit', null, sig); + /* istanbul ignore next */ + if (isWin$2 && sig === 'SIGHUP') { + // "SIGHUP" throws an `ENOSYS` error on Windows, + // so use a supported signal instead + sig = 'SIGINT'; + } + /* istanbul ignore next */ + process$2.kill(process$2.pid, sig); + } + }; + }); + + signalExit$1.exports.signals = function () { + return signals$1 + }; + + var loaded = false; + + var load$4 = function load () { + if (loaded || !processOk(commonjsGlobal.process)) { + return + } + loaded = true; + + // This is the number of onSignalExit's that are in play. + // It's important so that we can count the correct number of + // listeners on signals, and don't wait for the other one to + // handle it instead of us. + emitter.count += 1; + + signals$1 = signals$1.filter(function (sig) { + try { + process$2.on(sig, sigListeners[sig]); + return true + } catch (er) { + return false + } + }); + + process$2.emit = processEmit; + process$2.reallyExit = processReallyExit; + }; + signalExit$1.exports.load = load$4; + + var originalProcessReallyExit = process$2.reallyExit; + var processReallyExit = function processReallyExit (code) { + /* istanbul ignore if */ + if (!processOk(commonjsGlobal.process)) { + return + } + process$2.exitCode = code || /* istanbul ignore next */ 0; + emit$1('exit', process$2.exitCode, null); + /* istanbul ignore next */ + emit$1('afterexit', process$2.exitCode, null); + /* istanbul ignore next */ + originalProcessReallyExit.call(process$2, process$2.exitCode); + }; + + var originalProcessEmit = process$2.emit; + var processEmit = function processEmit (ev, arg) { + if (ev === 'exit' && processOk(commonjsGlobal.process)) { + /* istanbul ignore else */ + if (arg !== undefined) { + process$2.exitCode = arg; + } + var ret = originalProcessEmit.apply(this, arguments); + /* istanbul ignore next */ + emit$1('exit', process$2.exitCode, null); + /* istanbul ignore next */ + emit$1('afterexit', process$2.exitCode, null); + /* istanbul ignore next */ + return ret + } else { + return originalProcessEmit.apply(this, arguments) + } + }; +} + +var signalExitExports = signalExit$1.exports; +var signalExit = /*@__PURE__*/getDefaultExportFromCjs(signalExitExports); + +var isTypedarray = isTypedArray$6; +isTypedArray$6.strict = isStrictTypedArray; +isTypedArray$6.loose = isLooseTypedArray; + +var toString$5 = Object.prototype.toString; +var names$1 = { + '[object Int8Array]': true + , '[object Int16Array]': true + , '[object Int32Array]': true + , '[object Uint8Array]': true + , '[object Uint8ClampedArray]': true + , '[object Uint16Array]': true + , '[object Uint32Array]': true + , '[object Float32Array]': true + , '[object Float64Array]': true +}; + +function isTypedArray$6(arr) { + return ( + isStrictTypedArray(arr) + || isLooseTypedArray(arr) + ) +} + +function isStrictTypedArray(arr) { + return ( + arr instanceof Int8Array + || arr instanceof Int16Array + || arr instanceof Int32Array + || arr instanceof Uint8Array + || arr instanceof Uint8ClampedArray + || arr instanceof Uint16Array + || arr instanceof Uint32Array + || arr instanceof Float32Array + || arr instanceof Float64Array + ) +} + +function isLooseTypedArray(arr) { + return names$1[toString$5.call(arr)] +} + +/** + * Convert a typed array to a Buffer without a copy + * + * Author: Feross Aboukhadijeh + * License: MIT + * + * `npm install typedarray-to-buffer` + */ + +var isTypedArray$5 = isTypedarray.strict; + +var typedarrayToBuffer = function typedarrayToBuffer (arr) { + if (isTypedArray$5(arr)) { + // To avoid a copy, use the typed array's underlying ArrayBuffer to back new Buffer + var buf = Buffer.from(arr.buffer); + if (arr.byteLength !== arr.buffer.byteLength) { + // Respect the "view", i.e. byteOffset and byteLength, without doing a copy + buf = buf.slice(arr.byteOffset, arr.byteOffset + arr.byteLength); + } + return buf + } else { + // Pass through all other types to `Buffer.from` + return Buffer.from(arr) + } +}; + +writeFileAtomic$1.exports = writeFile$2; +writeFileAtomic$1.exports.sync = writeFileSync; +writeFileAtomic$1.exports._getTmpname = getTmpname; // for testing +writeFileAtomic$1.exports._cleanupOnExit = cleanupOnExit; + +const fs$e = require$$0$8; +const MurmurHash3 = imurmurhashExports; +const onExit$1 = signalExitExports; +const path$b = require$$0$b; +const isTypedArray$4 = isTypedarray; +const typedArrayToBuffer = typedarrayToBuffer; +const { promisify: promisify$1 } = require$$0$9; +const activeFiles = {}; + +// if we run inside of a worker_thread, `process.pid` is not unique +/* istanbul ignore next */ +const threadId = (function getId () { + try { + const workerThreads = require('worker_threads'); + + /// if we are in main thread, this is set to `0` + return workerThreads.threadId + } catch (e) { + // worker_threads are not available, fallback to 0 + return 0 + } +})(); + +let invocations = 0; +function getTmpname (filename) { + return filename + '.' + + MurmurHash3(__filename) + .hash(String(process.pid)) + .hash(String(threadId)) + .hash(String(++invocations)) + .result() +} + +function cleanupOnExit (tmpfile) { + return () => { + try { + fs$e.unlinkSync(typeof tmpfile === 'function' ? tmpfile() : tmpfile); + } catch (_) {} + } +} + +function serializeActiveFile (absoluteName) { + return new Promise(resolve => { + // make a queue if it doesn't already exist + if (!activeFiles[absoluteName]) activeFiles[absoluteName] = []; + + activeFiles[absoluteName].push(resolve); // add this job to the queue + if (activeFiles[absoluteName].length === 1) resolve(); // kick off the first one + }) +} + +// https://github.com/isaacs/node-graceful-fs/blob/master/polyfills.js#L315-L342 +function isChownErrOk (err) { + if (err.code === 'ENOSYS') { + return true + } + + const nonroot = !process.getuid || process.getuid() !== 0; + if (nonroot) { + if (err.code === 'EINVAL' || err.code === 'EPERM') { + return true + } + } + + return false +} + +async function writeFileAsync (filename, data, options = {}) { + if (typeof options === 'string') { + options = { encoding: options }; + } + + let fd; + let tmpfile; + /* istanbul ignore next -- The closure only gets called when onExit triggers */ + const removeOnExitHandler = onExit$1(cleanupOnExit(() => tmpfile)); + const absoluteName = path$b.resolve(filename); + + try { + await serializeActiveFile(absoluteName); + const truename = await promisify$1(fs$e.realpath)(filename).catch(() => filename); + tmpfile = getTmpname(truename); + + if (!options.mode || !options.chown) { + // Either mode or chown is not explicitly set + // Default behavior is to copy it from original file + const stats = await promisify$1(fs$e.stat)(truename).catch(() => {}); + if (stats) { + if (options.mode == null) { + options.mode = stats.mode; + } + + if (options.chown == null && process.getuid) { + options.chown = { uid: stats.uid, gid: stats.gid }; + } + } + } + + fd = await promisify$1(fs$e.open)(tmpfile, 'w', options.mode); + if (options.tmpfileCreated) { + await options.tmpfileCreated(tmpfile); + } + if (isTypedArray$4(data)) { + data = typedArrayToBuffer(data); + } + if (Buffer.isBuffer(data)) { + await promisify$1(fs$e.write)(fd, data, 0, data.length, 0); + } else if (data != null) { + await promisify$1(fs$e.write)(fd, String(data), 0, String(options.encoding || 'utf8')); + } + + if (options.fsync !== false) { + await promisify$1(fs$e.fsync)(fd); + } + + await promisify$1(fs$e.close)(fd); + fd = null; + + if (options.chown) { + await promisify$1(fs$e.chown)(tmpfile, options.chown.uid, options.chown.gid).catch(err => { + if (!isChownErrOk(err)) { + throw err + } + }); + } + + if (options.mode) { + await promisify$1(fs$e.chmod)(tmpfile, options.mode).catch(err => { + if (!isChownErrOk(err)) { + throw err + } + }); + } + + await promisify$1(fs$e.rename)(tmpfile, truename); + } finally { + if (fd) { + await promisify$1(fs$e.close)(fd).catch( + /* istanbul ignore next */ + () => {} + ); + } + removeOnExitHandler(); + await promisify$1(fs$e.unlink)(tmpfile).catch(() => {}); + activeFiles[absoluteName].shift(); // remove the element added by serializeSameFile + if (activeFiles[absoluteName].length > 0) { + activeFiles[absoluteName][0](); // start next job if one is pending + } else delete activeFiles[absoluteName]; + } +} + +function writeFile$2 (filename, data, options, callback) { + if (options instanceof Function) { + callback = options; + options = {}; + } + + const promise = writeFileAsync(filename, data, options); + if (callback) { + promise.then(callback, callback); + } + + return promise +} + +function writeFileSync (filename, data, options) { + if (typeof options === 'string') options = { encoding: options }; + else if (!options) options = {}; + try { + filename = fs$e.realpathSync(filename); + } catch (ex) { + // it's ok, it'll happen on a not yet existing file + } + const tmpfile = getTmpname(filename); + + if (!options.mode || !options.chown) { + // Either mode or chown is not explicitly set + // Default behavior is to copy it from original file + try { + const stats = fs$e.statSync(filename); + options = Object.assign({}, options); + if (!options.mode) { + options.mode = stats.mode; + } + if (!options.chown && process.getuid) { + options.chown = { uid: stats.uid, gid: stats.gid }; + } + } catch (ex) { + // ignore stat errors + } + } + + let fd; + const cleanup = cleanupOnExit(tmpfile); + const removeOnExitHandler = onExit$1(cleanup); + + let threw = true; + try { + fd = fs$e.openSync(tmpfile, 'w', options.mode || 0o666); + if (options.tmpfileCreated) { + options.tmpfileCreated(tmpfile); + } + if (isTypedArray$4(data)) { + data = typedArrayToBuffer(data); + } + if (Buffer.isBuffer(data)) { + fs$e.writeSync(fd, data, 0, data.length, 0); + } else if (data != null) { + fs$e.writeSync(fd, String(data), 0, String(options.encoding || 'utf8')); + } + if (options.fsync !== false) { + fs$e.fsyncSync(fd); + } + + fs$e.closeSync(fd); + fd = null; + + if (options.chown) { + try { + fs$e.chownSync(tmpfile, options.chown.uid, options.chown.gid); + } catch (err) { + if (!isChownErrOk(err)) { + throw err + } + } + } + + if (options.mode) { + try { + fs$e.chmodSync(tmpfile, options.mode); + } catch (err) { + if (!isChownErrOk(err)) { + throw err + } + } + } + + fs$e.renameSync(tmpfile, filename); + threw = false; + } finally { + if (fd) { + try { + fs$e.closeSync(fd); + } catch (ex) { + // ignore close errors at this stage, error may have closed fd already. + } + } + removeOnExitHandler(); + if (threw) { + cleanup(); + } + } +} + +var writeFileAtomicExports = writeFileAtomic$1.exports; +var writeFileAtomic = /*@__PURE__*/getDefaultExportFromCjs(writeFileAtomicExports); + +var isObj$1 = value => { + const type = typeof value; + return value !== null && (type === 'object' || type === 'function'); +}; + +const isObj = isObj$1; + +const disallowedKeys = new Set([ + '__proto__', + 'prototype', + 'constructor' +]); + +const isValidPath = pathSegments => !pathSegments.some(segment => disallowedKeys.has(segment)); + +function getPathSegments(path) { + const pathArray = path.split('.'); + const parts = []; + + for (let i = 0; i < pathArray.length; i++) { + let p = pathArray[i]; + + while (p[p.length - 1] === '\\' && pathArray[i + 1] !== undefined) { + p = p.slice(0, -1) + '.'; + p += pathArray[++i]; + } + + parts.push(p); + } + + if (!isValidPath(parts)) { + return []; + } + + return parts; +} + +var dotProp = { + get(object, path, value) { + if (!isObj(object) || typeof path !== 'string') { + return value === undefined ? object : value; + } + + const pathArray = getPathSegments(path); + if (pathArray.length === 0) { + return; + } + + for (let i = 0; i < pathArray.length; i++) { + object = object[pathArray[i]]; + + if (object === undefined || object === null) { + // `object` is either `undefined` or `null` so we want to stop the loop, and + // if this is not the last bit of the path, and + // if it did't return `undefined` + // it would return `null` if `object` is `null` + // but we want `get({foo: null}, 'foo.bar')` to equal `undefined`, or the supplied value, not `null` + if (i !== pathArray.length - 1) { + return value; + } + + break; + } + } + + return object === undefined ? value : object; + }, + + set(object, path, value) { + if (!isObj(object) || typeof path !== 'string') { + return object; + } + + const root = object; + const pathArray = getPathSegments(path); + + for (let i = 0; i < pathArray.length; i++) { + const p = pathArray[i]; + + if (!isObj(object[p])) { + object[p] = {}; + } + + if (i === pathArray.length - 1) { + object[p] = value; + } + + object = object[p]; + } + + return root; + }, + + delete(object, path) { + if (!isObj(object) || typeof path !== 'string') { + return false; + } + + const pathArray = getPathSegments(path); + + for (let i = 0; i < pathArray.length; i++) { + const p = pathArray[i]; + + if (i === pathArray.length - 1) { + delete object[p]; + return true; + } + + object = object[p]; + + if (!isObj(object)) { + return false; + } + } + }, + + has(object, path) { + if (!isObj(object) || typeof path !== 'string') { + return false; + } + + const pathArray = getPathSegments(path); + if (pathArray.length === 0) { + return false; + } + + // eslint-disable-next-line unicorn/no-for-loop + for (let i = 0; i < pathArray.length; i++) { + if (isObj(object)) { + if (!(pathArray[i] in object)) { + return false; + } + + object = object[pathArray[i]]; + } else { + return false; + } + } + + return true; + } +}; + +var dotProp$1 = /*@__PURE__*/getDefaultExportFromCjs(dotProp); + +const randomBytesAsync = require$$0$9.promisify(crypto.randomBytes); + +const urlSafeCharacters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~'.split(''); +const numericCharacters = '0123456789'.split(''); +const distinguishableCharacters = 'CDEHKMPRTUWXY012458'.split(''); +const asciiPrintableCharacters = '!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~'.split(''); +const alphanumericCharacters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'.split(''); + +const generateForCustomCharacters = (length, characters) => { + // Generating entropy is faster than complex math operations, so we use the simplest way + const characterCount = characters.length; + const maxValidSelector = (Math.floor(0x10000 / characterCount) * characterCount) - 1; // Using values above this will ruin distribution when using modular division + const entropyLength = 2 * Math.ceil(1.1 * length); // Generating a bit more than required so chances we need more than one pass will be really low + let string = ''; + let stringLength = 0; + + while (stringLength < length) { // In case we had many bad values, which may happen for character sets of size above 0x8000 but close to it + const entropy = crypto.randomBytes(entropyLength); + let entropyPosition = 0; + + while (entropyPosition < entropyLength && stringLength < length) { + const entropyValue = entropy.readUInt16LE(entropyPosition); + entropyPosition += 2; + if (entropyValue > maxValidSelector) { // Skip values which will ruin distribution when using modular division + continue; + } + + string += characters[entropyValue % characterCount]; + stringLength++; + } + } + + return string; +}; + +const generateForCustomCharactersAsync = async (length, characters) => { + // Generating entropy is faster than complex math operations, so we use the simplest way + const characterCount = characters.length; + const maxValidSelector = (Math.floor(0x10000 / characterCount) * characterCount) - 1; // Using values above this will ruin distribution when using modular division + const entropyLength = 2 * Math.ceil(1.1 * length); // Generating a bit more than required so chances we need more than one pass will be really low + let string = ''; + let stringLength = 0; + + while (stringLength < length) { // In case we had many bad values, which may happen for character sets of size above 0x8000 but close to it + const entropy = await randomBytesAsync(entropyLength); // eslint-disable-line no-await-in-loop + let entropyPosition = 0; + + while (entropyPosition < entropyLength && stringLength < length) { + const entropyValue = entropy.readUInt16LE(entropyPosition); + entropyPosition += 2; + if (entropyValue > maxValidSelector) { // Skip values which will ruin distribution when using modular division + continue; + } + + string += characters[entropyValue % characterCount]; + stringLength++; + } + } + + return string; +}; + +const generateRandomBytes = (byteLength, type, length) => crypto.randomBytes(byteLength).toString(type).slice(0, length); + +const generateRandomBytesAsync = async (byteLength, type, length) => { + const buffer = await randomBytesAsync(byteLength); + return buffer.toString(type).slice(0, length); +}; + +const allowedTypes = new Set([ + undefined, + 'hex', + 'base64', + 'url-safe', + 'numeric', + 'distinguishable', + 'ascii-printable', + 'alphanumeric' +]); + +const createGenerator = (generateForCustomCharacters, generateRandomBytes) => ({length, type, characters}) => { + if (!(length >= 0 && Number.isFinite(length))) { + throw new TypeError('Expected a `length` to be a non-negative finite number'); + } + + if (type !== undefined && characters !== undefined) { + throw new TypeError('Expected either `type` or `characters`'); + } + + if (characters !== undefined && typeof characters !== 'string') { + throw new TypeError('Expected `characters` to be string'); + } + + if (!allowedTypes.has(type)) { + throw new TypeError(`Unknown type: ${type}`); + } + + if (type === undefined && characters === undefined) { + type = 'hex'; + } + + if (type === 'hex' || (type === undefined && characters === undefined)) { + return generateRandomBytes(Math.ceil(length * 0.5), 'hex', length); // Need 0.5 byte entropy per character + } + + if (type === 'base64') { + return generateRandomBytes(Math.ceil(length * 0.75), 'base64', length); // Need 0.75 byte of entropy per character + } + + if (type === 'url-safe') { + return generateForCustomCharacters(length, urlSafeCharacters); + } + + if (type === 'numeric') { + return generateForCustomCharacters(length, numericCharacters); + } + + if (type === 'distinguishable') { + return generateForCustomCharacters(length, distinguishableCharacters); + } + + if (type === 'ascii-printable') { + return generateForCustomCharacters(length, asciiPrintableCharacters); + } + + if (type === 'alphanumeric') { + return generateForCustomCharacters(length, alphanumericCharacters); + } + + if (characters.length === 0) { + throw new TypeError('Expected `characters` string length to be greater than or equal to 1'); + } + + if (characters.length > 0x10000) { + throw new TypeError('Expected `characters` string length to be less or equal to 65536'); + } + + return generateForCustomCharacters(length, characters.split('')); +}; + +const cryptoRandomString = createGenerator(generateForCustomCharacters, generateRandomBytes); + +cryptoRandomString.async = createGenerator(generateForCustomCharactersAsync, generateRandomBytesAsync); + +function uniqueString() { + return cryptoRandomString({length: 32}); +} + +const configDirectory = xdgConfig || require$$0$b.join(require$$0$7.tmpdir(), uniqueString()); +const permissionError = 'You don\'t have access to this file.'; +const mkdirOptions = {mode: 0o0700, recursive: true}; +const writeFileOptions = {mode: 0o0600}; + +class Configstore { + constructor(id, defaults, options = {}) { + const pathPrefix = options.globalConfigPath ? + require$$0$b.join(id, 'config.json') : + require$$0$b.join('configstore', `${id}.json`); + + this._path = options.configPath || require$$0$b.join(configDirectory, pathPrefix); + + if (defaults) { + this.all = { + ...defaults, + ...this.all + }; + } + } + + get all() { + try { + return JSON.parse(fs$g.readFileSync(this._path, 'utf8')); + } catch (error) { + // Create directory if it doesn't exist + if (error.code === 'ENOENT') { + return {}; + } + + // Improve the message of permission errors + if (error.code === 'EACCES') { + error.message = `${error.message}\n${permissionError}\n`; + } + + // Empty the file if it encounters invalid JSON + if (error.name === 'SyntaxError') { + writeFileAtomic.sync(this._path, '', writeFileOptions); + return {}; + } + + throw error; + } + } + + set all(value) { + try { + // Make sure the folder exists as it could have been deleted in the meantime + fs$g.mkdirSync(require$$0$b.dirname(this._path), mkdirOptions); + + writeFileAtomic.sync(this._path, JSON.stringify(value, undefined, '\t'), writeFileOptions); + } catch (error) { + // Improve the message of permission errors + if (error.code === 'EACCES') { + error.message = `${error.message}\n${permissionError}\n`; + } + + throw error; + } + } + + get size() { + return Object.keys(this.all || {}).length; + } + + get(key) { + return dotProp$1.get(this.all, key); + } + + set(key, value) { + const config = this.all; + + if (arguments.length === 1) { + for (const k of Object.keys(key)) { + dotProp$1.set(config, k, key[k]); + } + } else { + dotProp$1.set(config, key, value); + } + + this.all = config; + } + + has(key) { + return dotProp$1.has(this.all, key); + } + + delete(key) { + const config = this.all; + dotProp$1.delete(config, key); + this.all = config; + } + + clear() { + this.all = {}; + } + + get path() { + return this._path; + } +} + +var re$5 = {exports: {}}; + +// 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$1 = 256; +const MAX_SAFE_INTEGER$4 = Number.MAX_SAFE_INTEGER || +/* istanbul ignore next */ 9007199254740991; + +// Max safe segment length for coercion. +const MAX_SAFE_COMPONENT_LENGTH = 16; + +// Max safe length for a build identifier. The max length minus 6 characters for +// the shortest version with a build 0.0.0+BUILD. +const MAX_SAFE_BUILD_LENGTH = MAX_LENGTH$1 - 6; + +const RELEASE_TYPES = [ + 'major', + 'premajor', + 'minor', + 'preminor', + 'patch', + 'prepatch', + 'prerelease', +]; + +var constants$2 = { + MAX_LENGTH: MAX_LENGTH$1, + MAX_SAFE_COMPONENT_LENGTH, + MAX_SAFE_BUILD_LENGTH, + MAX_SAFE_INTEGER: MAX_SAFE_INTEGER$4, + RELEASE_TYPES, + SEMVER_SPEC_VERSION, + FLAG_INCLUDE_PRERELEASE: 0b001, + FLAG_LOOSE: 0b010, +}; + +const debug$4 = ( + typeof process === 'object' && + process.env && + process.env.NODE_DEBUG && + /\bsemver\b/i.test(process.env.NODE_DEBUG) +) ? (...args) => console.error('SEMVER', ...args) + : () => {}; + +var debug_1 = debug$4; + +(function (module, exports) { + const { + MAX_SAFE_COMPONENT_LENGTH, + MAX_SAFE_BUILD_LENGTH, + MAX_LENGTH, + } = constants$2; + const debug = debug_1; + exports = module.exports = {}; + + // The actual regexps go on exports.re + const re = exports.re = []; + const safeRe = exports.safeRe = []; + const src = exports.src = []; + const t = exports.t = {}; + let R = 0; + + const LETTERDASHNUMBER = '[a-zA-Z0-9-]'; + + // Replace some greedy regex tokens to prevent regex dos issues. These regex are + // used internally via the safeRe object since all inputs in this library get + // normalized first to trim and collapse all extra whitespace. The original + // regexes are exported for userland consumption and lower level usage. A + // future breaking change could export the safer regex only with a note that + // all input should have extra whitespace removed. + const safeRegexReplacements = [ + ['\\s', 1], + ['\\d', MAX_LENGTH], + [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH], + ]; + + const makeSafeRegex = (value) => { + for (const [token, max] of safeRegexReplacements) { + value = value + .split(`${token}*`).join(`${token}{0,${max}}`) + .split(`${token}+`).join(`${token}{1,${max}}`); + } + return value + }; + + const createToken = (name, value, isGlobal) => { + const safe = makeSafeRegex(value); + const index = R++; + debug(name, index, value); + t[name] = index; + src[index] = value; + re[index] = new RegExp(value, isGlobal ? 'g' : undefined); + safeRe[index] = new RegExp(safe, 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', '\\d+'); + + // ## 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-]${LETTERDASHNUMBER}*`); + + // ## 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', `${LETTERDASHNUMBER}+`); + + // ## 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$5, re$5.exports)); + +var reExports = re$5.exports; + +// parse out just the options we care about +const looseOption = Object.freeze({ loose: true }); +const emptyOpts = Object.freeze({ }); +const parseOptions$1 = options => { + if (!options) { + return emptyOpts + } + + if (typeof options !== 'object') { + return looseOption + } + + return options +}; +var parseOptions_1 = parseOptions$1; + +const numeric = /^[0-9]+$/; +const compareIdentifiers$1 = (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$1(b, a); + +var identifiers$1 = { + compareIdentifiers: compareIdentifiers$1, + rcompareIdentifiers, +}; + +const debug$3 = debug_1; +const { MAX_LENGTH, MAX_SAFE_INTEGER: MAX_SAFE_INTEGER$3 } = constants$2; +const { safeRe: re$4, t: t$6 } = reExports; + +const parseOptions = parseOptions_1; +const { compareIdentifiers } = identifiers$1; +let SemVer$d = 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. Must be a string. Got type "${typeof version}".`) + } + + if (version.length > MAX_LENGTH) { + throw new TypeError( + `version is longer than ${MAX_LENGTH} characters` + ) + } + + debug$3('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$4[t$6.LOOSE] : re$4[t$6.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$3 || this.major < 0) { + throw new TypeError('Invalid major version') + } + + if (this.minor > MAX_SAFE_INTEGER$3 || this.minor < 0) { + throw new TypeError('Invalid minor version') + } + + if (this.patch > MAX_SAFE_INTEGER$3 || 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$3) { + 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$3('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$3('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$3('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, identifierBase) { + switch (release) { + case 'premajor': + this.prerelease.length = 0; + this.patch = 0; + this.minor = 0; + this.major++; + this.inc('pre', identifier, identifierBase); + break + case 'preminor': + this.prerelease.length = 0; + this.patch = 0; + this.minor++; + this.inc('pre', identifier, identifierBase); + 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, identifierBase); + this.inc('pre', identifier, identifierBase); + 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, identifierBase); + } + this.inc('pre', identifier, identifierBase); + 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': { + const base = Number(identifierBase) ? 1 : 0; + + if (!identifier && identifierBase === false) { + throw new Error('invalid increment argument: identifier is empty') + } + + if (this.prerelease.length === 0) { + this.prerelease = [base]; + } 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 + if (identifier === this.prerelease.join('.') && identifierBase === false) { + throw new Error('invalid increment argument: identifier already exists') + } + this.prerelease.push(base); + } + } + 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 + let prerelease = [identifier, base]; + if (identifierBase === false) { + prerelease = [identifier]; + } + if (compareIdentifiers(this.prerelease[0], identifier) === 0) { + if (isNaN(this.prerelease[1])) { + this.prerelease = prerelease; + } + } else { + this.prerelease = prerelease; + } + } + break + } + default: + throw new Error(`invalid increment argument: ${release}`) + } + this.raw = this.format(); + if (this.build.length) { + this.raw += `+${this.build.join('.')}`; + } + return this + } +}; + +var semver$2 = SemVer$d; + +const SemVer$c = semver$2; +const parse$l = (version, options, throwErrors = false) => { + if (version instanceof SemVer$c) { + return version + } + try { + return new SemVer$c(version, options) + } catch (er) { + if (!throwErrors) { + return null + } + throw er + } +}; + +var parse_1$1 = parse$l; + +const parse$k = parse_1$1; +const valid$2 = (version, options) => { + const v = parse$k(version, options); + return v ? v.version : null +}; +var valid_1 = valid$2; + +const parse$j = parse_1$1; +const clean$1 = (version, options) => { + const s = parse$j(version.trim().replace(/^[=v]+/, ''), options); + return s ? s.version : null +}; +var clean_1 = clean$1; + +const SemVer$b = semver$2; + +const inc$1 = (version, release, options, identifier, identifierBase) => { + if (typeof (options) === 'string') { + identifierBase = identifier; + identifier = options; + options = undefined; + } + + try { + return new SemVer$b( + version instanceof SemVer$b ? version.version : version, + options + ).inc(release, identifier, identifierBase).version + } catch (er) { + return null + } +}; +var inc_1 = inc$1; + +const parse$i = parse_1$1; + +const diff$1 = (version1, version2) => { + const v1 = parse$i(version1, null, true); + const v2 = parse$i(version2, null, true); + const comparison = v1.compare(v2); + + if (comparison === 0) { + return null + } + + const v1Higher = comparison > 0; + const highVersion = v1Higher ? v1 : v2; + const lowVersion = v1Higher ? v2 : v1; + const highHasPre = !!highVersion.prerelease.length; + const lowHasPre = !!lowVersion.prerelease.length; + + if (lowHasPre && !highHasPre) { + // Going from prerelease -> no prerelease requires some special casing + + // If the low version has only a major, then it will always be a major + // Some examples: + // 1.0.0-1 -> 1.0.0 + // 1.0.0-1 -> 1.1.1 + // 1.0.0-1 -> 2.0.0 + if (!lowVersion.patch && !lowVersion.minor) { + return 'major' + } + + // Otherwise it can be determined by checking the high version + + if (highVersion.patch) { + // anything higher than a patch bump would result in the wrong version + return 'patch' + } + + if (highVersion.minor) { + // anything higher than a minor bump would result in the wrong version + return 'minor' + } + + // bumping major/minor/patch all have same result + return 'major' + } + + // add the `pre` prefix if we are going to a prerelease version + const prefix = highHasPre ? 'pre' : ''; + + if (v1.major !== v2.major) { + return prefix + 'major' + } + + if (v1.minor !== v2.minor) { + return prefix + 'minor' + } + + if (v1.patch !== v2.patch) { + return prefix + 'patch' + } + + // high and low are preleases + return 'prerelease' +}; + +var diff_1 = diff$1; + +const SemVer$a = semver$2; +const major$2 = (a, loose) => new SemVer$a(a, loose).major; +var major_1 = major$2; + +const SemVer$9 = semver$2; +const minor$2 = (a, loose) => new SemVer$9(a, loose).minor; +var minor_1 = minor$2; + +const SemVer$8 = semver$2; +const patch$3 = (a, loose) => new SemVer$8(a, loose).patch; +var patch_1 = patch$3; + +const parse$h = parse_1$1; +const prerelease$1 = (version, options) => { + const parsed = parse$h(version, options); + return (parsed && parsed.prerelease.length) ? parsed.prerelease : null +}; +var prerelease_1 = prerelease$1; + +const SemVer$7 = semver$2; +const compare$f = (a, b, loose) => + new SemVer$7(a, loose).compare(new SemVer$7(b, loose)); + +var compare_1 = compare$f; + +const compare$e = compare_1; +const rcompare$1 = (a, b, loose) => compare$e(b, a, loose); +var rcompare_1 = rcompare$1; + +const compare$d = compare_1; +const compareLoose$1 = (a, b) => compare$d(a, b, true); +var compareLoose_1 = compareLoose$1; + +const SemVer$6 = semver$2; +const compareBuild$3 = (a, b, loose) => { + const versionA = new SemVer$6(a, loose); + const versionB = new SemVer$6(b, loose); + return versionA.compare(versionB) || versionA.compareBuild(versionB) +}; +var compareBuild_1 = compareBuild$3; + +const compareBuild$2 = compareBuild_1; +const sort$1 = (list, loose) => list.sort((a, b) => compareBuild$2(a, b, loose)); +var sort_1 = sort$1; + +const compareBuild$1 = compareBuild_1; +const rsort$1 = (list, loose) => list.sort((a, b) => compareBuild$1(b, a, loose)); +var rsort_1 = rsort$1; + +const compare$c = compare_1; +const gt$5 = (a, b, loose) => compare$c(a, b, loose) > 0; +var gt_1 = gt$5; + +const compare$b = compare_1; +const lt$4 = (a, b, loose) => compare$b(a, b, loose) < 0; +var lt_1 = lt$4; + +const compare$a = compare_1; +const eq$a = (a, b, loose) => compare$a(a, b, loose) === 0; +var eq_1$1 = eq$a; + +const compare$9 = compare_1; +const neq$2 = (a, b, loose) => compare$9(a, b, loose) !== 0; +var neq_1 = neq$2; + +const compare$8 = compare_1; +const gte$3 = (a, b, loose) => compare$8(a, b, loose) >= 0; +var gte_1 = gte$3; + +const compare$7 = compare_1; +const lte$3 = (a, b, loose) => compare$7(a, b, loose) <= 0; +var lte_1 = lte$3; + +const eq$9 = eq_1$1; +const neq$1 = neq_1; +const gt$4 = gt_1; +const gte$2 = gte_1; +const lt$3 = lt_1; +const lte$2 = lte_1; + +const cmp$1 = (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$9(a, b, loose) + + case '!=': + return neq$1(a, b, loose) + + case '>': + return gt$4(a, b, loose) + + case '>=': + return gte$2(a, b, loose) + + case '<': + return lt$3(a, b, loose) + + case '<=': + return lte$2(a, b, loose) + + default: + throw new TypeError(`Invalid operator: ${op}`) + } +}; +var cmp_1 = cmp$1; + +const SemVer$5 = semver$2; +const parse$g = parse_1$1; +const { safeRe: re$3, t: t$5 } = reExports; + +const coerce$1 = (version, options) => { + if (version instanceof SemVer$5) { + 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$3[t$5.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$3[t$5.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$3[t$5.COERCERTL].lastIndex = next.index + next[1].length + next[2].length; + } + // leave it in a clean state + re$3[t$5.COERCERTL].lastIndex = -1; + } + + if (match === null) { + return null + } + + return parse$g(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options) +}; +var coerce_1 = coerce$1; + +var iterator$1; +var hasRequiredIterator; + +function requireIterator () { + if (hasRequiredIterator) return iterator$1; + hasRequiredIterator = 1; + iterator$1 = function (Yallist) { + Yallist.prototype[Symbol.iterator] = function* () { + for (let walker = this.head; walker; walker = walker.next) { + yield walker.value; + } + }; + }; + return iterator$1; +} + +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; +var hasRequiredRange; + +function requireRange () { + if (hasRequiredRange) return range; + 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 reduce all whitespace as much as possible so we do not have to rely + // on potentially slow regexes like \s*. This is then stored and used for + // future error messages as well. + this.raw = range + .trim() + .split(/\s+/) + .join(' '); + + // First, split on || + this.set = this.raw + .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: ${this.raw}`) + } + + // 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) => comps.join(' ').trim()) + .join('||') + .trim(); + return this.range + } + + toString () { + return this.range + } + + parseRange (range) { + // memoize range parsing for performance. + // this is a very hot path, and fully deterministic. + const memoOpts = + (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | + (this.options.loose && FLAG_LOOSE); + const memoKey = 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); + debug('tilde trim', range); + + // `^ 1.2.3` => `^1.2.3` + range = range.replace(re[t.CARETTRIM], caretTrimReplace); + debug('caret trim', range); + + // 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 = Range; + + const LRU = requireLruCache(); + const cache = new LRU({ max: 1000 }); + + const parseOptions = parseOptions_1; + const Comparator = requireComparator(); + const debug = debug_1; + const SemVer = semver$2; + const { + safeRe: re, + t, + comparatorTrimReplace, + tildeTrimReplace, + caretTrimReplace, + } = reExports; + const { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = constants$2; + + 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) => { + return comp + .trim() + .split(/\s+/) + .map((c) => 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) => { + return comp + .trim() + .split(/\s+/) + .map((c) => 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) => 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; +} + +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; + } + } + + comp = comp.trim().split(/\s+/).join(' '); + 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 (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) + } + + options = parseOptions(options); + + // Special cases where nothing can possibly be lower + if (options.includePrerelease && + (this.value === '<0.0.0-0' || comp.value === '<0.0.0-0')) { + return false + } + if (!options.includePrerelease && + (this.value.startsWith('<0.0.0') || comp.value.startsWith('<0.0.0'))) { + return false + } + + // Same direction increasing (> or >=) + if (this.operator.startsWith('>') && comp.operator.startsWith('>')) { + return true + } + // Same direction decreasing (< or <=) + if (this.operator.startsWith('<') && comp.operator.startsWith('<')) { + return true + } + // same SemVer and both sides are inclusive (<= or >=) + if ( + (this.semver.version === comp.semver.version) && + this.operator.includes('=') && comp.operator.includes('=')) { + return true + } + // opposite directions less than + if (cmp(this.semver, '<', comp.semver, options) && + this.operator.startsWith('>') && comp.operator.startsWith('<')) { + return true + } + // opposite directions greater than + if (cmp(this.semver, '>', comp.semver, options) && + this.operator.startsWith('<') && comp.operator.startsWith('>')) { + return true + } + return false + } + } + + comparator = Comparator; + + const parseOptions = parseOptions_1; + const { safeRe: re, t } = reExports; + const cmp = cmp_1; + const debug = debug_1; + const SemVer = semver$2; + const Range = requireRange(); + return comparator; +} + +const Range$a = requireRange(); +const satisfies$4 = (version, range, options) => { + try { + range = new Range$a(range, options); + } catch (er) { + return false + } + return range.test(version) +}; +var satisfies_1 = satisfies$4; + +const Range$9 = requireRange(); + +// Mostly just for testing and legacy API reasons +const toComparators$1 = (range, options) => + new Range$9(range, options).set + .map(comp => comp.map(c => c.value).join(' ').trim().split(' ')); + +var toComparators_1 = toComparators$1; + +const SemVer$4 = semver$2; +const Range$8 = requireRange(); + +const maxSatisfying$1 = (versions, range, options) => { + let max = null; + let maxSV = null; + let rangeObj = null; + try { + rangeObj = new Range$8(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$4(max, options); + } + } + }); + return max +}; +var maxSatisfying_1 = maxSatisfying$1; + +const SemVer$3 = semver$2; +const Range$7 = requireRange(); +const minSatisfying$1 = (versions, range, options) => { + let min = null; + let minSV = null; + let rangeObj = null; + try { + rangeObj = new Range$7(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$3(min, options); + } + } + }); + return min +}; +var minSatisfying_1 = minSatisfying$1; + +const SemVer$2 = semver$2; +const Range$6 = requireRange(); +const gt$3 = gt_1; + +const minVersion$1 = (range, loose) => { + range = new Range$6(range, loose); + + let minver = new SemVer$2('0.0.0'); + if (range.test(minver)) { + return minver + } + + minver = new SemVer$2('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$2(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$3(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$3(minver, setMin))) { + minver = setMin; + } + } + + if (minver && range.test(minver)) { + return minver + } + + return null +}; +var minVersion_1 = minVersion$1; + +const Range$5 = requireRange(); +const validRange$1 = (range, options) => { + try { + // Return '*' instead of '' so that truthiness works. + // This will throw if it's invalid anyway + return new Range$5(range, options).range || '*' + } catch (er) { + return null + } +}; +var valid$1 = validRange$1; + +const SemVer$1 = semver$2; +const Comparator$2 = requireComparator(); +const { ANY: ANY$1 } = Comparator$2; +const Range$4 = requireRange(); +const satisfies$3 = satisfies_1; +const gt$2 = gt_1; +const lt$2 = lt_1; +const lte$1 = lte_1; +const gte$1 = gte_1; + +const outside$3 = (version, range, hilo, options) => { + version = new SemVer$1(version, options); + range = new Range$4(range, options); + + let gtfn, ltefn, ltfn, comp, ecomp; + switch (hilo) { + case '>': + gtfn = gt$2; + ltefn = lte$1; + ltfn = lt$2; + comp = '>'; + ecomp = '>='; + break + case '<': + gtfn = lt$2; + ltefn = gte$1; + ltfn = gt$2; + 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$3(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$1) { + comparator = new Comparator$2('>=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 +}; + +var outside_1 = outside$3; + +// Determine if version is greater than all the versions possible in the range. +const outside$2 = outside_1; +const gtr$1 = (version, range, options) => outside$2(version, range, '>', options); +var gtr_1 = gtr$1; + +const outside$1 = outside_1; +// Determine if version is less than all the versions possible in the range +const ltr$1 = (version, range, options) => outside$1(version, range, '<', options); +var ltr_1 = ltr$1; + +const Range$3 = requireRange(); +const intersects$1 = (r1, r2, options) => { + r1 = new Range$3(r1, options); + r2 = new Range$3(r2, options); + return r1.intersects(r2, options) +}; +var intersects_1 = intersects$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$2 = satisfies_1; +const compare$6 = compare_1; +var simplify = (versions, range, options) => { + const set = []; + let first = null; + let prev = null; + const v = versions.sort((a, b) => compare$6(a, b, options)); + for (const version of v) { + const included = satisfies$2(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 +}; + +const Range$2 = requireRange(); +const Comparator$1 = requireComparator(); +const { ANY } = Comparator$1; +const satisfies$1 = satisfies_1; +const compare$5 = compare_1; + +// 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$1 = (sub, dom, options = {}) => { + if (sub === dom) { + return true + } + + sub = new Range$2(sub, options); + dom = new Range$2(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 minimumVersionWithPreRelease = [new Comparator$1('>=0.0.0-0')]; +const minimumVersion = [new Comparator$1('>=0.0.0')]; + +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 = minimumVersionWithPreRelease; + } else { + sub = minimumVersion; + } + } + + if (dom.length === 1 && dom[0].semver === ANY) { + if (options.includePrerelease) { + return true + } else { + dom = minimumVersion; + } + } + + 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$5(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$1(eq, String(gt), options)) { + return null + } + + if (lt && !satisfies$1(eq, String(lt), options)) { + return null + } + + for (const c of dom) { + if (!satisfies$1(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$1(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$1(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$5(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$5(a.semver, b.semver, options); + return comp < 0 ? a + : comp > 0 ? b + : b.operator === '<' && a.operator === '<=' ? b + : a +}; + +var subset_1 = subset$1; + +// just pre-load all the stuff that index.js lazily exports +const internalRe = reExports; +const constants$1 = constants$2; +const SemVer = semver$2; +const identifiers = identifiers$1; +const parse$f = parse_1$1; +const valid = valid_1; +const clean = clean_1; +const inc = inc_1; +const diff = diff_1; +const major$1 = major_1; +const minor$1 = minor_1; +const patch$2 = patch_1; +const prerelease = prerelease_1; +const compare$4 = compare_1; +const rcompare = rcompare_1; +const compareLoose = compareLoose_1; +const compareBuild = compareBuild_1; +const sort = sort_1; +const rsort = rsort_1; +const gt$1 = gt_1; +const lt$1 = lt_1; +const eq$8 = eq_1$1; +const neq = neq_1; +const gte = gte_1; +const lte = lte_1; +const cmp = cmp_1; +const coerce = coerce_1; +const Comparator = requireComparator(); +const Range$1 = requireRange(); +const satisfies = satisfies_1; +const toComparators = toComparators_1; +const maxSatisfying = maxSatisfying_1; +const minSatisfying = minSatisfying_1; +const minVersion = minVersion_1; +const validRange = valid$1; +const outside = outside_1; +const gtr = gtr_1; +const ltr = ltr_1; +const intersects = intersects_1; +const simplifyRange = simplify; +const subset = subset_1; +var semver = { + parse: parse$f, + valid, + clean, + inc, + diff, + major: major$1, + minor: minor$1, + patch: patch$2, + prerelease, + compare: compare$4, + rcompare, + compareLoose, + compareBuild, + sort, + rsort, + gt: gt$1, + lt: lt$1, + eq: eq$8, + neq, + gte, + lte, + cmp, + coerce, + Comparator, + Range: Range$1, + 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$1.SEMVER_SPEC_VERSION, + RELEASE_TYPES: constants$1.RELEASE_TYPES, + compareIdentifiers: identifiers.compareIdentifiers, + rcompareIdentifiers: identifiers.rcompareIdentifiers, +}; + +var semver$1 = /*@__PURE__*/getDefaultExportFromCjs(semver); + +function semverDiff(versionA, versionB) { + versionA = semver$1.parse(versionA); + versionB = semver$1.parse(versionB); + + if (semver$1.compareBuild(versionA, versionB) >= 0) { + return; + } + + return semver$1.diff(versionA, versionB) || 'build'; +} + +const typedArrayTypeNames = [ + 'Int8Array', + 'Uint8Array', + 'Uint8ClampedArray', + 'Int16Array', + 'Uint16Array', + 'Int32Array', + 'Uint32Array', + 'Float32Array', + 'Float64Array', + 'BigInt64Array', + 'BigUint64Array', +]; +function isTypedArrayName(name) { + return typedArrayTypeNames.includes(name); +} +const objectTypeNames = [ + 'Function', + 'Generator', + 'AsyncGenerator', + 'GeneratorFunction', + 'AsyncGeneratorFunction', + 'AsyncFunction', + 'Observable', + 'Array', + 'Buffer', + 'Blob', + 'Object', + 'RegExp', + 'Date', + 'Error', + 'Map', + 'Set', + 'WeakMap', + 'WeakSet', + 'WeakRef', + 'ArrayBuffer', + 'SharedArrayBuffer', + 'DataView', + 'Promise', + 'URL', + 'FormData', + 'URLSearchParams', + 'HTMLElement', + 'NaN', + ...typedArrayTypeNames, +]; +function isObjectTypeName(name) { + return objectTypeNames.includes(name); +} +const primitiveTypeNames = [ + 'null', + 'undefined', + 'string', + 'number', + 'bigint', + 'boolean', + 'symbol', +]; +function isPrimitiveTypeName(name) { + return primitiveTypeNames.includes(name); +} +// eslint-disable-next-line @typescript-eslint/ban-types +function isOfType(type) { + return (value) => typeof value === type; +} +const { toString: toString$4 } = Object.prototype; +const getObjectType = (value) => { + const objectTypeName = toString$4.call(value).slice(8, -1); + if (/HTML\w+Element/.test(objectTypeName) && is$5.domElement(value)) { + return 'HTMLElement'; + } + if (isObjectTypeName(objectTypeName)) { + return objectTypeName; + } + return undefined; +}; +const isObjectOfType = (type) => (value) => getObjectType(value) === type; +function is$5(value) { + if (value === null) { + return 'null'; + } + switch (typeof value) { + case 'undefined': { + return 'undefined'; + } + case 'string': { + return 'string'; + } + case 'number': { + return Number.isNaN(value) ? 'NaN' : 'number'; + } + case 'boolean': { + return 'boolean'; + } + case 'function': { + return 'Function'; + } + case 'bigint': { + return 'bigint'; + } + case 'symbol': { + return 'symbol'; + } + } + if (is$5.observable(value)) { + return 'Observable'; + } + if (is$5.array(value)) { + return 'Array'; + } + if (is$5.buffer(value)) { + return 'Buffer'; + } + const tagType = getObjectType(value); + if (tagType) { + return tagType; + } + if (value instanceof String || value instanceof Boolean || value instanceof Number) { + throw new TypeError('Please don\'t use object wrappers for primitive types'); + } + return 'Object'; +} +is$5.undefined = isOfType('undefined'); +is$5.string = isOfType('string'); +const isNumberType = isOfType('number'); +is$5.number = (value) => isNumberType(value) && !is$5.nan(value); +is$5.positiveNumber = (value) => is$5.number(value) && value > 0; +is$5.negativeNumber = (value) => is$5.number(value) && value < 0; +is$5.bigint = isOfType('bigint'); +// eslint-disable-next-line @typescript-eslint/ban-types +is$5.function_ = isOfType('function'); +// eslint-disable-next-line @typescript-eslint/ban-types +is$5.null_ = (value) => value === null; +is$5.class_ = (value) => is$5.function_(value) && value.toString().startsWith('class '); +is$5.boolean = (value) => value === true || value === false; +is$5.symbol = isOfType('symbol'); +is$5.numericString = (value) => is$5.string(value) && !is$5.emptyStringOrWhitespace(value) && !Number.isNaN(Number(value)); +is$5.array = (value, assertion) => { + if (!Array.isArray(value)) { + return false; + } + if (!is$5.function_(assertion)) { + return true; + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument + return value.every(element => assertion(element)); +}; +// eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-call +is$5.buffer = (value) => value?.constructor?.isBuffer?.(value) ?? false; +is$5.blob = (value) => isObjectOfType('Blob')(value); +is$5.nullOrUndefined = (value) => is$5.null_(value) || is$5.undefined(value); // eslint-disable-line @typescript-eslint/ban-types +is$5.object = (value) => !is$5.null_(value) && (typeof value === 'object' || is$5.function_(value)); // eslint-disable-line @typescript-eslint/ban-types +is$5.iterable = (value) => is$5.function_(value?.[Symbol.iterator]); +is$5.asyncIterable = (value) => is$5.function_(value?.[Symbol.asyncIterator]); +is$5.generator = (value) => is$5.iterable(value) && is$5.function_(value?.next) && is$5.function_(value?.throw); +is$5.asyncGenerator = (value) => is$5.asyncIterable(value) && is$5.function_(value.next) && is$5.function_(value.throw); +is$5.nativePromise = (value) => isObjectOfType('Promise')(value); +const hasPromiseApi = (value) => is$5.function_(value?.then) + && is$5.function_(value?.catch); +is$5.promise = (value) => is$5.nativePromise(value) || hasPromiseApi(value); +is$5.generatorFunction = isObjectOfType('GeneratorFunction'); +is$5.asyncGeneratorFunction = (value) => getObjectType(value) === 'AsyncGeneratorFunction'; +is$5.asyncFunction = (value) => getObjectType(value) === 'AsyncFunction'; +// eslint-disable-next-line no-prototype-builtins, @typescript-eslint/ban-types +is$5.boundFunction = (value) => is$5.function_(value) && !value.hasOwnProperty('prototype'); +is$5.regExp = isObjectOfType('RegExp'); +is$5.date = isObjectOfType('Date'); +is$5.error = isObjectOfType('Error'); +is$5.map = (value) => isObjectOfType('Map')(value); +is$5.set = (value) => isObjectOfType('Set')(value); +is$5.weakMap = (value) => isObjectOfType('WeakMap')(value); // eslint-disable-line @typescript-eslint/ban-types +is$5.weakSet = (value) => isObjectOfType('WeakSet')(value); // eslint-disable-line @typescript-eslint/ban-types +is$5.weakRef = (value) => isObjectOfType('WeakRef')(value); // eslint-disable-line @typescript-eslint/ban-types +is$5.int8Array = isObjectOfType('Int8Array'); +is$5.uint8Array = isObjectOfType('Uint8Array'); +is$5.uint8ClampedArray = isObjectOfType('Uint8ClampedArray'); +is$5.int16Array = isObjectOfType('Int16Array'); +is$5.uint16Array = isObjectOfType('Uint16Array'); +is$5.int32Array = isObjectOfType('Int32Array'); +is$5.uint32Array = isObjectOfType('Uint32Array'); +is$5.float32Array = isObjectOfType('Float32Array'); +is$5.float64Array = isObjectOfType('Float64Array'); +is$5.bigInt64Array = isObjectOfType('BigInt64Array'); +is$5.bigUint64Array = isObjectOfType('BigUint64Array'); +is$5.arrayBuffer = isObjectOfType('ArrayBuffer'); +is$5.sharedArrayBuffer = isObjectOfType('SharedArrayBuffer'); +is$5.dataView = isObjectOfType('DataView'); +// eslint-disable-next-line @typescript-eslint/no-unsafe-argument +is$5.enumCase = (value, targetEnum) => Object.values(targetEnum).includes(value); +is$5.directInstanceOf = (instance, class_) => Object.getPrototypeOf(instance) === class_.prototype; +is$5.urlInstance = (value) => isObjectOfType('URL')(value); +is$5.urlString = (value) => { + if (!is$5.string(value)) { + return false; + } + try { + new URL(value); // eslint-disable-line no-new + return true; + } + catch { + return false; + } +}; +// Example: `is.truthy = (value: unknown): value is (not false | not 0 | not '' | not undefined | not null) => Boolean(value);` +is$5.truthy = (value) => Boolean(value); // eslint-disable-line unicorn/prefer-native-coercion-functions +// Example: `is.falsy = (value: unknown): value is (not true | 0 | '' | undefined | null) => Boolean(value);` +is$5.falsy = (value) => !value; +is$5.nan = (value) => Number.isNaN(value); +is$5.primitive = (value) => is$5.null_(value) || isPrimitiveTypeName(typeof value); +is$5.integer = (value) => Number.isInteger(value); +is$5.safeInteger = (value) => Number.isSafeInteger(value); +is$5.plainObject = (value) => { + // From: https://github.com/sindresorhus/is-plain-obj/blob/main/index.js + if (typeof value !== 'object' || value === null) { + return false; + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + const prototype = Object.getPrototypeOf(value); + return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in value) && !(Symbol.iterator in value); +}; +is$5.typedArray = (value) => isTypedArrayName(getObjectType(value)); +const isValidLength = (value) => is$5.safeInteger(value) && value >= 0; +is$5.arrayLike = (value) => !is$5.nullOrUndefined(value) && !is$5.function_(value) && isValidLength(value.length); +is$5.tupleLike = (value, guards) => { + if (is$5.array(guards) && is$5.array(value) && guards.length === value.length) { + return guards.every((guard, index) => guard(value[index])); + } + return false; +}; +is$5.inRange = (value, range) => { + if (is$5.number(range)) { + return value >= Math.min(0, range) && value <= Math.max(range, 0); + } + if (is$5.array(range) && range.length === 2) { + return value >= Math.min(...range) && value <= Math.max(...range); + } + throw new TypeError(`Invalid range: ${JSON.stringify(range)}`); +}; +// eslint-disable-next-line @typescript-eslint/naming-convention +const NODE_TYPE_ELEMENT = 1; +// eslint-disable-next-line @typescript-eslint/naming-convention +const DOM_PROPERTIES_TO_CHECK = [ + 'innerHTML', + 'ownerDocument', + 'style', + 'attributes', + 'nodeValue', +]; +is$5.domElement = (value) => is$5.object(value) + && value.nodeType === NODE_TYPE_ELEMENT + && is$5.string(value.nodeName) + && !is$5.plainObject(value) + && DOM_PROPERTIES_TO_CHECK.every(property => property in value); +is$5.observable = (value) => { + if (!value) { + return false; + } + // eslint-disable-next-line no-use-extend-native/no-use-extend-native, @typescript-eslint/no-unsafe-call + if (value === value[Symbol.observable]?.()) { + return true; + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-call + if (value === value['@@observable']?.()) { + return true; + } + return false; +}; +is$5.nodeStream = (value) => is$5.object(value) && is$5.function_(value.pipe) && !is$5.observable(value); +is$5.infinite = (value) => value === Number.POSITIVE_INFINITY || value === Number.NEGATIVE_INFINITY; +const isAbsoluteMod2 = (remainder) => (value) => is$5.integer(value) && Math.abs(value % 2) === remainder; +is$5.evenInteger = isAbsoluteMod2(0); +is$5.oddInteger = isAbsoluteMod2(1); +is$5.emptyArray = (value) => is$5.array(value) && value.length === 0; +is$5.nonEmptyArray = (value) => is$5.array(value) && value.length > 0; +is$5.emptyString = (value) => is$5.string(value) && value.length === 0; +const isWhiteSpaceString = (value) => is$5.string(value) && !/\S/.test(value); +is$5.emptyStringOrWhitespace = (value) => is$5.emptyString(value) || isWhiteSpaceString(value); +// TODO: Use `not ''` when the `not` operator is available. +is$5.nonEmptyString = (value) => is$5.string(value) && value.length > 0; +// TODO: Use `not ''` when the `not` operator is available. +is$5.nonEmptyStringAndNotWhitespace = (value) => is$5.string(value) && !is$5.emptyStringOrWhitespace(value); +// eslint-disable-next-line unicorn/no-array-callback-reference +is$5.emptyObject = (value) => is$5.object(value) && !is$5.map(value) && !is$5.set(value) && Object.keys(value).length === 0; +// TODO: Use `not` operator here to remove `Map` and `Set` from type guard: +// - https://github.com/Microsoft/TypeScript/pull/29317 +// eslint-disable-next-line unicorn/no-array-callback-reference +is$5.nonEmptyObject = (value) => is$5.object(value) && !is$5.map(value) && !is$5.set(value) && Object.keys(value).length > 0; +is$5.emptySet = (value) => is$5.set(value) && value.size === 0; +is$5.nonEmptySet = (value) => is$5.set(value) && value.size > 0; +// eslint-disable-next-line unicorn/no-array-callback-reference +is$5.emptyMap = (value) => is$5.map(value) && value.size === 0; +// eslint-disable-next-line unicorn/no-array-callback-reference +is$5.nonEmptyMap = (value) => is$5.map(value) && value.size > 0; +// `PropertyKey` is any value that can be used as an object key (string, number, or symbol) +is$5.propertyKey = (value) => is$5.any([is$5.string, is$5.number, is$5.symbol], value); +is$5.formData = (value) => isObjectOfType('FormData')(value); +is$5.urlSearchParams = (value) => isObjectOfType('URLSearchParams')(value); +const predicateOnArray = (method, predicate, values) => { + if (!is$5.function_(predicate)) { + throw new TypeError(`Invalid predicate: ${JSON.stringify(predicate)}`); + } + if (values.length === 0) { + throw new TypeError('Invalid number of values'); + } + return method.call(values, predicate); +}; +is$5.any = (predicate, ...values) => { + const predicates = is$5.array(predicate) ? predicate : [predicate]; + return predicates.some(singlePredicate => predicateOnArray(Array.prototype.some, singlePredicate, values)); +}; +is$5.all = (predicate, ...values) => predicateOnArray(Array.prototype.every, predicate, values); +const assertType = (condition, description, value, options = {}) => { + if (!condition) { + const { multipleValues } = options; + const valuesMessage = multipleValues + ? `received values of types ${[ + ...new Set(value.map(singleValue => `\`${is$5(singleValue)}\``)), + ].join(', ')}` + : `received value of type \`${is$5(value)}\``; + throw new TypeError(`Expected value which is \`${description}\`, ${valuesMessage}.`); + } +}; +/* eslint-disable @typescript-eslint/no-confusing-void-expression */ +const assert$2 = { + // Unknowns. + undefined: (value) => assertType(is$5.undefined(value), 'undefined', value), + string: (value) => assertType(is$5.string(value), 'string', value), + number: (value) => assertType(is$5.number(value), 'number', value), + positiveNumber: (value) => assertType(is$5.positiveNumber(value), "positive number" /* AssertionTypeDescription.positiveNumber */, value), + negativeNumber: (value) => assertType(is$5.negativeNumber(value), "negative number" /* AssertionTypeDescription.negativeNumber */, value), + bigint: (value) => assertType(is$5.bigint(value), 'bigint', value), + // eslint-disable-next-line @typescript-eslint/ban-types + function_: (value) => assertType(is$5.function_(value), 'Function', value), + null_: (value) => assertType(is$5.null_(value), 'null', value), + class_: (value) => assertType(is$5.class_(value), "Class" /* AssertionTypeDescription.class_ */, value), + boolean: (value) => assertType(is$5.boolean(value), 'boolean', value), + symbol: (value) => assertType(is$5.symbol(value), 'symbol', value), + numericString: (value) => assertType(is$5.numericString(value), "string with a number" /* AssertionTypeDescription.numericString */, value), + array: (value, assertion) => { + const assert = assertType; + assert(is$5.array(value), 'Array', value); + if (assertion) { + // eslint-disable-next-line unicorn/no-array-for-each, unicorn/no-array-callback-reference + value.forEach(assertion); + } + }, + buffer: (value) => assertType(is$5.buffer(value), 'Buffer', value), + blob: (value) => assertType(is$5.blob(value), 'Blob', value), + nullOrUndefined: (value) => assertType(is$5.nullOrUndefined(value), "null or undefined" /* AssertionTypeDescription.nullOrUndefined */, value), + object: (value) => assertType(is$5.object(value), 'Object', value), + iterable: (value) => assertType(is$5.iterable(value), "Iterable" /* AssertionTypeDescription.iterable */, value), + asyncIterable: (value) => assertType(is$5.asyncIterable(value), "AsyncIterable" /* AssertionTypeDescription.asyncIterable */, value), + generator: (value) => assertType(is$5.generator(value), 'Generator', value), + asyncGenerator: (value) => assertType(is$5.asyncGenerator(value), 'AsyncGenerator', value), + nativePromise: (value) => assertType(is$5.nativePromise(value), "native Promise" /* AssertionTypeDescription.nativePromise */, value), + promise: (value) => assertType(is$5.promise(value), 'Promise', value), + generatorFunction: (value) => assertType(is$5.generatorFunction(value), 'GeneratorFunction', value), + asyncGeneratorFunction: (value) => assertType(is$5.asyncGeneratorFunction(value), 'AsyncGeneratorFunction', value), + // eslint-disable-next-line @typescript-eslint/ban-types + asyncFunction: (value) => assertType(is$5.asyncFunction(value), 'AsyncFunction', value), + // eslint-disable-next-line @typescript-eslint/ban-types + boundFunction: (value) => assertType(is$5.boundFunction(value), 'Function', value), + regExp: (value) => assertType(is$5.regExp(value), 'RegExp', value), + date: (value) => assertType(is$5.date(value), 'Date', value), + error: (value) => assertType(is$5.error(value), 'Error', value), + map: (value) => assertType(is$5.map(value), 'Map', value), + set: (value) => assertType(is$5.set(value), 'Set', value), + weakMap: (value) => assertType(is$5.weakMap(value), 'WeakMap', value), + weakSet: (value) => assertType(is$5.weakSet(value), 'WeakSet', value), + weakRef: (value) => assertType(is$5.weakRef(value), 'WeakRef', value), + int8Array: (value) => assertType(is$5.int8Array(value), 'Int8Array', value), + uint8Array: (value) => assertType(is$5.uint8Array(value), 'Uint8Array', value), + uint8ClampedArray: (value) => assertType(is$5.uint8ClampedArray(value), 'Uint8ClampedArray', value), + int16Array: (value) => assertType(is$5.int16Array(value), 'Int16Array', value), + uint16Array: (value) => assertType(is$5.uint16Array(value), 'Uint16Array', value), + int32Array: (value) => assertType(is$5.int32Array(value), 'Int32Array', value), + uint32Array: (value) => assertType(is$5.uint32Array(value), 'Uint32Array', value), + float32Array: (value) => assertType(is$5.float32Array(value), 'Float32Array', value), + float64Array: (value) => assertType(is$5.float64Array(value), 'Float64Array', value), + bigInt64Array: (value) => assertType(is$5.bigInt64Array(value), 'BigInt64Array', value), + bigUint64Array: (value) => assertType(is$5.bigUint64Array(value), 'BigUint64Array', value), + arrayBuffer: (value) => assertType(is$5.arrayBuffer(value), 'ArrayBuffer', value), + sharedArrayBuffer: (value) => assertType(is$5.sharedArrayBuffer(value), 'SharedArrayBuffer', value), + dataView: (value) => assertType(is$5.dataView(value), 'DataView', value), + enumCase: (value, targetEnum) => assertType(is$5.enumCase(value, targetEnum), 'EnumCase', value), + urlInstance: (value) => assertType(is$5.urlInstance(value), 'URL', value), + urlString: (value) => assertType(is$5.urlString(value), "string with a URL" /* AssertionTypeDescription.urlString */, value), + truthy: (value) => assertType(is$5.truthy(value), "truthy" /* AssertionTypeDescription.truthy */, value), + falsy: (value) => assertType(is$5.falsy(value), "falsy" /* AssertionTypeDescription.falsy */, value), + nan: (value) => assertType(is$5.nan(value), "NaN" /* AssertionTypeDescription.nan */, value), + primitive: (value) => assertType(is$5.primitive(value), "primitive" /* AssertionTypeDescription.primitive */, value), + integer: (value) => assertType(is$5.integer(value), "integer" /* AssertionTypeDescription.integer */, value), + safeInteger: (value) => assertType(is$5.safeInteger(value), "integer" /* AssertionTypeDescription.safeInteger */, value), + plainObject: (value) => assertType(is$5.plainObject(value), "plain object" /* AssertionTypeDescription.plainObject */, value), + typedArray: (value) => assertType(is$5.typedArray(value), "TypedArray" /* AssertionTypeDescription.typedArray */, value), + arrayLike: (value) => assertType(is$5.arrayLike(value), "array-like" /* AssertionTypeDescription.arrayLike */, value), + tupleLike: (value, guards) => assertType(is$5.tupleLike(value, guards), "tuple-like" /* AssertionTypeDescription.tupleLike */, value), + domElement: (value) => assertType(is$5.domElement(value), "HTMLElement" /* AssertionTypeDescription.domElement */, value), + observable: (value) => assertType(is$5.observable(value), 'Observable', value), + nodeStream: (value) => assertType(is$5.nodeStream(value), "Node.js Stream" /* AssertionTypeDescription.nodeStream */, value), + infinite: (value) => assertType(is$5.infinite(value), "infinite number" /* AssertionTypeDescription.infinite */, value), + emptyArray: (value) => assertType(is$5.emptyArray(value), "empty array" /* AssertionTypeDescription.emptyArray */, value), + nonEmptyArray: (value) => assertType(is$5.nonEmptyArray(value), "non-empty array" /* AssertionTypeDescription.nonEmptyArray */, value), + emptyString: (value) => assertType(is$5.emptyString(value), "empty string" /* AssertionTypeDescription.emptyString */, value), + emptyStringOrWhitespace: (value) => assertType(is$5.emptyStringOrWhitespace(value), "empty string or whitespace" /* AssertionTypeDescription.emptyStringOrWhitespace */, value), + nonEmptyString: (value) => assertType(is$5.nonEmptyString(value), "non-empty string" /* AssertionTypeDescription.nonEmptyString */, value), + nonEmptyStringAndNotWhitespace: (value) => assertType(is$5.nonEmptyStringAndNotWhitespace(value), "non-empty string and not whitespace" /* AssertionTypeDescription.nonEmptyStringAndNotWhitespace */, value), + emptyObject: (value) => assertType(is$5.emptyObject(value), "empty object" /* AssertionTypeDescription.emptyObject */, value), + nonEmptyObject: (value) => assertType(is$5.nonEmptyObject(value), "non-empty object" /* AssertionTypeDescription.nonEmptyObject */, value), + emptySet: (value) => assertType(is$5.emptySet(value), "empty set" /* AssertionTypeDescription.emptySet */, value), + nonEmptySet: (value) => assertType(is$5.nonEmptySet(value), "non-empty set" /* AssertionTypeDescription.nonEmptySet */, value), + emptyMap: (value) => assertType(is$5.emptyMap(value), "empty map" /* AssertionTypeDescription.emptyMap */, value), + nonEmptyMap: (value) => assertType(is$5.nonEmptyMap(value), "non-empty map" /* AssertionTypeDescription.nonEmptyMap */, value), + propertyKey: (value) => assertType(is$5.propertyKey(value), 'PropertyKey', value), + formData: (value) => assertType(is$5.formData(value), 'FormData', value), + urlSearchParams: (value) => assertType(is$5.urlSearchParams(value), 'URLSearchParams', value), + // Numbers. + evenInteger: (value) => assertType(is$5.evenInteger(value), "even integer" /* AssertionTypeDescription.evenInteger */, value), + oddInteger: (value) => assertType(is$5.oddInteger(value), "odd integer" /* AssertionTypeDescription.oddInteger */, value), + // Two arguments. + directInstanceOf: (instance, class_) => assertType(is$5.directInstanceOf(instance, class_), "T" /* AssertionTypeDescription.directInstanceOf */, instance), + inRange: (value, range) => assertType(is$5.inRange(value, range), "in range" /* AssertionTypeDescription.inRange */, value), + // Variadic functions. + any: (predicate, ...values) => assertType(is$5.any(predicate, ...values), "predicate returns truthy for any value" /* AssertionTypeDescription.any */, values, { multipleValues: true }), + all: (predicate, ...values) => assertType(is$5.all(predicate, ...values), "predicate returns truthy for all values" /* AssertionTypeDescription.all */, values, { multipleValues: true }), +}; +/* eslint-enable @typescript-eslint/no-confusing-void-expression */ +// Some few keywords are reserved, but we'll populate them for Node.js users +// See https://github.com/Microsoft/TypeScript/issues/2536 +Object.defineProperties(is$5, { + class: { + value: is$5.class_, + }, + function: { + value: is$5.function_, + }, + null: { + value: is$5.null_, + }, +}); +Object.defineProperties(assert$2, { + class: { + value: assert$2.class_, + }, + function: { + value: assert$2.function_, + }, + null: { + value: assert$2.null_, + }, +}); + +let CancelError$1 = class CancelError extends Error { + constructor(reason) { + super(reason || 'Promise was canceled'); + this.name = 'CancelError'; + } + + get isCanceled() { + return true; + } +}; + +// TODO: Use private class fields when ESLint 8 is out. + +class PCancelable { + static fn(userFunction) { + return (...arguments_) => { + return new PCancelable((resolve, reject, onCancel) => { + arguments_.push(onCancel); + // eslint-disable-next-line promise/prefer-await-to-then + userFunction(...arguments_).then(resolve, reject); + }); + }; + } + + constructor(executor) { + this._cancelHandlers = []; + this._isPending = true; + this._isCanceled = false; + this._rejectOnCancel = true; + + this._promise = new Promise((resolve, reject) => { + this._reject = reject; + + const onResolve = value => { + if (!this._isCanceled || !onCancel.shouldReject) { + this._isPending = false; + resolve(value); + } + }; + + const onReject = error => { + this._isPending = false; + reject(error); + }; + + const onCancel = handler => { + if (!this._isPending) { + throw new Error('The `onCancel` handler was attached after the promise settled.'); + } + + this._cancelHandlers.push(handler); + }; + + Object.defineProperties(onCancel, { + shouldReject: { + get: () => this._rejectOnCancel, + set: boolean => { + this._rejectOnCancel = boolean; + } + } + }); + + executor(onResolve, onReject, onCancel); + }); + } + + then(onFulfilled, onRejected) { + // eslint-disable-next-line promise/prefer-await-to-then + return this._promise.then(onFulfilled, onRejected); + } + + catch(onRejected) { + // eslint-disable-next-line promise/prefer-await-to-then + return this._promise.catch(onRejected); + } + + finally(onFinally) { + // eslint-disable-next-line promise/prefer-await-to-then + return this._promise.finally(onFinally); + } + + cancel(reason) { + if (!this._isPending || this._isCanceled) { + return; + } + + this._isCanceled = true; + + if (this._cancelHandlers.length > 0) { + try { + for (const handler of this._cancelHandlers) { + handler(); + } + } catch (error) { + this._reject(error); + return; + } + } + + if (this._rejectOnCancel) { + this._reject(new CancelError$1(reason)); + } + } + + get isCanceled() { + return this._isCanceled; + } +} + +Object.setPrototypeOf(PCancelable.prototype, Promise.prototype); + +// A hacky check to prevent circular references. +function isRequest$3(x) { + return is$5.object(x) && '_onResponse' in x; +} +/** +An error to be thrown when a request fails. +Contains a `code` property with error class code, like `ECONNREFUSED`. +*/ +let RequestError$1 = class RequestError extends Error { + constructor(message, error, self) { + super(message); + Object.defineProperty(this, "input", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "code", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "stack", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "response", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "request", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "timings", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Error.captureStackTrace(this, this.constructor); + this.name = 'RequestError'; + this.code = error.code ?? 'ERR_GOT_REQUEST_ERROR'; + this.input = error.input; + if (isRequest$3(self)) { + Object.defineProperty(this, 'request', { + enumerable: false, + value: self, + }); + Object.defineProperty(this, 'response', { + enumerable: false, + value: self.response, + }); + this.options = self.options; + } + else { + this.options = self; + } + this.timings = this.request?.timings; + // Recover the original stacktrace + if (is$5.string(error.stack) && is$5.string(this.stack)) { + const indexOfMessage = this.stack.indexOf(this.message) + this.message.length; + const thisStackTrace = this.stack.slice(indexOfMessage).split('\n').reverse(); + const errorStackTrace = error.stack.slice(error.stack.indexOf(error.message) + error.message.length).split('\n').reverse(); + // Remove duplicated traces + while (errorStackTrace.length > 0 && errorStackTrace[0] === thisStackTrace[0]) { + thisStackTrace.shift(); + } + this.stack = `${this.stack.slice(0, indexOfMessage)}${thisStackTrace.reverse().join('\n')}${errorStackTrace.reverse().join('\n')}`; + } + } +}; +/** +An error to be thrown when the server redirects you more than ten times. +Includes a `response` property. +*/ +class MaxRedirectsError extends RequestError$1 { + constructor(request) { + super(`Redirected ${request.options.maxRedirects} times. Aborting.`, {}, request); + this.name = 'MaxRedirectsError'; + this.code = 'ERR_TOO_MANY_REDIRECTS'; + } +} +/** +An error to be thrown when the server response code is not 2xx nor 3xx if `options.followRedirect` is `true`, but always except for 304. +Includes a `response` property. +*/ +// eslint-disable-next-line @typescript-eslint/naming-convention +class HTTPError extends RequestError$1 { + constructor(response) { + super(`Response code ${response.statusCode} (${response.statusMessage})`, {}, response.request); + this.name = 'HTTPError'; + this.code = 'ERR_NON_2XX_3XX_RESPONSE'; + } +} +/** +An error to be thrown when a cache method fails. +For example, if the database goes down or there's a filesystem error. +*/ +let CacheError$1 = class CacheError extends RequestError$1 { + constructor(error, request) { + super(error.message, error, request); + this.name = 'CacheError'; + this.code = this.code === 'ERR_GOT_REQUEST_ERROR' ? 'ERR_CACHE_ACCESS' : this.code; + } +}; +/** +An error to be thrown when the request body is a stream and an error occurs while reading from that stream. +*/ +class UploadError extends RequestError$1 { + constructor(error, request) { + super(error.message, error, request); + this.name = 'UploadError'; + this.code = this.code === 'ERR_GOT_REQUEST_ERROR' ? 'ERR_UPLOAD' : this.code; + } +} +/** +An error to be thrown when the request is aborted due to a timeout. +Includes an `event` and `timings` property. +*/ +let TimeoutError$1 = class TimeoutError extends RequestError$1 { + constructor(error, timings, request) { + super(error.message, error, request); + Object.defineProperty(this, "timings", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "event", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.name = 'TimeoutError'; + this.event = error.event; + this.timings = timings; + } +}; +/** +An error to be thrown when reading from response stream fails. +*/ +class ReadError extends RequestError$1 { + constructor(error, request) { + super(error.message, error, request); + this.name = 'ReadError'; + this.code = this.code === 'ERR_GOT_REQUEST_ERROR' ? 'ERR_READING_RESPONSE_STREAM' : this.code; + } +} +/** +An error which always triggers a new retry when thrown. +*/ +class RetryError extends RequestError$1 { + constructor(request) { + super('Retrying', {}, request); + this.name = 'RetryError'; + this.code = 'ERR_RETRYING'; + } +} +/** +An error to be thrown when the request is aborted by AbortController. +*/ +let AbortError$3 = class AbortError extends RequestError$1 { + constructor(request) { + super('This operation was aborted.', {}, request); + this.code = 'ERR_ABORTED'; + this.name = 'AbortError'; + } +}; + +var source$3 = {exports: {}}; + +(function (module, exports) { + Object.defineProperty(exports, "__esModule", { value: true }); + function isTLSSocket(socket) { + return socket.encrypted; + } + const deferToConnect = (socket, fn) => { + let listeners; + if (typeof fn === 'function') { + const connect = fn; + listeners = { connect }; + } + else { + listeners = fn; + } + const hasConnectListener = typeof listeners.connect === 'function'; + const hasSecureConnectListener = typeof listeners.secureConnect === 'function'; + const hasCloseListener = typeof listeners.close === 'function'; + const onConnect = () => { + if (hasConnectListener) { + listeners.connect(); + } + if (isTLSSocket(socket) && hasSecureConnectListener) { + if (socket.authorized) { + listeners.secureConnect(); + } + else if (!socket.authorizationError) { + socket.once('secureConnect', listeners.secureConnect); + } + } + if (hasCloseListener) { + socket.once('close', listeners.close); + } + }; + if (socket.writable && !socket.connecting) { + onConnect(); + } + else if (socket.connecting) { + socket.once('connect', onConnect); + } + else if (socket.destroyed && hasCloseListener) { + listeners.close(socket._hadError); + } + }; + exports.default = deferToConnect; + // For CommonJS default export support + module.exports = deferToConnect; + module.exports.default = deferToConnect; +} (source$3, source$3.exports)); + +var sourceExports = source$3.exports; +var deferToConnect = /*@__PURE__*/getDefaultExportFromCjs(sourceExports); + +const timer = (request) => { + if (request.timings) { + return request.timings; + } + const timings = { + start: Date.now(), + socket: undefined, + lookup: undefined, + connect: undefined, + secureConnect: undefined, + upload: undefined, + response: undefined, + end: undefined, + error: undefined, + abort: undefined, + phases: { + wait: undefined, + dns: undefined, + tcp: undefined, + tls: undefined, + request: undefined, + firstByte: undefined, + download: undefined, + total: undefined, + }, + }; + request.timings = timings; + const handleError = (origin) => { + origin.once(require$$2$3.errorMonitor, () => { + timings.error = Date.now(); + timings.phases.total = timings.error - timings.start; + }); + }; + handleError(request); + const onAbort = () => { + timings.abort = Date.now(); + timings.phases.total = timings.abort - timings.start; + }; + request.prependOnceListener('abort', onAbort); + const onSocket = (socket) => { + timings.socket = Date.now(); + timings.phases.wait = timings.socket - timings.start; + if (require$$0$9.types.isProxy(socket)) { + return; + } + const lookupListener = () => { + timings.lookup = Date.now(); + timings.phases.dns = timings.lookup - timings.socket; + }; + socket.prependOnceListener('lookup', lookupListener); + deferToConnect(socket, { + connect: () => { + timings.connect = Date.now(); + if (timings.lookup === undefined) { + socket.removeListener('lookup', lookupListener); + timings.lookup = timings.connect; + timings.phases.dns = timings.lookup - timings.socket; + } + timings.phases.tcp = timings.connect - timings.lookup; + }, + secureConnect: () => { + timings.secureConnect = Date.now(); + timings.phases.tls = timings.secureConnect - timings.connect; + }, + }); + }; + if (request.socket) { + onSocket(request.socket); + } + else { + request.prependOnceListener('socket', onSocket); + } + const onUpload = () => { + timings.upload = Date.now(); + timings.phases.request = timings.upload - (timings.secureConnect ?? timings.connect); + }; + if (request.writableFinished) { + onUpload(); + } + else { + request.prependOnceListener('finish', onUpload); + } + request.prependOnceListener('response', (response) => { + timings.response = Date.now(); + timings.phases.firstByte = timings.response - timings.upload; + response.timings = timings; + handleError(response); + response.prependOnceListener('end', () => { + request.off('abort', onAbort); + response.off('aborted', onAbort); + if (timings.phases.total) { + // Aborted or errored + return; + } + timings.end = Date.now(); + timings.phases.download = timings.end - timings.response; + timings.phases.total = timings.end - timings.start; + }); + response.prependOnceListener('aborted', onAbort); + }); + return timings; +}; +var timer$1 = timer; + +// https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs +const DATA_URL_DEFAULT_MIME_TYPE = 'text/plain'; +const DATA_URL_DEFAULT_CHARSET = 'us-ascii'; + +const testParameter = (name, filters) => filters.some(filter => filter instanceof RegExp ? filter.test(name) : filter === name); + +const supportedProtocols = new Set([ + 'https:', + 'http:', + 'file:', +]); + +const hasCustomProtocol = urlString => { + try { + const {protocol} = new URL(urlString); + return protocol.endsWith(':') && !supportedProtocols.has(protocol); + } catch { + return false; + } +}; + +const normalizeDataURL = (urlString, {stripHash}) => { + const match = /^data:(?[^,]*?),(?[^#]*?)(?:#(?.*))?$/.exec(urlString); + + if (!match) { + throw new Error(`Invalid URL: ${urlString}`); + } + + let {type, data, hash} = match.groups; + const mediaType = type.split(';'); + hash = stripHash ? '' : hash; + + let isBase64 = false; + if (mediaType[mediaType.length - 1] === 'base64') { + mediaType.pop(); + isBase64 = true; + } + + // Lowercase MIME type + const mimeType = mediaType.shift()?.toLowerCase() ?? ''; + const attributes = mediaType + .map(attribute => { + let [key, value = ''] = attribute.split('=').map(string => string.trim()); + + // Lowercase `charset` + if (key === 'charset') { + value = value.toLowerCase(); + + if (value === DATA_URL_DEFAULT_CHARSET) { + return ''; + } + } + + return `${key}${value ? `=${value}` : ''}`; + }) + .filter(Boolean); + + const normalizedMediaType = [ + ...attributes, + ]; + + if (isBase64) { + normalizedMediaType.push('base64'); + } + + if (normalizedMediaType.length > 0 || (mimeType && mimeType !== DATA_URL_DEFAULT_MIME_TYPE)) { + normalizedMediaType.unshift(mimeType); + } + + return `data:${normalizedMediaType.join(';')},${isBase64 ? data.trim() : data}${hash ? `#${hash}` : ''}`; +}; + +function normalizeUrl(urlString, options) { + options = { + defaultProtocol: 'http', + normalizeProtocol: true, + forceHttp: false, + forceHttps: false, + stripAuthentication: true, + stripHash: false, + stripTextFragment: true, + stripWWW: true, + removeQueryParameters: [/^utm_\w+/i], + removeTrailingSlash: true, + removeSingleSlash: true, + removeDirectoryIndex: false, + removeExplicitPort: false, + sortQueryParameters: true, + ...options, + }; + + // Legacy: Append `:` to the protocol if missing. + if (typeof options.defaultProtocol === 'string' && !options.defaultProtocol.endsWith(':')) { + options.defaultProtocol = `${options.defaultProtocol}:`; + } + + urlString = urlString.trim(); + + // Data URL + if (/^data:/i.test(urlString)) { + return normalizeDataURL(urlString, options); + } + + if (hasCustomProtocol(urlString)) { + return urlString; + } + + const hasRelativeProtocol = urlString.startsWith('//'); + const isRelativeUrl = !hasRelativeProtocol && /^\.*\//.test(urlString); + + // Prepend protocol + if (!isRelativeUrl) { + urlString = urlString.replace(/^(?!(?:\w+:)?\/\/)|^\/\//, options.defaultProtocol); + } + + const urlObject = new URL(urlString); + + if (options.forceHttp && options.forceHttps) { + throw new Error('The `forceHttp` and `forceHttps` options cannot be used together'); + } + + if (options.forceHttp && urlObject.protocol === 'https:') { + urlObject.protocol = 'http:'; + } + + if (options.forceHttps && urlObject.protocol === 'http:') { + urlObject.protocol = 'https:'; + } + + // Remove auth + if (options.stripAuthentication) { + urlObject.username = ''; + urlObject.password = ''; + } + + // Remove hash + if (options.stripHash) { + urlObject.hash = ''; + } else if (options.stripTextFragment) { + urlObject.hash = urlObject.hash.replace(/#?:~:text.*?$/i, ''); + } + + // Remove duplicate slashes if not preceded by a protocol + // NOTE: This could be implemented using a single negative lookbehind + // regex, but we avoid that to maintain compatibility with older js engines + // which do not have support for that feature. + if (urlObject.pathname) { + // TODO: Replace everything below with `urlObject.pathname = urlObject.pathname.replace(/(? 0) { + let pathComponents = urlObject.pathname.split('/'); + const lastComponent = pathComponents[pathComponents.length - 1]; + + if (testParameter(lastComponent, options.removeDirectoryIndex)) { + pathComponents = pathComponents.slice(0, -1); + urlObject.pathname = pathComponents.slice(1).join('/') + '/'; + } + } + + if (urlObject.hostname) { + // Remove trailing dot + urlObject.hostname = urlObject.hostname.replace(/\.$/, ''); + + // Remove `www.` + if (options.stripWWW && /^www\.(?!www\.)[a-z\-\d]{1,63}\.[a-z.\-\d]{2,63}$/.test(urlObject.hostname)) { + // Each label should be max 63 at length (min: 1). + // Source: https://en.wikipedia.org/wiki/Hostname#Restrictions_on_valid_host_names + // Each TLD should be up to 63 characters long (min: 2). + // It is technically possible to have a single character TLD, but none currently exist. + urlObject.hostname = urlObject.hostname.replace(/^www\./, ''); + } + } + + // Remove query unwanted parameters + if (Array.isArray(options.removeQueryParameters)) { + // eslint-disable-next-line unicorn/no-useless-spread -- We are intentionally spreading to get a copy. + for (const key of [...urlObject.searchParams.keys()]) { + if (testParameter(key, options.removeQueryParameters)) { + urlObject.searchParams.delete(key); + } + } + } + + if (!Array.isArray(options.keepQueryParameters) && options.removeQueryParameters === true) { + urlObject.search = ''; + } + + // Keep wanted query parameters + if (Array.isArray(options.keepQueryParameters) && options.keepQueryParameters.length > 0) { + // eslint-disable-next-line unicorn/no-useless-spread -- We are intentionally spreading to get a copy. + for (const key of [...urlObject.searchParams.keys()]) { + if (!testParameter(key, options.keepQueryParameters)) { + urlObject.searchParams.delete(key); + } + } + } + + // Sort query parameters + if (options.sortQueryParameters) { + urlObject.searchParams.sort(); + + // Calling `.sort()` encodes the search parameters, so we need to decode them again. + try { + urlObject.search = decodeURIComponent(urlObject.search); + } catch {} + } + + if (options.removeTrailingSlash) { + urlObject.pathname = urlObject.pathname.replace(/\/$/, ''); + } + + // Remove an explicit port number, excluding a default port number, if applicable + if (options.removeExplicitPort && urlObject.port) { + urlObject.port = ''; + } + + const oldUrlString = urlString; + + // Take advantage of many of the Node `url` normalizations + urlString = urlObject.toString(); + + if (!options.removeSingleSlash && urlObject.pathname === '/' && !oldUrlString.endsWith('/') && urlObject.hash === '') { + urlString = urlString.replace(/\/$/, ''); + } + + // Remove ending `/` unless removeSingleSlash is false + if ((options.removeTrailingSlash || urlObject.pathname === '/') && urlObject.hash === '' && options.removeSingleSlash) { + urlString = urlString.replace(/\/$/, ''); + } + + // Restore relative protocol, if applicable + if (hasRelativeProtocol && !options.normalizeProtocol) { + urlString = urlString.replace(/^http:\/\//, '//'); + } + + // Remove http/https + if (options.stripProtocol) { + urlString = urlString.replace(/^(?:https?:)?\/\//, ''); + } + + return urlString; +} + +var getStream$4 = {exports: {}}; + +const {PassThrough: PassThroughStream} = Stream$3; + +var bufferStream$1 = options => { + options = {...options}; + + const {array} = options; + let {encoding} = options; + const isBuffer = encoding === 'buffer'; + let objectMode = false; + + if (array) { + objectMode = !(encoding || isBuffer); + } else { + encoding = encoding || 'utf8'; + } + + if (isBuffer) { + encoding = null; + } + + const stream = new PassThroughStream({objectMode}); + + if (encoding) { + stream.setEncoding(encoding); + } + + let length = 0; + const chunks = []; + + stream.on('data', chunk => { + chunks.push(chunk); + + if (objectMode) { + length = chunks.length; + } else { + length += chunk.length; + } + }); + + stream.getBufferedValue = () => { + if (array) { + return chunks; + } + + return isBuffer ? Buffer.concat(chunks, length) : chunks.join(''); + }; + + stream.getBufferedLength = () => length; + + return stream; +}; + +const {constants: BufferConstants} = require$$0$d; +const stream$3 = Stream$3; +const {promisify} = require$$0$9; +const bufferStream = bufferStream$1; + +const streamPipelinePromisified = promisify(stream$3.pipeline); + +class MaxBufferError extends Error { + constructor() { + super('maxBuffer exceeded'); + this.name = 'MaxBufferError'; + } +} + +async function getStream$2(inputStream, options) { + if (!inputStream) { + throw new Error('Expected a stream'); + } + + options = { + maxBuffer: Infinity, + ...options + }; + + const {maxBuffer} = options; + const stream = bufferStream(options); + + await new Promise((resolve, reject) => { + const rejectPromise = error => { + // Don't retrieve an oversized buffer. + if (error && stream.getBufferedLength() <= BufferConstants.MAX_LENGTH) { + error.bufferedData = stream.getBufferedValue(); + } + + reject(error); + }; + + (async () => { + try { + await streamPipelinePromisified(inputStream, stream); + resolve(); + } catch (error) { + rejectPromise(error); + } + })(); + + stream.on('data', () => { + if (stream.getBufferedLength() > maxBuffer) { + rejectPromise(new MaxBufferError()); + } + }); + }); + + return stream.getBufferedValue(); +} + +getStream$4.exports = getStream$2; +getStream$4.exports.buffer = (stream, options) => getStream$2(stream, {...options, encoding: 'buffer'}); +getStream$4.exports.array = (stream, options) => getStream$2(stream, {...options, array: true}); +getStream$4.exports.MaxBufferError = MaxBufferError; + +var getStreamExports = getStream$4.exports; +var getStream$3 = /*@__PURE__*/getDefaultExportFromCjs(getStreamExports); + +// rfc7231 6.1 +const statusCodeCacheableByDefault = new Set([ + 200, + 203, + 204, + 206, + 300, + 301, + 308, + 404, + 405, + 410, + 414, + 501, +]); + +// This implementation does not understand partial responses (206) +const understoodStatuses = new Set([ + 200, + 203, + 204, + 300, + 301, + 302, + 303, + 307, + 308, + 404, + 405, + 410, + 414, + 501, +]); + +const errorStatusCodes = new Set([ + 500, + 502, + 503, + 504, +]); + +const hopByHopHeaders = { + date: true, // included, because we add Age update Date + connection: true, + 'keep-alive': true, + 'proxy-authenticate': true, + 'proxy-authorization': true, + te: true, + trailer: true, + 'transfer-encoding': true, + upgrade: true, +}; + +const excludedFromRevalidationUpdate = { + // Since the old body is reused, it doesn't make sense to change properties of the body + 'content-length': true, + 'content-encoding': true, + 'transfer-encoding': true, + 'content-range': true, +}; + +function toNumberOrZero(s) { + const n = parseInt(s, 10); + return isFinite(n) ? n : 0; +} + +// RFC 5861 +function isErrorResponse(response) { + // consider undefined response as faulty + if(!response) { + return true + } + return errorStatusCodes.has(response.status); +} + +function parseCacheControl(header) { + const cc = {}; + if (!header) return cc; + + // TODO: When there is more than one value present for a given directive (e.g., two Expires header fields, multiple Cache-Control: max-age directives), + // the directive's value is considered invalid. Caches are encouraged to consider responses that have invalid freshness information to be stale + const parts = header.trim().split(/,/); + for (const part of parts) { + const [k, v] = part.split(/=/, 2); + cc[k.trim()] = v === undefined ? true : v.trim().replace(/^"|"$/g, ''); + } + + return cc; +} + +function formatCacheControl(cc) { + let parts = []; + for (const k in cc) { + const v = cc[k]; + parts.push(v === true ? k : k + '=' + v); + } + if (!parts.length) { + return undefined; + } + return parts.join(', '); +} + +var httpCacheSemantics = class CachePolicy { + constructor( + req, + res, + { + shared, + cacheHeuristic, + immutableMinTimeToLive, + ignoreCargoCult, + _fromObject, + } = {} + ) { + if (_fromObject) { + this._fromObject(_fromObject); + return; + } + + if (!res || !res.headers) { + throw Error('Response headers missing'); + } + this._assertRequestHasHeaders(req); + + this._responseTime = this.now(); + this._isShared = shared !== false; + this._cacheHeuristic = + undefined !== cacheHeuristic ? cacheHeuristic : 0.1; // 10% matches IE + this._immutableMinTtl = + undefined !== immutableMinTimeToLive + ? immutableMinTimeToLive + : 24 * 3600 * 1000; + + this._status = 'status' in res ? res.status : 200; + this._resHeaders = res.headers; + this._rescc = parseCacheControl(res.headers['cache-control']); + this._method = 'method' in req ? req.method : 'GET'; + this._url = req.url; + this._host = req.headers.host; + this._noAuthorization = !req.headers.authorization; + this._reqHeaders = res.headers.vary ? req.headers : null; // Don't keep all request headers if they won't be used + this._reqcc = parseCacheControl(req.headers['cache-control']); + + // Assume that if someone uses legacy, non-standard uncecessary options they don't understand caching, + // so there's no point stricly adhering to the blindly copy&pasted directives. + if ( + ignoreCargoCult && + 'pre-check' in this._rescc && + 'post-check' in this._rescc + ) { + delete this._rescc['pre-check']; + delete this._rescc['post-check']; + delete this._rescc['no-cache']; + delete this._rescc['no-store']; + delete this._rescc['must-revalidate']; + this._resHeaders = Object.assign({}, this._resHeaders, { + 'cache-control': formatCacheControl(this._rescc), + }); + delete this._resHeaders.expires; + delete this._resHeaders.pragma; + } + + // When the Cache-Control header field is not present in a request, caches MUST consider the no-cache request pragma-directive + // as having the same effect as if "Cache-Control: no-cache" were present (see Section 5.2.1). + if ( + res.headers['cache-control'] == null && + /no-cache/.test(res.headers.pragma) + ) { + this._rescc['no-cache'] = true; + } + } + + now() { + return Date.now(); + } + + storable() { + // The "no-store" request directive indicates that a cache MUST NOT store any part of either this request or any response to it. + return !!( + !this._reqcc['no-store'] && + // A cache MUST NOT store a response to any request, unless: + // The request method is understood by the cache and defined as being cacheable, and + ('GET' === this._method || + 'HEAD' === this._method || + ('POST' === this._method && this._hasExplicitExpiration())) && + // the response status code is understood by the cache, and + understoodStatuses.has(this._status) && + // the "no-store" cache directive does not appear in request or response header fields, and + !this._rescc['no-store'] && + // the "private" response directive does not appear in the response, if the cache is shared, and + (!this._isShared || !this._rescc.private) && + // the Authorization header field does not appear in the request, if the cache is shared, + (!this._isShared || + this._noAuthorization || + this._allowsStoringAuthenticated()) && + // the response either: + // contains an Expires header field, or + (this._resHeaders.expires || + // contains a max-age response directive, or + // contains a s-maxage response directive and the cache is shared, or + // contains a public response directive. + this._rescc['max-age'] || + (this._isShared && this._rescc['s-maxage']) || + this._rescc.public || + // has a status code that is defined as cacheable by default + statusCodeCacheableByDefault.has(this._status)) + ); + } + + _hasExplicitExpiration() { + // 4.2.1 Calculating Freshness Lifetime + return ( + (this._isShared && this._rescc['s-maxage']) || + this._rescc['max-age'] || + this._resHeaders.expires + ); + } + + _assertRequestHasHeaders(req) { + if (!req || !req.headers) { + throw Error('Request headers missing'); + } + } + + satisfiesWithoutRevalidation(req) { + this._assertRequestHasHeaders(req); + + // When presented with a request, a cache MUST NOT reuse a stored response, unless: + // the presented request does not contain the no-cache pragma (Section 5.4), nor the no-cache cache directive, + // unless the stored response is successfully validated (Section 4.3), and + const requestCC = parseCacheControl(req.headers['cache-control']); + if (requestCC['no-cache'] || /no-cache/.test(req.headers.pragma)) { + return false; + } + + if (requestCC['max-age'] && this.age() > requestCC['max-age']) { + return false; + } + + if ( + requestCC['min-fresh'] && + this.timeToLive() < 1000 * requestCC['min-fresh'] + ) { + return false; + } + + // the stored response is either: + // fresh, or allowed to be served stale + if (this.stale()) { + const allowsStale = + requestCC['max-stale'] && + !this._rescc['must-revalidate'] && + (true === requestCC['max-stale'] || + requestCC['max-stale'] > this.age() - this.maxAge()); + if (!allowsStale) { + return false; + } + } + + return this._requestMatches(req, false); + } + + _requestMatches(req, allowHeadMethod) { + // The presented effective request URI and that of the stored response match, and + return ( + (!this._url || this._url === req.url) && + this._host === req.headers.host && + // the request method associated with the stored response allows it to be used for the presented request, and + (!req.method || + this._method === req.method || + (allowHeadMethod && 'HEAD' === req.method)) && + // selecting header fields nominated by the stored response (if any) match those presented, and + this._varyMatches(req) + ); + } + + _allowsStoringAuthenticated() { + // following Cache-Control response directives (Section 5.2.2) have such an effect: must-revalidate, public, and s-maxage. + return ( + this._rescc['must-revalidate'] || + this._rescc.public || + this._rescc['s-maxage'] + ); + } + + _varyMatches(req) { + if (!this._resHeaders.vary) { + return true; + } + + // A Vary header field-value of "*" always fails to match + if (this._resHeaders.vary === '*') { + return false; + } + + const fields = this._resHeaders.vary + .trim() + .toLowerCase() + .split(/\s*,\s*/); + for (const name of fields) { + if (req.headers[name] !== this._reqHeaders[name]) return false; + } + return true; + } + + _copyWithoutHopByHopHeaders(inHeaders) { + const headers = {}; + for (const name in inHeaders) { + if (hopByHopHeaders[name]) continue; + headers[name] = inHeaders[name]; + } + // 9.1. Connection + if (inHeaders.connection) { + const tokens = inHeaders.connection.trim().split(/\s*,\s*/); + for (const name of tokens) { + delete headers[name]; + } + } + if (headers.warning) { + const warnings = headers.warning.split(/,/).filter(warning => { + return !/^\s*1[0-9][0-9]/.test(warning); + }); + if (!warnings.length) { + delete headers.warning; + } else { + headers.warning = warnings.join(',').trim(); + } + } + return headers; + } + + responseHeaders() { + const headers = this._copyWithoutHopByHopHeaders(this._resHeaders); + const age = this.age(); + + // A cache SHOULD generate 113 warning if it heuristically chose a freshness + // lifetime greater than 24 hours and the response's age is greater than 24 hours. + if ( + age > 3600 * 24 && + !this._hasExplicitExpiration() && + this.maxAge() > 3600 * 24 + ) { + headers.warning = + (headers.warning ? `${headers.warning}, ` : '') + + '113 - "rfc7234 5.5.4"'; + } + headers.age = `${Math.round(age)}`; + headers.date = new Date(this.now()).toUTCString(); + return headers; + } + + /** + * Value of the Date response header or current time if Date was invalid + * @return timestamp + */ + date() { + const serverDate = Date.parse(this._resHeaders.date); + if (isFinite(serverDate)) { + return serverDate; + } + return this._responseTime; + } + + /** + * Value of the Age header, in seconds, updated for the current time. + * May be fractional. + * + * @return Number + */ + age() { + let age = this._ageValue(); + + const residentTime = (this.now() - this._responseTime) / 1000; + return age + residentTime; + } + + _ageValue() { + return toNumberOrZero(this._resHeaders.age); + } + + /** + * Value of applicable max-age (or heuristic equivalent) in seconds. This counts since response's `Date`. + * + * For an up-to-date value, see `timeToLive()`. + * + * @return Number + */ + maxAge() { + if (!this.storable() || this._rescc['no-cache']) { + return 0; + } + + // Shared responses with cookies are cacheable according to the RFC, but IMHO it'd be unwise to do so by default + // so this implementation requires explicit opt-in via public header + if ( + this._isShared && + (this._resHeaders['set-cookie'] && + !this._rescc.public && + !this._rescc.immutable) + ) { + return 0; + } + + if (this._resHeaders.vary === '*') { + return 0; + } + + if (this._isShared) { + if (this._rescc['proxy-revalidate']) { + return 0; + } + // if a response includes the s-maxage directive, a shared cache recipient MUST ignore the Expires field. + if (this._rescc['s-maxage']) { + return toNumberOrZero(this._rescc['s-maxage']); + } + } + + // If a response includes a Cache-Control field with the max-age directive, a recipient MUST ignore the Expires field. + if (this._rescc['max-age']) { + return toNumberOrZero(this._rescc['max-age']); + } + + const defaultMinTtl = this._rescc.immutable ? this._immutableMinTtl : 0; + + const serverDate = this.date(); + if (this._resHeaders.expires) { + const expires = Date.parse(this._resHeaders.expires); + // A cache recipient MUST interpret invalid date formats, especially the value "0", as representing a time in the past (i.e., "already expired"). + if (Number.isNaN(expires) || expires < serverDate) { + return 0; + } + return Math.max(defaultMinTtl, (expires - serverDate) / 1000); + } + + if (this._resHeaders['last-modified']) { + const lastModified = Date.parse(this._resHeaders['last-modified']); + if (isFinite(lastModified) && serverDate > lastModified) { + return Math.max( + defaultMinTtl, + ((serverDate - lastModified) / 1000) * this._cacheHeuristic + ); + } + } + + return defaultMinTtl; + } + + timeToLive() { + const age = this.maxAge() - this.age(); + const staleIfErrorAge = age + toNumberOrZero(this._rescc['stale-if-error']); + const staleWhileRevalidateAge = age + toNumberOrZero(this._rescc['stale-while-revalidate']); + return Math.max(0, age, staleIfErrorAge, staleWhileRevalidateAge) * 1000; + } + + stale() { + return this.maxAge() <= this.age(); + } + + _useStaleIfError() { + return this.maxAge() + toNumberOrZero(this._rescc['stale-if-error']) > this.age(); + } + + useStaleWhileRevalidate() { + return this.maxAge() + toNumberOrZero(this._rescc['stale-while-revalidate']) > this.age(); + } + + static fromObject(obj) { + return new this(undefined, undefined, { _fromObject: obj }); + } + + _fromObject(obj) { + if (this._responseTime) throw Error('Reinitialized'); + if (!obj || obj.v !== 1) throw Error('Invalid serialization'); + + this._responseTime = obj.t; + this._isShared = obj.sh; + this._cacheHeuristic = obj.ch; + this._immutableMinTtl = + obj.imm !== undefined ? obj.imm : 24 * 3600 * 1000; + this._status = obj.st; + this._resHeaders = obj.resh; + this._rescc = obj.rescc; + this._method = obj.m; + this._url = obj.u; + this._host = obj.h; + this._noAuthorization = obj.a; + this._reqHeaders = obj.reqh; + this._reqcc = obj.reqcc; + } + + toObject() { + return { + v: 1, + t: this._responseTime, + sh: this._isShared, + ch: this._cacheHeuristic, + imm: this._immutableMinTtl, + st: this._status, + resh: this._resHeaders, + rescc: this._rescc, + m: this._method, + u: this._url, + h: this._host, + a: this._noAuthorization, + reqh: this._reqHeaders, + reqcc: this._reqcc, + }; + } + + /** + * Headers for sending to the origin server to revalidate stale response. + * Allows server to return 304 to allow reuse of the previous response. + * + * Hop by hop headers are always stripped. + * Revalidation headers may be added or removed, depending on request. + */ + revalidationHeaders(incomingReq) { + this._assertRequestHasHeaders(incomingReq); + const headers = this._copyWithoutHopByHopHeaders(incomingReq.headers); + + // This implementation does not understand range requests + delete headers['if-range']; + + if (!this._requestMatches(incomingReq, true) || !this.storable()) { + // revalidation allowed via HEAD + // not for the same resource, or wasn't allowed to be cached anyway + delete headers['if-none-match']; + delete headers['if-modified-since']; + return headers; + } + + /* MUST send that entity-tag in any cache validation request (using If-Match or If-None-Match) if an entity-tag has been provided by the origin server. */ + if (this._resHeaders.etag) { + headers['if-none-match'] = headers['if-none-match'] + ? `${headers['if-none-match']}, ${this._resHeaders.etag}` + : this._resHeaders.etag; + } + + // Clients MAY issue simple (non-subrange) GET requests with either weak validators or strong validators. Clients MUST NOT use weak validators in other forms of request. + const forbidsWeakValidators = + headers['accept-ranges'] || + headers['if-match'] || + headers['if-unmodified-since'] || + (this._method && this._method != 'GET'); + + /* SHOULD send the Last-Modified value in non-subrange cache validation requests (using If-Modified-Since) if only a Last-Modified value has been provided by the origin server. + Note: This implementation does not understand partial responses (206) */ + if (forbidsWeakValidators) { + delete headers['if-modified-since']; + + if (headers['if-none-match']) { + const etags = headers['if-none-match'] + .split(/,/) + .filter(etag => { + return !/^\s*W\//.test(etag); + }); + if (!etags.length) { + delete headers['if-none-match']; + } else { + headers['if-none-match'] = etags.join(',').trim(); + } + } + } else if ( + this._resHeaders['last-modified'] && + !headers['if-modified-since'] + ) { + headers['if-modified-since'] = this._resHeaders['last-modified']; + } + + return headers; + } + + /** + * Creates new CachePolicy with information combined from the previews response, + * and the new revalidation response. + * + * Returns {policy, modified} where modified is a boolean indicating + * whether the response body has been modified, and old cached body can't be used. + * + * @return {Object} {policy: CachePolicy, modified: Boolean} + */ + revalidatedPolicy(request, response) { + this._assertRequestHasHeaders(request); + if(this._useStaleIfError() && isErrorResponse(response)) { // I consider the revalidation request unsuccessful + return { + modified: false, + matches: false, + policy: this, + }; + } + if (!response || !response.headers) { + throw Error('Response headers missing'); + } + + // These aren't going to be supported exactly, since one CachePolicy object + // doesn't know about all the other cached objects. + let matches = false; + if (response.status !== undefined && response.status != 304) { + matches = false; + } else if ( + response.headers.etag && + !/^\s*W\//.test(response.headers.etag) + ) { + // "All of the stored responses with the same strong validator are selected. + // If none of the stored responses contain the same strong validator, + // then the cache MUST NOT use the new response to update any stored responses." + matches = + this._resHeaders.etag && + this._resHeaders.etag.replace(/^\s*W\//, '') === + response.headers.etag; + } else if (this._resHeaders.etag && response.headers.etag) { + // "If the new response contains a weak validator and that validator corresponds + // to one of the cache's stored responses, + // then the most recent of those matching stored responses is selected for update." + matches = + this._resHeaders.etag.replace(/^\s*W\//, '') === + response.headers.etag.replace(/^\s*W\//, ''); + } else if (this._resHeaders['last-modified']) { + matches = + this._resHeaders['last-modified'] === + response.headers['last-modified']; + } else { + // If the new response does not include any form of validator (such as in the case where + // a client generates an If-Modified-Since request from a source other than the Last-Modified + // response header field), and there is only one stored response, and that stored response also + // lacks a validator, then that stored response is selected for update. + if ( + !this._resHeaders.etag && + !this._resHeaders['last-modified'] && + !response.headers.etag && + !response.headers['last-modified'] + ) { + matches = true; + } + } + + if (!matches) { + return { + policy: new this.constructor(request, response), + // Client receiving 304 without body, even if it's invalid/mismatched has no option + // but to reuse a cached body. We don't have a good way to tell clients to do + // error recovery in such case. + modified: response.status != 304, + matches: false, + }; + } + + // use other header fields provided in the 304 (Not Modified) response to replace all instances + // of the corresponding header fields in the stored response. + const headers = {}; + for (const k in this._resHeaders) { + headers[k] = + k in response.headers && !excludedFromRevalidationUpdate[k] + ? response.headers[k] + : this._resHeaders[k]; + } + + const newResponse = Object.assign({}, response, { + status: this._status, + method: this._method, + headers, + }); + return { + policy: new this.constructor(request, newResponse, { + shared: this._isShared, + cacheHeuristic: this._cacheHeuristic, + immutableMinTimeToLive: this._immutableMinTtl, + }), + modified: false, + matches: true, + }; + } +}; + +var CachePolicy = /*@__PURE__*/getDefaultExportFromCjs(httpCacheSemantics); + +function lowercaseKeys(object) { + return Object.fromEntries(Object.entries(object).map(([key, value]) => [key.toLowerCase(), value])); +} + +let Response$3 = class Response extends Stream$4.Readable { + statusCode; + headers; + body; + url; + + constructor({statusCode, headers, body, url}) { + if (typeof statusCode !== 'number') { + throw new TypeError('Argument `statusCode` should be a number'); + } + + if (typeof headers !== 'object') { + throw new TypeError('Argument `headers` should be an object'); + } + + if (!(body instanceof Uint8Array)) { + throw new TypeError('Argument `body` should be a buffer'); + } + + if (typeof url !== 'string') { + throw new TypeError('Argument `url` should be a string'); + } + + super({ + read() { + this.push(body); + this.push(null); + }, + }); + + this.statusCode = statusCode; + this.headers = lowercaseKeys(headers); + this.body = body; + this.url = url; + } +}; + +function commonjsRequire(path) { + throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.'); +} + +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$2 = require$$2$3; +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$2 { + 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 = await 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$8 = Keyv; + +var Keyv$1 = /*@__PURE__*/getDefaultExportFromCjs(src$8); + +// We define these manually to ensure they're always copied +// even if they would move up the prototype chain +// https://nodejs.org/api/http.html#http_class_http_incomingmessage +const knownProperties$1 = [ + 'aborted', + 'complete', + 'headers', + 'httpVersion', + 'httpVersionMinor', + 'httpVersionMajor', + 'method', + 'rawHeaders', + 'rawTrailers', + 'setTimeout', + 'socket', + 'statusCode', + 'statusMessage', + 'trailers', + 'url', +]; + +function mimicResponse$2(fromStream, toStream) { + if (toStream._readableState.autoDestroy) { + throw new Error('The second stream must have the `autoDestroy` option set to `false`'); + } + + const fromProperties = new Set([...Object.keys(fromStream), ...knownProperties$1]); + + const properties = {}; + + for (const property of fromProperties) { + // Don't overwrite existing properties. + if (property in toStream) { + continue; + } + + properties[property] = { + get() { + const value = fromStream[property]; + const isFunction = typeof value === 'function'; + + return isFunction ? value.bind(fromStream) : value; + }, + set(value) { + fromStream[property] = value; + }, + enumerable: true, + configurable: false, + }; + } + + Object.defineProperties(toStream, properties); + + fromStream.once('aborted', () => { + toStream.destroy(); + + toStream.emit('aborted'); + }); + + fromStream.once('close', () => { + if (fromStream.complete) { + if (toStream.readable) { + toStream.once('end', () => { + toStream.emit('close'); + }); + } else { + toStream.emit('close'); + } + } else { + toStream.emit('close'); + } + }); + + return toStream; +} + +// Type definitions for cacheable-request 6.0 +// Project: https://github.com/lukechilds/cacheable-request#readme +// Definitions by: BendingBender +// Paul Melnikow +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 +class RequestError extends Error { + constructor(error) { + super(error.message); + Object.assign(this, error); + } +} +class CacheError extends Error { + constructor(error) { + super(error.message); + Object.assign(this, error); + } +} + +class CacheableRequest { + constructor(cacheRequest, cacheAdapter) { + this.hooks = new Map(); + this.request = () => (options, cb) => { + let url; + if (typeof options === 'string') { + url = normalizeUrlObject(urlLib.parse(options)); + options = {}; + } + else if (options instanceof urlLib.URL) { + url = normalizeUrlObject(urlLib.parse(options.toString())); + options = {}; + } + else { + const [pathname, ...searchParts] = (options.path ?? '').split('?'); + const search = searchParts.length > 0 + ? `?${searchParts.join('?')}` + : ''; + url = normalizeUrlObject({ ...options, pathname, search }); + } + options = { + headers: {}, + method: 'GET', + cache: true, + strictTtl: false, + automaticFailover: false, + ...options, + ...urlObjectToRequestOptions(url), + }; + options.headers = Object.fromEntries(entries(options.headers).map(([key, value]) => [key.toLowerCase(), value])); + const ee = new EventEmitter$3(); + const normalizedUrlString = normalizeUrl(urlLib.format(url), { + stripWWW: false, + removeTrailingSlash: false, + stripAuthentication: false, + }); + let key = `${options.method}:${normalizedUrlString}`; + // POST, PATCH, and PUT requests may be cached, depending on the response + // cache-control headers. As a result, the body of the request should be + // added to the cache key in order to avoid collisions. + if (options.body && options.method !== undefined && ['POST', 'PATCH', 'PUT'].includes(options.method)) { + if (options.body instanceof Stream$4.Readable) { + // Streamed bodies should completely skip the cache because they may + // or may not be hashable and in either case the stream would need to + // close before the cache key could be generated. + options.cache = false; + } + else { + key += `:${crypto$1.createHash('md5').update(options.body).digest('hex')}`; + } + } + let revalidate = false; + let madeRequest = false; + const makeRequest = (options_) => { + madeRequest = true; + let requestErrored = false; + let requestErrorCallback = () => { }; + const requestErrorPromise = new Promise(resolve => { + requestErrorCallback = () => { + if (!requestErrored) { + requestErrored = true; + resolve(); + } + }; + }); + const handler = async (response) => { + if (revalidate) { + response.status = response.statusCode; + const revalidatedPolicy = CachePolicy.fromObject(revalidate.cachePolicy).revalidatedPolicy(options_, response); + if (!revalidatedPolicy.modified) { + response.resume(); + await new Promise(resolve => { + // Skipping 'error' handler cause 'error' event should't be emitted for 304 response + response + .once('end', resolve); + }); + const headers = convertHeaders(revalidatedPolicy.policy.responseHeaders()); + response = new Response$3({ statusCode: revalidate.statusCode, headers, body: revalidate.body, url: revalidate.url }); + response.cachePolicy = revalidatedPolicy.policy; + response.fromCache = true; + } + } + if (!response.fromCache) { + response.cachePolicy = new CachePolicy(options_, response, options_); + response.fromCache = false; + } + let clonedResponse; + if (options_.cache && response.cachePolicy.storable()) { + clonedResponse = cloneResponse(response); + (async () => { + try { + const bodyPromise = getStream$3.buffer(response); + await Promise.race([ + requestErrorPromise, + new Promise(resolve => response.once('end', resolve)), + new Promise(resolve => response.once('close', resolve)), // eslint-disable-line no-promise-executor-return + ]); + const body = await bodyPromise; + let value = { + url: response.url, + statusCode: response.fromCache ? revalidate.statusCode : response.statusCode, + body, + cachePolicy: response.cachePolicy.toObject(), + }; + let ttl = options_.strictTtl ? response.cachePolicy.timeToLive() : undefined; + if (options_.maxTtl) { + ttl = ttl ? Math.min(ttl, options_.maxTtl) : options_.maxTtl; + } + if (this.hooks.size > 0) { + /* eslint-disable no-await-in-loop */ + for (const key_ of this.hooks.keys()) { + value = await this.runHook(key_, value, response); + } + /* eslint-enable no-await-in-loop */ + } + await this.cache.set(key, value, ttl); + } + catch (error) { + ee.emit('error', new CacheError(error)); + } + })(); + } + else if (options_.cache && revalidate) { + (async () => { + try { + await this.cache.delete(key); + } + catch (error) { + ee.emit('error', new CacheError(error)); + } + })(); + } + ee.emit('response', clonedResponse ?? response); + if (typeof cb === 'function') { + cb(clonedResponse ?? response); + } + }; + try { + const request_ = this.cacheRequest(options_, handler); + request_.once('error', requestErrorCallback); + request_.once('abort', requestErrorCallback); + request_.once('destroy', requestErrorCallback); + ee.emit('request', request_); + } + catch (error) { + ee.emit('error', new RequestError(error)); + } + }; + (async () => { + const get = async (options_) => { + await Promise.resolve(); + const cacheEntry = options_.cache ? await this.cache.get(key) : undefined; + if (cacheEntry === undefined && !options_.forceRefresh) { + makeRequest(options_); + return; + } + const policy = CachePolicy.fromObject(cacheEntry.cachePolicy); + if (policy.satisfiesWithoutRevalidation(options_) && !options_.forceRefresh) { + const headers = convertHeaders(policy.responseHeaders()); + const response = new Response$3({ statusCode: cacheEntry.statusCode, headers, body: cacheEntry.body, url: cacheEntry.url }); + response.cachePolicy = policy; + response.fromCache = true; + ee.emit('response', response); + if (typeof cb === 'function') { + cb(response); + } + } + else if (policy.satisfiesWithoutRevalidation(options_) && Date.now() >= policy.timeToLive() && options_.forceRefresh) { + await this.cache.delete(key); + options_.headers = policy.revalidationHeaders(options_); + makeRequest(options_); + } + else { + revalidate = cacheEntry; + options_.headers = policy.revalidationHeaders(options_); + makeRequest(options_); + } + }; + const errorHandler = (error) => ee.emit('error', new CacheError(error)); + if (this.cache instanceof Keyv$1) { + const cachek = this.cache; + cachek.once('error', errorHandler); + ee.on('error', () => cachek.removeListener('error', errorHandler)); + ee.on('response', () => cachek.removeListener('error', errorHandler)); + } + try { + await get(options); + } + catch (error) { + if (options.automaticFailover && !madeRequest) { + makeRequest(options); + } + ee.emit('error', new CacheError(error)); + } + })(); + return ee; + }; + this.addHook = (name, fn) => { + if (!this.hooks.has(name)) { + this.hooks.set(name, fn); + } + }; + this.removeHook = (name) => this.hooks.delete(name); + this.getHook = (name) => this.hooks.get(name); + this.runHook = async (name, ...args) => this.hooks.get(name)?.(...args); + if (cacheAdapter instanceof Keyv$1) { + this.cache = cacheAdapter; + } + else if (typeof cacheAdapter === 'string') { + this.cache = new Keyv$1({ + uri: cacheAdapter, + namespace: 'cacheable-request', + }); + } + else { + this.cache = new Keyv$1({ + store: cacheAdapter, + namespace: 'cacheable-request', + }); + } + this.request = this.request.bind(this); + this.cacheRequest = cacheRequest; + } +} +const entries = Object.entries; +const cloneResponse = (response) => { + const clone = new Stream$4.PassThrough({ autoDestroy: false }); + mimicResponse$2(response, clone); + return response.pipe(clone); +}; +const urlObjectToRequestOptions = (url) => { + const options = { ...url }; + options.path = `${url.pathname || '/'}${url.search || ''}`; + delete options.pathname; + delete options.search; + return options; +}; +const normalizeUrlObject = (url) => +// If url was parsed by url.parse or new URL: +// - hostname will be set +// - host will be hostname[:port] +// - port will be set if it was explicit in the parsed string +// Otherwise, url was from request options: +// - hostname or host may be set +// - host shall not have port encoded +({ + protocol: url.protocol, + auth: url.auth, + hostname: url.hostname || url.host || 'localhost', + port: url.port, + pathname: url.pathname, + search: url.search, +}); +const convertHeaders = (headers) => { + const result = []; + for (const name of Object.keys(headers)) { + result[name.toLowerCase()] = headers[name]; + } + return result; +}; +var CacheableRequest$1 = CacheableRequest; + +// We define these manually to ensure they're always copied +// even if they would move up the prototype chain +// https://nodejs.org/api/http.html#http_class_http_incomingmessage +const knownProperties = [ + 'aborted', + 'complete', + 'headers', + 'httpVersion', + 'httpVersionMinor', + 'httpVersionMajor', + 'method', + 'rawHeaders', + 'rawTrailers', + 'setTimeout', + 'socket', + 'statusCode', + 'statusMessage', + 'trailers', + 'url' +]; + +var mimicResponse$1 = (fromStream, toStream) => { + if (toStream._readableState.autoDestroy) { + throw new Error('The second stream must have the `autoDestroy` option set to `false`'); + } + + const fromProperties = new Set(Object.keys(fromStream).concat(knownProperties)); + + const properties = {}; + + for (const property of fromProperties) { + // Don't overwrite existing properties. + if (property in toStream) { + continue; + } + + properties[property] = { + get() { + const value = fromStream[property]; + const isFunction = typeof value === 'function'; + + return isFunction ? value.bind(fromStream) : value; + }, + set(value) { + fromStream[property] = value; + }, + enumerable: true, + configurable: false + }; + } + + Object.defineProperties(toStream, properties); + + fromStream.once('aborted', () => { + toStream.destroy(); + + toStream.emit('aborted'); + }); + + fromStream.once('close', () => { + if (fromStream.complete) { + if (toStream.readable) { + toStream.once('end', () => { + toStream.emit('close'); + }); + } else { + toStream.emit('close'); + } + } else { + toStream.emit('close'); + } + }); + + return toStream; +}; + +const {Transform, PassThrough: PassThrough$3} = Stream$3; +const zlib = zlib$1; +const mimicResponse = mimicResponse$1; + +var decompressResponse = response => { + const contentEncoding = (response.headers['content-encoding'] || '').toLowerCase(); + + if (!['gzip', 'deflate', 'br'].includes(contentEncoding)) { + return response; + } + + // TODO: Remove this when targeting Node.js 12. + const isBrotli = contentEncoding === 'br'; + if (isBrotli && typeof zlib.createBrotliDecompress !== 'function') { + response.destroy(new Error('Brotli is not supported on Node.js < 12')); + return response; + } + + let isEmpty = true; + + const checker = new Transform({ + transform(data, _encoding, callback) { + isEmpty = false; + + callback(null, data); + }, + + flush(callback) { + callback(); + } + }); + + const finalStream = new PassThrough$3({ + autoDestroy: false, + destroy(error, callback) { + response.destroy(); + + callback(error); + } + }); + + const decompressStream = isBrotli ? zlib.createBrotliDecompress() : zlib.createUnzip(); + + decompressStream.once('error', error => { + if (isEmpty && !response.readable) { + finalStream.end(); + return; + } + + finalStream.destroy(error); + }); + + mimicResponse(response, finalStream); + response.pipe(checker).pipe(decompressStream).pipe(finalStream); + + return finalStream; +}; + +var decompressResponse$1 = /*@__PURE__*/getDefaultExportFromCjs(decompressResponse); + +const isFunction$e = (value) => (typeof value === "function"); + +const isAsyncIterable = (value) => (isFunction$e(value[Symbol.asyncIterator])); +async function* readStream(readable) { + const reader = readable.getReader(); + while (true) { + const { done, value } = await reader.read(); + if (done) { + break; + } + yield value; + } +} +const getStreamIterator = (source) => { + if (isAsyncIterable(source)) { + return source; + } + if (isFunction$e(source.getReader)) { + return readStream(source); + } + throw new TypeError("Unsupported data source: Expected either ReadableStream or async iterable."); +}; + +const alphabet = "abcdefghijklmnopqrstuvwxyz0123456789"; +function createBoundary() { + let size = 16; + let res = ""; + while (size--) { + res += alphabet[(Math.random() * alphabet.length) << 0]; + } + return res; +} + +const normalizeValue = (value) => String(value) + .replace(/\r|\n/g, (match, i, str) => { + if ((match === "\r" && str[i + 1] !== "\n") + || (match === "\n" && str[i - 1] !== "\r")) { + return "\r\n"; + } + return match; +}); + +const getType$1 = (value) => (Object.prototype.toString.call(value).slice(8, -1).toLowerCase()); +function isPlainObject$9(value) { + if (getType$1(value) !== "object") { + return false; + } + const pp = Object.getPrototypeOf(value); + if (pp === null || pp === undefined) { + return true; + } + const Ctor = pp.constructor && pp.constructor.toString(); + return Ctor === Object.toString(); +} + +function getProperty(target, prop) { + if (typeof prop === "string") { + for (const [name, value] of Object.entries(target)) { + if (prop.toLowerCase() === name.toLowerCase()) { + return value; + } + } + } + return undefined; +} +const proxyHeaders = (object) => new Proxy(object, { + get: (target, prop) => getProperty(target, prop), + has: (target, prop) => getProperty(target, prop) !== undefined +}); + +const isFormData$1 = (value) => Boolean(value + && isFunction$e(value.constructor) + && value[Symbol.toStringTag] === "FormData" + && isFunction$e(value.append) + && isFunction$e(value.getAll) + && isFunction$e(value.entries) + && isFunction$e(value[Symbol.iterator])); + +const escapeName = (name) => String(name) + .replace(/\r/g, "%0D") + .replace(/\n/g, "%0A") + .replace(/"/g, "%22"); + +const isFile$1 = (value) => Boolean(value + && typeof value === "object" + && isFunction$e(value.constructor) + && value[Symbol.toStringTag] === "File" + && isFunction$e(value.stream) + && value.name != null); + +var __classPrivateFieldSet$2 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +}; +var __classPrivateFieldGet$3 = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var _FormDataEncoder_instances, _FormDataEncoder_CRLF, _FormDataEncoder_CRLF_BYTES, _FormDataEncoder_CRLF_BYTES_LENGTH, _FormDataEncoder_DASHES, _FormDataEncoder_encoder, _FormDataEncoder_footer, _FormDataEncoder_form, _FormDataEncoder_options, _FormDataEncoder_getFieldHeader, _FormDataEncoder_getContentLength; +const defaultOptions$3 = { + enableAdditionalHeaders: false +}; +const readonlyProp = { writable: false, configurable: false }; +class FormDataEncoder { + constructor(form, boundaryOrOptions, options) { + _FormDataEncoder_instances.add(this); + _FormDataEncoder_CRLF.set(this, "\r\n"); + _FormDataEncoder_CRLF_BYTES.set(this, void 0); + _FormDataEncoder_CRLF_BYTES_LENGTH.set(this, void 0); + _FormDataEncoder_DASHES.set(this, "-".repeat(2)); + _FormDataEncoder_encoder.set(this, new TextEncoder()); + _FormDataEncoder_footer.set(this, void 0); + _FormDataEncoder_form.set(this, void 0); + _FormDataEncoder_options.set(this, void 0); + if (!isFormData$1(form)) { + throw new TypeError("Expected first argument to be a FormData instance."); + } + let boundary; + if (isPlainObject$9(boundaryOrOptions)) { + options = boundaryOrOptions; + } + else { + boundary = boundaryOrOptions; + } + if (!boundary) { + boundary = createBoundary(); + } + if (typeof boundary !== "string") { + throw new TypeError("Expected boundary argument to be a string."); + } + if (options && !isPlainObject$9(options)) { + throw new TypeError("Expected options argument to be an object."); + } + __classPrivateFieldSet$2(this, _FormDataEncoder_form, Array.from(form.entries()), "f"); + __classPrivateFieldSet$2(this, _FormDataEncoder_options, { ...defaultOptions$3, ...options }, "f"); + __classPrivateFieldSet$2(this, _FormDataEncoder_CRLF_BYTES, __classPrivateFieldGet$3(this, _FormDataEncoder_encoder, "f").encode(__classPrivateFieldGet$3(this, _FormDataEncoder_CRLF, "f")), "f"); + __classPrivateFieldSet$2(this, _FormDataEncoder_CRLF_BYTES_LENGTH, __classPrivateFieldGet$3(this, _FormDataEncoder_CRLF_BYTES, "f").byteLength, "f"); + this.boundary = `form-data-boundary-${boundary}`; + this.contentType = `multipart/form-data; boundary=${this.boundary}`; + __classPrivateFieldSet$2(this, _FormDataEncoder_footer, __classPrivateFieldGet$3(this, _FormDataEncoder_encoder, "f").encode(`${__classPrivateFieldGet$3(this, _FormDataEncoder_DASHES, "f")}${this.boundary}${__classPrivateFieldGet$3(this, _FormDataEncoder_DASHES, "f")}${__classPrivateFieldGet$3(this, _FormDataEncoder_CRLF, "f").repeat(2)}`), "f"); + const headers = { + "Content-Type": this.contentType + }; + const contentLength = __classPrivateFieldGet$3(this, _FormDataEncoder_instances, "m", _FormDataEncoder_getContentLength).call(this); + if (contentLength) { + this.contentLength = contentLength; + headers["Content-Length"] = contentLength; + } + this.headers = proxyHeaders(Object.freeze(headers)); + Object.defineProperties(this, { + boundary: readonlyProp, + contentType: readonlyProp, + contentLength: readonlyProp, + headers: readonlyProp + }); + } + getContentLength() { + return this.contentLength == null ? undefined : Number(this.contentLength); + } + *values() { + for (const [name, raw] of __classPrivateFieldGet$3(this, _FormDataEncoder_form, "f")) { + const value = isFile$1(raw) ? raw : __classPrivateFieldGet$3(this, _FormDataEncoder_encoder, "f").encode(normalizeValue(raw)); + yield __classPrivateFieldGet$3(this, _FormDataEncoder_instances, "m", _FormDataEncoder_getFieldHeader).call(this, name, value); + yield value; + yield __classPrivateFieldGet$3(this, _FormDataEncoder_CRLF_BYTES, "f"); + } + yield __classPrivateFieldGet$3(this, _FormDataEncoder_footer, "f"); + } + async *encode() { + for (const part of this.values()) { + if (isFile$1(part)) { + yield* getStreamIterator(part.stream()); + } + else { + yield part; + } + } + } + [(_FormDataEncoder_CRLF = new WeakMap(), _FormDataEncoder_CRLF_BYTES = new WeakMap(), _FormDataEncoder_CRLF_BYTES_LENGTH = new WeakMap(), _FormDataEncoder_DASHES = new WeakMap(), _FormDataEncoder_encoder = new WeakMap(), _FormDataEncoder_footer = new WeakMap(), _FormDataEncoder_form = new WeakMap(), _FormDataEncoder_options = new WeakMap(), _FormDataEncoder_instances = new WeakSet(), _FormDataEncoder_getFieldHeader = function _FormDataEncoder_getFieldHeader(name, value) { + let header = ""; + header += `${__classPrivateFieldGet$3(this, _FormDataEncoder_DASHES, "f")}${this.boundary}${__classPrivateFieldGet$3(this, _FormDataEncoder_CRLF, "f")}`; + header += `Content-Disposition: form-data; name="${escapeName(name)}"`; + if (isFile$1(value)) { + header += `; filename="${escapeName(value.name)}"${__classPrivateFieldGet$3(this, _FormDataEncoder_CRLF, "f")}`; + header += `Content-Type: ${value.type || "application/octet-stream"}`; + } + const size = isFile$1(value) ? value.size : value.byteLength; + if (__classPrivateFieldGet$3(this, _FormDataEncoder_options, "f").enableAdditionalHeaders === true + && size != null + && !isNaN(size)) { + header += `${__classPrivateFieldGet$3(this, _FormDataEncoder_CRLF, "f")}Content-Length: ${isFile$1(value) ? value.size : value.byteLength}`; + } + return __classPrivateFieldGet$3(this, _FormDataEncoder_encoder, "f").encode(`${header}${__classPrivateFieldGet$3(this, _FormDataEncoder_CRLF, "f").repeat(2)}`); + }, _FormDataEncoder_getContentLength = function _FormDataEncoder_getContentLength() { + let length = 0; + for (const [name, raw] of __classPrivateFieldGet$3(this, _FormDataEncoder_form, "f")) { + const value = isFile$1(raw) ? raw : __classPrivateFieldGet$3(this, _FormDataEncoder_encoder, "f").encode(normalizeValue(raw)); + const size = isFile$1(value) ? value.size : value.byteLength; + if (size == null || isNaN(size)) { + return undefined; + } + length += __classPrivateFieldGet$3(this, _FormDataEncoder_instances, "m", _FormDataEncoder_getFieldHeader).call(this, name, value).byteLength; + length += size; + length += __classPrivateFieldGet$3(this, _FormDataEncoder_CRLF_BYTES_LENGTH, "f"); + } + return String(length + __classPrivateFieldGet$3(this, _FormDataEncoder_footer, "f").byteLength); + }, Symbol.iterator)]() { + return this.values(); + } + [Symbol.asyncIterator]() { + return this.encode(); + } +} + +function isFormData(body) { + return is$5.nodeStream(body) && is$5.function_(body.getBoundary); +} + +async function getBodySize(body, headers) { + if (headers && 'content-length' in headers) { + return Number(headers['content-length']); + } + if (!body) { + return 0; + } + if (is$5.string(body)) { + return node_buffer.Buffer.byteLength(body); + } + if (is$5.buffer(body)) { + return body.length; + } + if (isFormData(body)) { + return node_util.promisify(body.getLength.bind(body))(); + } + return undefined; +} + +function proxyEvents$2(from, to, events) { + const eventFunctions = {}; + for (const event of events) { + const eventFunction = (...args) => { + to.emit(event, ...args); + }; + eventFunctions[event] = eventFunction; + from.on(event, eventFunction); + } + return () => { + for (const [event, eventFunction] of Object.entries(eventFunctions)) { + from.off(event, eventFunction); + } + }; +} + +// When attaching listeners, it's very easy to forget about them. +// Especially if you do error handling and set timeouts. +// So instead of checking if it's proper to throw an error on every timeout ever, +// use this simple tool which will remove all listeners you have attached. +function unhandle() { + const handlers = []; + return { + once(origin, event, fn) { + origin.once(event, fn); + handlers.push({ origin, event, fn }); + }, + unhandleAll() { + for (const handler of handlers) { + const { origin, event, fn } = handler; + origin.removeListener(event, fn); + } + handlers.length = 0; + }, + }; +} + +const reentry = Symbol('reentry'); +const noop$6 = () => { }; +class TimeoutError extends Error { + constructor(threshold, event) { + super(`Timeout awaiting '${event}' for ${threshold}ms`); + Object.defineProperty(this, "event", { + enumerable: true, + configurable: true, + writable: true, + value: event + }); + Object.defineProperty(this, "code", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.name = 'TimeoutError'; + this.code = 'ETIMEDOUT'; + } +} +function timedOut(request, delays, options) { + if (reentry in request) { + return noop$6; + } + request[reentry] = true; + const cancelers = []; + const { once, unhandleAll } = unhandle(); + const addTimeout = (delay, callback, event) => { + const timeout = setTimeout(callback, delay, delay, event); + timeout.unref?.(); + const cancel = () => { + clearTimeout(timeout); + }; + cancelers.push(cancel); + return cancel; + }; + const { host, hostname } = options; + const timeoutHandler = (delay, event) => { + request.destroy(new TimeoutError(delay, event)); + }; + const cancelTimeouts = () => { + for (const cancel of cancelers) { + cancel(); + } + unhandleAll(); + }; + request.once('error', error => { + cancelTimeouts(); + // Save original behavior + /* istanbul ignore next */ + if (request.listenerCount('error') === 0) { + throw error; + } + }); + if (typeof delays.request !== 'undefined') { + const cancelTimeout = addTimeout(delays.request, timeoutHandler, 'request'); + once(request, 'response', (response) => { + once(response, 'end', cancelTimeout); + }); + } + if (typeof delays.socket !== 'undefined') { + const { socket } = delays; + const socketTimeoutHandler = () => { + timeoutHandler(socket, 'socket'); + }; + request.setTimeout(socket, socketTimeoutHandler); + // `request.setTimeout(0)` causes a memory leak. + // We can just remove the listener and forget about the timer - it's unreffed. + // See https://github.com/sindresorhus/got/issues/690 + cancelers.push(() => { + request.removeListener('timeout', socketTimeoutHandler); + }); + } + const hasLookup = typeof delays.lookup !== 'undefined'; + const hasConnect = typeof delays.connect !== 'undefined'; + const hasSecureConnect = typeof delays.secureConnect !== 'undefined'; + const hasSend = typeof delays.send !== 'undefined'; + if (hasLookup || hasConnect || hasSecureConnect || hasSend) { + once(request, 'socket', (socket) => { + const { socketPath } = request; + /* istanbul ignore next: hard to test */ + if (socket.connecting) { + const hasPath = Boolean(socketPath ?? net.isIP(hostname ?? host ?? '') !== 0); + if (hasLookup && !hasPath && typeof socket.address().address === 'undefined') { + const cancelTimeout = addTimeout(delays.lookup, timeoutHandler, 'lookup'); + once(socket, 'lookup', cancelTimeout); + } + if (hasConnect) { + const timeConnect = () => addTimeout(delays.connect, timeoutHandler, 'connect'); + if (hasPath) { + once(socket, 'connect', timeConnect()); + } + else { + once(socket, 'lookup', (error) => { + if (error === null) { + once(socket, 'connect', timeConnect()); + } + }); + } + } + if (hasSecureConnect && options.protocol === 'https:') { + once(socket, 'connect', () => { + const cancelTimeout = addTimeout(delays.secureConnect, timeoutHandler, 'secureConnect'); + once(socket, 'secureConnect', cancelTimeout); + }); + } + } + if (hasSend) { + const timeRequest = () => addTimeout(delays.send, timeoutHandler, 'send'); + /* istanbul ignore next: hard to test */ + if (socket.connecting) { + once(socket, 'connect', () => { + once(request, 'upload-complete', timeRequest()); + }); + } + else { + once(request, 'upload-complete', timeRequest()); + } + } + }); + } + if (typeof delays.response !== 'undefined') { + once(request, 'upload-complete', () => { + const cancelTimeout = addTimeout(delays.response, timeoutHandler, 'response'); + once(request, 'response', cancelTimeout); + }); + } + if (typeof delays.read !== 'undefined') { + once(request, 'response', (response) => { + const cancelTimeout = addTimeout(delays.read, timeoutHandler, 'read'); + once(response, 'end', cancelTimeout); + }); + } + return cancelTimeouts; +} + +function urlToOptions$1(url) { + // Cast to URL + url = url; + const options = { + protocol: url.protocol, + hostname: is$5.string(url.hostname) && url.hostname.startsWith('[') ? url.hostname.slice(1, -1) : url.hostname, + host: url.host, + hash: url.hash, + search: url.search, + pathname: url.pathname, + href: url.href, + path: `${url.pathname || ''}${url.search || ''}`, + }; + if (is$5.string(url.port) && url.port.length > 0) { + options.port = Number(url.port); + } + if (url.username || url.password) { + options.auth = `${url.username || ''}:${url.password || ''}`; + } + return options; +} + +class WeakableMap { + constructor() { + Object.defineProperty(this, "weakMap", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "map", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.weakMap = new WeakMap(); + this.map = new Map(); + } + set(key, value) { + if (typeof key === 'object') { + this.weakMap.set(key, value); + } + else { + this.map.set(key, value); + } + } + get(key) { + if (typeof key === 'object') { + return this.weakMap.get(key); + } + return this.map.get(key); + } + has(key) { + if (typeof key === 'object') { + return this.weakMap.has(key); + } + return this.map.has(key); + } +} + +const calculateRetryDelay = ({ attemptCount, retryOptions, error, retryAfter, computedValue, }) => { + if (error.name === 'RetryError') { + return 1; + } + if (attemptCount > retryOptions.limit) { + return 0; + } + const hasMethod = retryOptions.methods.includes(error.options.method); + const hasErrorCode = retryOptions.errorCodes.includes(error.code); + const hasStatusCode = error.response && retryOptions.statusCodes.includes(error.response.statusCode); + if (!hasMethod || (!hasErrorCode && !hasStatusCode)) { + return 0; + } + if (error.response) { + if (retryAfter) { + // In this case `computedValue` is `options.request.timeout` + if (retryAfter > computedValue) { + return 0; + } + return retryAfter; + } + if (error.response.statusCode === 413) { + return 0; + } + } + const noise = Math.random() * retryOptions.noise; + return Math.min(((2 ** (attemptCount - 1)) * 1000), retryOptions.backoffLimit) + noise; +}; +var calculateRetryDelay$1 = calculateRetryDelay; + +const {Resolver: AsyncResolver} = node_dns.promises; + +const kCacheableLookupCreateConnection = Symbol('cacheableLookupCreateConnection'); +const kCacheableLookupInstance = Symbol('cacheableLookupInstance'); +const kExpires = Symbol('expires'); + +const supportsALL = typeof node_dns.ALL === 'number'; + +const verifyAgent = agent => { + if (!(agent && typeof agent.createConnection === 'function')) { + throw new Error('Expected an Agent instance as the first argument'); + } +}; + +const map4to6 = entries => { + for (const entry of entries) { + if (entry.family === 6) { + continue; + } + + entry.address = `::ffff:${entry.address}`; + entry.family = 6; + } +}; + +const getIfaceInfo = () => { + let has4 = false; + let has6 = false; + + for (const device of Object.values(os$5.networkInterfaces())) { + for (const iface of device) { + if (iface.internal) { + continue; + } + + if (iface.family === 'IPv6') { + has6 = true; + } else { + has4 = true; + } + + if (has4 && has6) { + return {has4, has6}; + } + } + } + + return {has4, has6}; +}; + +const isIterable$3 = map => { + return Symbol.iterator in map; +}; + +const ignoreNoResultErrors = dnsPromise => { + return dnsPromise.catch(error => { + if ( + error.code === 'ENODATA' || + error.code === 'ENOTFOUND' || + error.code === 'ENOENT' // Windows: name exists, but not this record type + ) { + return []; + } + + throw error; + }); +}; + +const ttl = {ttl: true}; +const all = {all: true}; +const all4 = {all: true, family: 4}; +const all6 = {all: true, family: 6}; + +class CacheableLookup { + constructor({ + cache = new Map(), + maxTtl = Infinity, + fallbackDuration = 3600, + errorTtl = 0.15, + resolver = new AsyncResolver(), + lookup = node_dns.lookup + } = {}) { + this.maxTtl = maxTtl; + this.errorTtl = errorTtl; + + this._cache = cache; + this._resolver = resolver; + this._dnsLookup = lookup && node_util.promisify(lookup); + this.stats = { + cache: 0, + query: 0 + }; + + if (this._resolver instanceof AsyncResolver) { + this._resolve4 = this._resolver.resolve4.bind(this._resolver); + this._resolve6 = this._resolver.resolve6.bind(this._resolver); + } else { + this._resolve4 = node_util.promisify(this._resolver.resolve4.bind(this._resolver)); + this._resolve6 = node_util.promisify(this._resolver.resolve6.bind(this._resolver)); + } + + this._iface = getIfaceInfo(); + + this._pending = {}; + this._nextRemovalTime = false; + this._hostnamesToFallback = new Set(); + + this.fallbackDuration = fallbackDuration; + + if (fallbackDuration > 0) { + const interval = setInterval(() => { + this._hostnamesToFallback.clear(); + }, fallbackDuration * 1000); + + /* istanbul ignore next: There is no `interval.unref()` when running inside an Electron renderer */ + if (interval.unref) { + interval.unref(); + } + + this._fallbackInterval = interval; + } + + this.lookup = this.lookup.bind(this); + this.lookupAsync = this.lookupAsync.bind(this); + } + + set servers(servers) { + this.clear(); + + this._resolver.setServers(servers); + } + + get servers() { + return this._resolver.getServers(); + } + + lookup(hostname, options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } else if (typeof options === 'number') { + options = { + family: options + }; + } + + if (!callback) { + throw new Error('Callback must be a function.'); + } + + // eslint-disable-next-line promise/prefer-await-to-then + this.lookupAsync(hostname, options).then(result => { + if (options.all) { + callback(null, result); + } else { + callback(null, result.address, result.family, result.expires, result.ttl, result.source); + } + }, callback); + } + + async lookupAsync(hostname, options = {}) { + if (typeof options === 'number') { + options = { + family: options + }; + } + + let cached = await this.query(hostname); + + if (options.family === 6) { + const filtered = cached.filter(entry => entry.family === 6); + + if (options.hints & node_dns.V4MAPPED) { + if ((supportsALL && options.hints & node_dns.ALL) || filtered.length === 0) { + map4to6(cached); + } else { + cached = filtered; + } + } else { + cached = filtered; + } + } else if (options.family === 4) { + cached = cached.filter(entry => entry.family === 4); + } + + if (options.hints & node_dns.ADDRCONFIG) { + const {_iface} = this; + cached = cached.filter(entry => entry.family === 6 ? _iface.has6 : _iface.has4); + } + + if (cached.length === 0) { + const error = new Error(`cacheableLookup ENOTFOUND ${hostname}`); + error.code = 'ENOTFOUND'; + error.hostname = hostname; + + throw error; + } + + if (options.all) { + return cached; + } + + return cached[0]; + } + + async query(hostname) { + let source = 'cache'; + let cached = await this._cache.get(hostname); + + if (cached) { + this.stats.cache++; + } + + if (!cached) { + const pending = this._pending[hostname]; + if (pending) { + this.stats.cache++; + cached = await pending; + } else { + source = 'query'; + const newPromise = this.queryAndCache(hostname); + this._pending[hostname] = newPromise; + this.stats.query++; + try { + cached = await newPromise; + } finally { + delete this._pending[hostname]; + } + } + } + + cached = cached.map(entry => { + return {...entry, source}; + }); + + return cached; + } + + async _resolve(hostname) { + // ANY is unsafe as it doesn't trigger new queries in the underlying server. + const [A, AAAA] = await Promise.all([ + ignoreNoResultErrors(this._resolve4(hostname, ttl)), + ignoreNoResultErrors(this._resolve6(hostname, ttl)) + ]); + + let aTtl = 0; + let aaaaTtl = 0; + let cacheTtl = 0; + + const now = Date.now(); + + for (const entry of A) { + entry.family = 4; + entry.expires = now + (entry.ttl * 1000); + + aTtl = Math.max(aTtl, entry.ttl); + } + + for (const entry of AAAA) { + entry.family = 6; + entry.expires = now + (entry.ttl * 1000); + + aaaaTtl = Math.max(aaaaTtl, entry.ttl); + } + + if (A.length > 0) { + if (AAAA.length > 0) { + cacheTtl = Math.min(aTtl, aaaaTtl); + } else { + cacheTtl = aTtl; + } + } else { + cacheTtl = aaaaTtl; + } + + return { + entries: [ + ...A, + ...AAAA + ], + cacheTtl + }; + } + + async _lookup(hostname) { + try { + const [A, AAAA] = await Promise.all([ + // Passing {all: true} doesn't return all IPv4 and IPv6 entries. + // See https://github.com/szmarczak/cacheable-lookup/issues/42 + ignoreNoResultErrors(this._dnsLookup(hostname, all4)), + ignoreNoResultErrors(this._dnsLookup(hostname, all6)) + ]); + + return { + entries: [ + ...A, + ...AAAA + ], + cacheTtl: 0 + }; + } catch { + return { + entries: [], + cacheTtl: 0 + }; + } + } + + async _set(hostname, data, cacheTtl) { + if (this.maxTtl > 0 && cacheTtl > 0) { + cacheTtl = Math.min(cacheTtl, this.maxTtl) * 1000; + data[kExpires] = Date.now() + cacheTtl; + + try { + await this._cache.set(hostname, data, cacheTtl); + } catch (error) { + this.lookupAsync = async () => { + const cacheError = new Error('Cache Error. Please recreate the CacheableLookup instance.'); + cacheError.cause = error; + + throw cacheError; + }; + } + + if (isIterable$3(this._cache)) { + this._tick(cacheTtl); + } + } + } + + async queryAndCache(hostname) { + if (this._hostnamesToFallback.has(hostname)) { + return this._dnsLookup(hostname, all); + } + + let query = await this._resolve(hostname); + + if (query.entries.length === 0 && this._dnsLookup) { + query = await this._lookup(hostname); + + if (query.entries.length !== 0 && this.fallbackDuration > 0) { + // Use `dns.lookup(...)` for that particular hostname + this._hostnamesToFallback.add(hostname); + } + } + + const cacheTtl = query.entries.length === 0 ? this.errorTtl : query.cacheTtl; + await this._set(hostname, query.entries, cacheTtl); + + return query.entries; + } + + _tick(ms) { + const nextRemovalTime = this._nextRemovalTime; + + if (!nextRemovalTime || ms < nextRemovalTime) { + clearTimeout(this._removalTimeout); + + this._nextRemovalTime = ms; + + this._removalTimeout = setTimeout(() => { + this._nextRemovalTime = false; + + let nextExpiry = Infinity; + + const now = Date.now(); + + for (const [hostname, entries] of this._cache) { + const expires = entries[kExpires]; + + if (now >= expires) { + this._cache.delete(hostname); + } else if (expires < nextExpiry) { + nextExpiry = expires; + } + } + + if (nextExpiry !== Infinity) { + this._tick(nextExpiry - now); + } + }, ms); + + /* istanbul ignore next: There is no `timeout.unref()` when running inside an Electron renderer */ + if (this._removalTimeout.unref) { + this._removalTimeout.unref(); + } + } + } + + install(agent) { + verifyAgent(agent); + + if (kCacheableLookupCreateConnection in agent) { + throw new Error('CacheableLookup has been already installed'); + } + + agent[kCacheableLookupCreateConnection] = agent.createConnection; + agent[kCacheableLookupInstance] = this; + + agent.createConnection = (options, callback) => { + if (!('lookup' in options)) { + options.lookup = this.lookup; + } + + return agent[kCacheableLookupCreateConnection](options, callback); + }; + } + + uninstall(agent) { + verifyAgent(agent); + + if (agent[kCacheableLookupCreateConnection]) { + if (agent[kCacheableLookupInstance] !== this) { + throw new Error('The agent is not owned by this CacheableLookup instance'); + } + + agent.createConnection = agent[kCacheableLookupCreateConnection]; + + delete agent[kCacheableLookupCreateConnection]; + delete agent[kCacheableLookupInstance]; + } + } + + updateInterfaceInfo() { + const {_iface} = this; + + this._iface = getIfaceInfo(); + + if ((_iface.has4 && !this._iface.has4) || (_iface.has6 && !this._iface.has6)) { + this._cache.clear(); + } + } + + clear(hostname) { + if (hostname) { + this._cache.delete(hostname); + return; + } + + this._cache.clear(); + } +} + +let QuickLRU$2 = class QuickLRU { + constructor(options = {}) { + if (!(options.maxSize && options.maxSize > 0)) { + throw new TypeError('`maxSize` must be a number greater than 0'); + } + + this.maxSize = options.maxSize; + this.onEviction = options.onEviction; + this.cache = new Map(); + this.oldCache = new Map(); + this._size = 0; + } + + _set(key, value) { + this.cache.set(key, value); + this._size++; + + if (this._size >= this.maxSize) { + this._size = 0; + + if (typeof this.onEviction === 'function') { + for (const [key, value] of this.oldCache.entries()) { + this.onEviction(key, value); + } + } + + this.oldCache = this.cache; + this.cache = new Map(); + } + } + + get(key) { + if (this.cache.has(key)) { + return this.cache.get(key); + } + + if (this.oldCache.has(key)) { + const value = this.oldCache.get(key); + this.oldCache.delete(key); + this._set(key, value); + return value; + } + } + + set(key, value) { + if (this.cache.has(key)) { + this.cache.set(key, value); + } else { + this._set(key, value); + } + + return this; + } + + has(key) { + return this.cache.has(key) || this.oldCache.has(key); + } + + peek(key) { + if (this.cache.has(key)) { + return this.cache.get(key); + } + + if (this.oldCache.has(key)) { + return this.oldCache.get(key); + } + } + + 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; + } + + * keys() { + for (const [key] of this) { + yield key; + } + } + + * values() { + for (const [, value] of this) { + yield value; + } + } + + * [Symbol.iterator]() { + for (const item of this.cache) { + yield item; + } + + for (const item of this.oldCache) { + const [key] = item; + if (!this.cache.has(key)) { + yield item; + } + } + } + + get 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); + } +}; + +var quickLru = QuickLRU$2; + +var delayAsyncDestroy$2 = stream => { + if (stream.listenerCount('error') !== 0) { + return stream; + } + + stream.__destroy = stream._destroy; + stream._destroy = (...args) => { + const callback = args.pop(); + + stream.__destroy(...args, async error => { + await Promise.resolve(); + callback(error); + }); + }; + + const onError = error => { + // eslint-disable-next-line promise/prefer-await-to-then + Promise.resolve().then(() => { + stream.emit('error', error); + }); + }; + + stream.once('error', onError); + + // eslint-disable-next-line promise/prefer-await-to-then + Promise.resolve().then(() => { + stream.off('error', onError); + }); + + return stream; +}; + +// See https://github.com/facebook/jest/issues/2549 +// eslint-disable-next-line node/prefer-global/url +const {URL: URL$7} = require$$0$e; +const EventEmitter$1 = require$$2$3; +const tls$3 = require$$1$3; +const http2$2 = require$$3$4; +const QuickLRU$1 = quickLru; +const delayAsyncDestroy$1 = delayAsyncDestroy$2; + +const kCurrentStreamCount = Symbol('currentStreamCount'); +const kRequest = Symbol('request'); +const kOriginSet = Symbol('cachedOriginSet'); +const kGracefullyClosing = Symbol('gracefullyClosing'); +const kLength = Symbol('length'); + +const nameKeys = [ + // Not an Agent option actually + 'createConnection', + + // `http2.connect()` options + 'maxDeflateDynamicTableSize', + 'maxSettings', + 'maxSessionMemory', + 'maxHeaderListPairs', + 'maxOutstandingPings', + 'maxReservedRemoteStreams', + 'maxSendHeaderBlockLength', + 'paddingStrategy', + 'peerMaxConcurrentStreams', + 'settings', + + // `tls.connect()` source options + 'family', + 'localAddress', + 'rejectUnauthorized', + + // `tls.connect()` secure context options + 'pskCallback', + 'minDHSize', + + // `tls.connect()` destination options + // - `servername` is automatically validated, skip it + // - `host` and `port` just describe the destination server, + 'path', + 'socket', + + // `tls.createSecureContext()` options + 'ca', + 'cert', + 'sigalgs', + 'ciphers', + 'clientCertEngine', + 'crl', + 'dhparam', + 'ecdhCurve', + 'honorCipherOrder', + 'key', + 'privateKeyEngine', + 'privateKeyIdentifier', + 'maxVersion', + 'minVersion', + 'pfx', + 'secureOptions', + 'secureProtocol', + 'sessionIdContext', + 'ticketKeys' +]; + +const getSortedIndex = (array, value, compare) => { + let low = 0; + let high = array.length; + + while (low < high) { + const mid = (low + high) >>> 1; + + if (compare(array[mid], value)) { + low = mid + 1; + } else { + high = mid; + } + } + + return low; +}; + +const compareSessions = (a, b) => a.remoteSettings.maxConcurrentStreams > b.remoteSettings.maxConcurrentStreams; + +// See https://tools.ietf.org/html/rfc8336 +const closeCoveredSessions = (where, session) => { + // Clients SHOULD NOT emit new requests on any connection whose Origin + // Set is a proper subset of another connection's Origin Set, and they + // SHOULD close it once all outstanding requests are satisfied. + for (let index = 0; index < where.length; index++) { + const coveredSession = where[index]; + + if ( + // Unfortunately `.every()` returns true for an empty array + coveredSession[kOriginSet].length > 0 + + // The set is a proper subset when its length is less than the other set. + && coveredSession[kOriginSet].length < session[kOriginSet].length + + // And the other set includes all elements of the subset. + && coveredSession[kOriginSet].every(origin => session[kOriginSet].includes(origin)) + + // Makes sure that the session can handle all requests from the covered session. + && (coveredSession[kCurrentStreamCount] + session[kCurrentStreamCount]) <= session.remoteSettings.maxConcurrentStreams + ) { + // This allows pending requests to finish and prevents making new requests. + gracefullyClose(coveredSession); + } + } +}; + +// This is basically inverted `closeCoveredSessions(...)`. +const closeSessionIfCovered = (where, coveredSession) => { + for (let index = 0; index < where.length; index++) { + const session = where[index]; + + if ( + coveredSession[kOriginSet].length > 0 + && coveredSession[kOriginSet].length < session[kOriginSet].length + && coveredSession[kOriginSet].every(origin => session[kOriginSet].includes(origin)) + && (coveredSession[kCurrentStreamCount] + session[kCurrentStreamCount]) <= session.remoteSettings.maxConcurrentStreams + ) { + gracefullyClose(coveredSession); + + return true; + } + } + + return false; +}; + +const gracefullyClose = session => { + session[kGracefullyClosing] = true; + + if (session[kCurrentStreamCount] === 0) { + session.close(); + } +}; + +let Agent$4 = class Agent extends EventEmitter$1 { + constructor({timeout = 0, maxSessions = Number.POSITIVE_INFINITY, maxEmptySessions = 10, maxCachedTlsSessions = 100} = {}) { + super(); + + // SESSIONS[NORMALIZED_OPTIONS] = []; + this.sessions = {}; + + // The queue for creating new sessions. It looks like this: + // QUEUE[NORMALIZED_OPTIONS][NORMALIZED_ORIGIN] = ENTRY_FUNCTION + // + // It's faster when there are many origins. If there's only one, then QUEUE[`${options}:${origin}`] is faster. + // I guess object creation / deletion is causing the slowdown. + // + // The entry function has `listeners`, `completed` and `destroyed` properties. + // `listeners` is an array of objects containing `resolve` and `reject` functions. + // `completed` is a boolean. It's set to true after ENTRY_FUNCTION is executed. + // `destroyed` is a boolean. If it's set to true, the session will be destroyed if hasn't connected yet. + this.queue = {}; + + // Each session will use this timeout value. + this.timeout = timeout; + + // Max sessions in total + this.maxSessions = maxSessions; + + // Max empty sessions in total + this.maxEmptySessions = maxEmptySessions; + + this._emptySessionCount = 0; + this._sessionCount = 0; + + // We don't support push streams by default. + this.settings = { + enablePush: false, + initialWindowSize: 1024 * 1024 * 32 // 32MB, see https://github.com/nodejs/node/issues/38426 + }; + + // Reusing TLS sessions increases performance. + this.tlsSessionCache = new QuickLRU$1({maxSize: maxCachedTlsSessions}); + } + + get protocol() { + return 'https:'; + } + + normalizeOptions(options) { + let normalized = ''; + + for (let index = 0; index < nameKeys.length; index++) { + const key = nameKeys[index]; + + normalized += ':'; + + if (options && options[key] !== undefined) { + normalized += options[key]; + } + } + + return normalized; + } + + _processQueue() { + if (this._sessionCount >= this.maxSessions) { + this.closeEmptySessions(this.maxSessions - this._sessionCount + 1); + return; + } + + // eslint-disable-next-line guard-for-in + for (const normalizedOptions in this.queue) { + // eslint-disable-next-line guard-for-in + for (const normalizedOrigin in this.queue[normalizedOptions]) { + const item = this.queue[normalizedOptions][normalizedOrigin]; + + // The entry function can be run only once. + if (!item.completed) { + item.completed = true; + + item(); + } + } + } + } + + _isBetterSession(thisStreamCount, thatStreamCount) { + return thisStreamCount > thatStreamCount; + } + + _accept(session, listeners, normalizedOrigin, options) { + let index = 0; + + while (index < listeners.length && session[kCurrentStreamCount] < session.remoteSettings.maxConcurrentStreams) { + // We assume `resolve(...)` calls `request(...)` *directly*, + // otherwise the session will get overloaded. + listeners[index].resolve(session); + + index++; + } + + listeners.splice(0, index); + + if (listeners.length > 0) { + this.getSession(normalizedOrigin, options, listeners); + listeners.length = 0; + } + } + + getSession(origin, options, listeners) { + return new Promise((resolve, reject) => { + if (Array.isArray(listeners) && listeners.length > 0) { + listeners = [...listeners]; + + // Resolve the current promise ASAP, we're just moving the listeners. + // They will be executed at a different time. + resolve(); + } else { + listeners = [{resolve, reject}]; + } + + try { + // Parse origin + if (typeof origin === 'string') { + origin = new URL$7(origin); + } else if (!(origin instanceof URL$7)) { + throw new TypeError('The `origin` argument needs to be a string or an URL object'); + } + + if (options) { + // Validate servername + const {servername} = options; + const {hostname} = origin; + if (servername && hostname !== servername) { + throw new Error(`Origin ${hostname} differs from servername ${servername}`); + } + } + } catch (error) { + for (let index = 0; index < listeners.length; index++) { + listeners[index].reject(error); + } + + return; + } + + const normalizedOptions = this.normalizeOptions(options); + const normalizedOrigin = origin.origin; + + if (normalizedOptions in this.sessions) { + const sessions = this.sessions[normalizedOptions]; + + let maxConcurrentStreams = -1; + let currentStreamsCount = -1; + let optimalSession; + + // We could just do this.sessions[normalizedOptions].find(...) but that isn't optimal. + // Additionally, we are looking for session which has biggest current pending streams count. + // + // |------------| |------------| |------------| |------------| + // | Session: A | | Session: B | | Session: C | | Session: D | + // | Pending: 5 |-| Pending: 8 |-| Pending: 9 |-| Pending: 4 | + // | Max: 10 | | Max: 10 | | Max: 9 | | Max: 5 | + // |------------| |------------| |------------| |------------| + // ^ + // | + // pick this one -- + // + for (let index = 0; index < sessions.length; index++) { + const session = sessions[index]; + + const sessionMaxConcurrentStreams = session.remoteSettings.maxConcurrentStreams; + + if (sessionMaxConcurrentStreams < maxConcurrentStreams) { + break; + } + + if (!session[kOriginSet].includes(normalizedOrigin)) { + continue; + } + + const sessionCurrentStreamsCount = session[kCurrentStreamCount]; + + if ( + sessionCurrentStreamsCount >= sessionMaxConcurrentStreams + || session[kGracefullyClosing] + // Unfortunately the `close` event isn't called immediately, + // so `session.destroyed` is `true`, but `session.closed` is `false`. + || session.destroyed + ) { + continue; + } + + // We only need set this once. + if (!optimalSession) { + maxConcurrentStreams = sessionMaxConcurrentStreams; + } + + // Either get the session which has biggest current stream count or the lowest. + if (this._isBetterSession(sessionCurrentStreamsCount, currentStreamsCount)) { + optimalSession = session; + currentStreamsCount = sessionCurrentStreamsCount; + } + } + + if (optimalSession) { + this._accept(optimalSession, listeners, normalizedOrigin, options); + return; + } + } + + if (normalizedOptions in this.queue) { + if (normalizedOrigin in this.queue[normalizedOptions]) { + // There's already an item in the queue, just attach ourselves to it. + this.queue[normalizedOptions][normalizedOrigin].listeners.push(...listeners); + return; + } + } else { + this.queue[normalizedOptions] = { + [kLength]: 0 + }; + } + + // The entry must be removed from the queue IMMEDIATELY when: + // 1. the session connects successfully, + // 2. an error occurs. + const removeFromQueue = () => { + // Our entry can be replaced. We cannot remove the new one. + if (normalizedOptions in this.queue && this.queue[normalizedOptions][normalizedOrigin] === entry) { + delete this.queue[normalizedOptions][normalizedOrigin]; + + if (--this.queue[normalizedOptions][kLength] === 0) { + delete this.queue[normalizedOptions]; + } + } + }; + + // The main logic is here + const entry = async () => { + this._sessionCount++; + + const name = `${normalizedOrigin}:${normalizedOptions}`; + let receivedSettings = false; + let socket; + + try { + const computedOptions = {...options}; + + if (computedOptions.settings === undefined) { + computedOptions.settings = this.settings; + } + + if (computedOptions.session === undefined) { + computedOptions.session = this.tlsSessionCache.get(name); + } + + const createConnection = computedOptions.createConnection || this.createConnection; + + // A hacky workaround to enable async `createConnection` + socket = await createConnection.call(this, origin, computedOptions); + computedOptions.createConnection = () => socket; + + const session = http2$2.connect(origin, computedOptions); + session[kCurrentStreamCount] = 0; + session[kGracefullyClosing] = false; + + // Node.js return https://false:443 instead of https://1.1.1.1:443 + const getOriginSet = () => { + const {socket} = session; + + let originSet; + if (socket.servername === false) { + socket.servername = socket.remoteAddress; + originSet = session.originSet; + socket.servername = false; + } else { + originSet = session.originSet; + } + + return originSet; + }; + + const isFree = () => session[kCurrentStreamCount] < session.remoteSettings.maxConcurrentStreams; + + session.socket.once('session', tlsSession => { + this.tlsSessionCache.set(name, tlsSession); + }); + + session.once('error', error => { + // Listeners are empty when the session successfully connected. + for (let index = 0; index < listeners.length; index++) { + listeners[index].reject(error); + } + + // The connection got broken, purge the cache. + this.tlsSessionCache.delete(name); + }); + + session.setTimeout(this.timeout, () => { + // Terminates all streams owned by this session. + session.destroy(); + }); + + session.once('close', () => { + this._sessionCount--; + + if (receivedSettings) { + // Assumes session `close` is emitted after request `close` + this._emptySessionCount--; + + // This cannot be moved to the stream logic, + // because there may be a session that hadn't made a single request. + const where = this.sessions[normalizedOptions]; + + if (where.length === 1) { + delete this.sessions[normalizedOptions]; + } else { + where.splice(where.indexOf(session), 1); + } + } else { + // Broken connection + removeFromQueue(); + + const error = new Error('Session closed without receiving a SETTINGS frame'); + error.code = 'HTTP2WRAPPER_NOSETTINGS'; + + for (let index = 0; index < listeners.length; index++) { + listeners[index].reject(error); + } + } + + // There may be another session awaiting. + this._processQueue(); + }); + + // Iterates over the queue and processes listeners. + const processListeners = () => { + const queue = this.queue[normalizedOptions]; + if (!queue) { + return; + } + + const originSet = session[kOriginSet]; + + for (let index = 0; index < originSet.length; index++) { + const origin = originSet[index]; + + if (origin in queue) { + const {listeners, completed} = queue[origin]; + + let index = 0; + + // Prevents session overloading. + while (index < listeners.length && isFree()) { + // We assume `resolve(...)` calls `request(...)` *directly*, + // otherwise the session will get overloaded. + listeners[index].resolve(session); + + index++; + } + + queue[origin].listeners.splice(0, index); + + if (queue[origin].listeners.length === 0 && !completed) { + delete queue[origin]; + + if (--queue[kLength] === 0) { + delete this.queue[normalizedOptions]; + break; + } + } + + // We're no longer free, no point in continuing. + if (!isFree()) { + break; + } + } + } + }; + + // The Origin Set cannot shrink. No need to check if it suddenly became covered by another one. + session.on('origin', () => { + session[kOriginSet] = getOriginSet() || []; + session[kGracefullyClosing] = false; + closeSessionIfCovered(this.sessions[normalizedOptions], session); + + if (session[kGracefullyClosing] || !isFree()) { + return; + } + + processListeners(); + + if (!isFree()) { + return; + } + + // Close covered sessions (if possible). + closeCoveredSessions(this.sessions[normalizedOptions], session); + }); + + session.once('remoteSettings', () => { + // The Agent could have been destroyed already. + if (entry.destroyed) { + const error = new Error('Agent has been destroyed'); + + for (let index = 0; index < listeners.length; index++) { + listeners[index].reject(error); + } + + session.destroy(); + return; + } + + // See https://github.com/nodejs/node/issues/38426 + if (session.setLocalWindowSize) { + session.setLocalWindowSize(1024 * 1024 * 4); // 4 MB + } + + session[kOriginSet] = getOriginSet() || []; + + if (session.socket.encrypted) { + const mainOrigin = session[kOriginSet][0]; + if (mainOrigin !== normalizedOrigin) { + const error = new Error(`Requested origin ${normalizedOrigin} does not match server ${mainOrigin}`); + + for (let index = 0; index < listeners.length; index++) { + listeners[index].reject(error); + } + + session.destroy(); + return; + } + } + + removeFromQueue(); + + { + const where = this.sessions; + + if (normalizedOptions in where) { + const sessions = where[normalizedOptions]; + sessions.splice(getSortedIndex(sessions, session, compareSessions), 0, session); + } else { + where[normalizedOptions] = [session]; + } + } + + receivedSettings = true; + this._emptySessionCount++; + + this.emit('session', session); + this._accept(session, listeners, normalizedOrigin, options); + + if (session[kCurrentStreamCount] === 0 && this._emptySessionCount > this.maxEmptySessions) { + this.closeEmptySessions(this._emptySessionCount - this.maxEmptySessions); + } + + // `session.remoteSettings.maxConcurrentStreams` might get increased + session.on('remoteSettings', () => { + if (!isFree()) { + return; + } + + processListeners(); + + if (!isFree()) { + return; + } + + // In case the Origin Set changes + closeCoveredSessions(this.sessions[normalizedOptions], session); + }); + }); + + // Shim `session.request()` in order to catch all streams + session[kRequest] = session.request; + session.request = (headers, streamOptions) => { + if (session[kGracefullyClosing]) { + throw new Error('The session is gracefully closing. No new streams are allowed.'); + } + + const stream = session[kRequest](headers, streamOptions); + + // The process won't exit until the session is closed or all requests are gone. + session.ref(); + + if (session[kCurrentStreamCount]++ === 0) { + this._emptySessionCount--; + } + + stream.once('close', () => { + if (--session[kCurrentStreamCount] === 0) { + this._emptySessionCount++; + session.unref(); + + if (this._emptySessionCount > this.maxEmptySessions || session[kGracefullyClosing]) { + session.close(); + return; + } + } + + if (session.destroyed || session.closed) { + return; + } + + if (isFree() && !closeSessionIfCovered(this.sessions[normalizedOptions], session)) { + closeCoveredSessions(this.sessions[normalizedOptions], session); + processListeners(); + + if (session[kCurrentStreamCount] === 0) { + this._processQueue(); + } + } + }); + + return stream; + }; + } catch (error) { + removeFromQueue(); + this._sessionCount--; + + for (let index = 0; index < listeners.length; index++) { + listeners[index].reject(error); + } + } + }; + + entry.listeners = listeners; + entry.completed = false; + entry.destroyed = false; + + this.queue[normalizedOptions][normalizedOrigin] = entry; + this.queue[normalizedOptions][kLength]++; + this._processQueue(); + }); + } + + request(origin, options, headers, streamOptions) { + return new Promise((resolve, reject) => { + this.getSession(origin, options, [{ + reject, + resolve: session => { + try { + const stream = session.request(headers, streamOptions); + + // Do not throw before `request(...)` has been awaited + delayAsyncDestroy$1(stream); + + resolve(stream); + } catch (error) { + reject(error); + } + } + }]); + }); + } + + async createConnection(origin, options) { + return Agent.connect(origin, options); + } + + static connect(origin, options) { + options.ALPNProtocols = ['h2']; + + const port = origin.port || 443; + const host = origin.hostname; + + if (typeof options.servername === 'undefined') { + options.servername = host; + } + + const socket = tls$3.connect(port, host, options); + + if (options.socket) { + socket._peername = { + family: undefined, + address: undefined, + port + }; + } + + return socket; + } + + closeEmptySessions(maxCount = Number.POSITIVE_INFINITY) { + let closedCount = 0; + + const {sessions} = this; + + // eslint-disable-next-line guard-for-in + for (const key in sessions) { + const thisSessions = sessions[key]; + + for (let index = 0; index < thisSessions.length; index++) { + const session = thisSessions[index]; + + if (session[kCurrentStreamCount] === 0) { + closedCount++; + session.close(); + + if (closedCount >= maxCount) { + return closedCount; + } + } + } + } + + return closedCount; + } + + destroy(reason) { + const {sessions, queue} = this; + + // eslint-disable-next-line guard-for-in + for (const key in sessions) { + const thisSessions = sessions[key]; + + for (let index = 0; index < thisSessions.length; index++) { + thisSessions[index].destroy(reason); + } + } + + // eslint-disable-next-line guard-for-in + for (const normalizedOptions in queue) { + const entries = queue[normalizedOptions]; + + // eslint-disable-next-line guard-for-in + for (const normalizedOrigin in entries) { + entries[normalizedOrigin].destroyed = true; + } + } + + // New requests should NOT attach to destroyed sessions + this.queue = {}; + this.tlsSessionCache.clear(); + } + + get emptySessionCount() { + return this._emptySessionCount; + } + + get pendingSessionCount() { + return this._sessionCount - this._emptySessionCount; + } + + get sessionCount() { + return this._sessionCount; + } +}; + +Agent$4.kCurrentStreamCount = kCurrentStreamCount; +Agent$4.kGracefullyClosing = kGracefullyClosing; + +var agent = { + Agent: Agent$4, + globalAgent: new Agent$4() +}; + +const {Readable: Readable$1} = Stream$3; + +let IncomingMessage$2 = class IncomingMessage extends Readable$1 { + constructor(socket, highWaterMark) { + super({ + emitClose: false, + autoDestroy: true, + highWaterMark + }); + + this.statusCode = null; + this.statusMessage = ''; + this.httpVersion = '2.0'; + this.httpVersionMajor = 2; + this.httpVersionMinor = 0; + this.headers = {}; + this.trailers = {}; + this.req = null; + + this.aborted = false; + this.complete = false; + this.upgrade = null; + + this.rawHeaders = []; + this.rawTrailers = []; + + this.socket = socket; + + this._dumped = false; + } + + get connection() { + return this.socket; + } + + set connection(value) { + this.socket = value; + } + + _destroy(error, callback) { + if (!this.readableEnded) { + this.aborted = true; + } + + // See https://github.com/nodejs/node/issues/35303 + callback(); + + this.req._request.destroy(error); + } + + setTimeout(ms, callback) { + this.req.setTimeout(ms, callback); + return this; + } + + _dump() { + if (!this._dumped) { + this._dumped = true; + + this.removeAllListeners('data'); + this.resume(); + } + } + + _read() { + if (this.req) { + this.req._request.resume(); + } + } +}; + +var incomingMessage = IncomingMessage$2; + +var proxyEvents$1 = (from, to, events) => { + for (const event of events) { + from.on(event, (...args) => to.emit(event, ...args)); + } +}; + +var errors$3 = {exports: {}}; + +(function (module) { + /* istanbul ignore file: https://github.com/nodejs/node/blob/master/lib/internal/errors.js */ + + const makeError = (Base, key, getMessage) => { + module.exports[key] = class NodeError extends Base { + constructor(...args) { + super(typeof getMessage === 'string' ? getMessage : getMessage(args)); + this.name = `${super.name} [${key}]`; + this.code = key; + } + }; + }; + + makeError(TypeError, 'ERR_INVALID_ARG_TYPE', args => { + const type = args[0].includes('.') ? 'property' : 'argument'; + + let valid = args[1]; + const isManyTypes = Array.isArray(valid); + + if (isManyTypes) { + valid = `${valid.slice(0, -1).join(', ')} or ${valid.slice(-1)}`; + } + + return `The "${args[0]}" ${type} must be ${isManyTypes ? 'one of' : 'of'} type ${valid}. Received ${typeof args[2]}`; + }); + + makeError(TypeError, 'ERR_INVALID_PROTOCOL', args => + `Protocol "${args[0]}" not supported. Expected "${args[1]}"` + ); + + makeError(Error, 'ERR_HTTP_HEADERS_SENT', args => + `Cannot ${args[0]} headers after they are sent to the client` + ); + + makeError(TypeError, 'ERR_INVALID_HTTP_TOKEN', args => + `${args[0]} must be a valid HTTP token [${args[1]}]` + ); + + makeError(TypeError, 'ERR_HTTP_INVALID_HEADER_VALUE', args => + `Invalid value "${args[0]} for header "${args[1]}"` + ); + + makeError(TypeError, 'ERR_INVALID_CHAR', args => + `Invalid character in ${args[0]} [${args[1]}]` + ); + + makeError( + Error, + 'ERR_HTTP2_NO_SOCKET_MANIPULATION', + 'HTTP/2 sockets should not be directly manipulated (e.g. read and written)' + ); +} (errors$3)); + +var errorsExports = errors$3.exports; + +var isRequestPseudoHeader$1 = header => { + switch (header) { + case ':method': + case ':scheme': + case ':authority': + case ':path': + return true; + default: + return false; + } +}; + +const {ERR_INVALID_HTTP_TOKEN} = errorsExports; +const isRequestPseudoHeader = isRequestPseudoHeader$1; + +const isValidHttpToken = /^[\^`\-\w!#$%&*+.|~]+$/; + +var validateHeaderName$3 = name => { + if (typeof name !== 'string' || (!isValidHttpToken.test(name) && !isRequestPseudoHeader(name))) { + throw new ERR_INVALID_HTTP_TOKEN('Header name', name); + } +}; + +const { + ERR_HTTP_INVALID_HEADER_VALUE, + ERR_INVALID_CHAR +} = errorsExports; + +const isInvalidHeaderValue = /[^\t\u0020-\u007E\u0080-\u00FF]/; + +var validateHeaderValue$3 = (name, value) => { + if (typeof value === 'undefined') { + throw new ERR_HTTP_INVALID_HEADER_VALUE(value, name); + } + + if (isInvalidHeaderValue.test(value)) { + throw new ERR_INVALID_CHAR('header content', name); + } +}; + +const {ERR_HTTP2_NO_SOCKET_MANIPULATION} = errorsExports; + +/* istanbul ignore file */ +/* https://github.com/nodejs/node/blob/6eec858f34a40ffa489c1ec54bb24da72a28c781/lib/internal/http2/compat.js#L195-L272 */ + +const proxySocketHandler$1 = { + has(stream, property) { + // Replaced [kSocket] with .socket + const reference = stream.session === undefined ? stream : stream.session.socket; + return (property in stream) || (property in reference); + }, + + get(stream, property) { + switch (property) { + case 'on': + case 'once': + case 'end': + case 'emit': + case 'destroy': + return stream[property].bind(stream); + case 'writable': + case 'destroyed': + return stream[property]; + case 'readable': + if (stream.destroyed) { + return false; + } + + return stream.readable; + case 'setTimeout': { + const {session} = stream; + if (session !== undefined) { + return session.setTimeout.bind(session); + } + + return stream.setTimeout.bind(stream); + } + + case 'write': + case 'read': + case 'pause': + case 'resume': + throw new ERR_HTTP2_NO_SOCKET_MANIPULATION(); + default: { + // Replaced [kSocket] with .socket + const reference = stream.session === undefined ? stream : stream.session.socket; + const value = reference[property]; + + return typeof value === 'function' ? value.bind(reference) : value; + } + } + }, + + getPrototypeOf(stream) { + if (stream.session !== undefined) { + // Replaced [kSocket] with .socket + return Reflect.getPrototypeOf(stream.session.socket); + } + + return Reflect.getPrototypeOf(stream); + }, + + set(stream, property, value) { + switch (property) { + case 'writable': + case 'readable': + case 'destroyed': + case 'on': + case 'once': + case 'end': + case 'emit': + case 'destroy': + stream[property] = value; + return true; + case 'setTimeout': { + const {session} = stream; + if (session === undefined) { + stream.setTimeout = value; + } else { + session.setTimeout = value; + } + + return true; + } + + case 'write': + case 'read': + case 'pause': + case 'resume': + throw new ERR_HTTP2_NO_SOCKET_MANIPULATION(); + default: { + // Replaced [kSocket] with .socket + const reference = stream.session === undefined ? stream : stream.session.socket; + reference[property] = value; + return true; + } + } + } +}; + +var proxySocketHandler_1 = proxySocketHandler$1; + +// See https://github.com/facebook/jest/issues/2549 +// eslint-disable-next-line node/prefer-global/url +const {URL: URL$6, urlToHttpOptions: urlToHttpOptions$1} = require$$0$e; +const http2$1 = require$$3$4; +const {Writable} = Stream$3; +const {Agent: Agent$3, globalAgent: globalAgent$4} = agent; +const IncomingMessage$1 = incomingMessage; +const proxyEvents = proxyEvents$1; +const { + ERR_INVALID_ARG_TYPE: ERR_INVALID_ARG_TYPE$2, + ERR_INVALID_PROTOCOL, + ERR_HTTP_HEADERS_SENT +} = errorsExports; +const validateHeaderName$2 = validateHeaderName$3; +const validateHeaderValue$2 = validateHeaderValue$3; +const proxySocketHandler = proxySocketHandler_1; + +const { + HTTP2_HEADER_STATUS, + HTTP2_HEADER_METHOD, + HTTP2_HEADER_PATH, + HTTP2_HEADER_AUTHORITY, + HTTP2_METHOD_CONNECT +} = http2$1.constants; + +const kHeaders = Symbol('headers'); +const kOrigin = Symbol('origin'); +const kSession = Symbol('session'); +const kOptions = Symbol('options'); +const kFlushedHeaders = Symbol('flushedHeaders'); +const kJobs = Symbol('jobs'); +const kPendingAgentPromise = Symbol('pendingAgentPromise'); + +let ClientRequest$5 = class ClientRequest extends Writable { + constructor(input, options, callback) { + super({ + autoDestroy: false, + emitClose: false + }); + + if (typeof input === 'string') { + input = urlToHttpOptions$1(new URL$6(input)); + } else if (input instanceof URL$6) { + input = urlToHttpOptions$1(input); + } else { + input = {...input}; + } + + if (typeof options === 'function' || options === undefined) { + // (options, callback) + callback = options; + options = input; + } else { + // (input, options, callback) + options = Object.assign(input, options); + } + + if (options.h2session) { + this[kSession] = options.h2session; + + if (this[kSession].destroyed) { + throw new Error('The session has been closed already'); + } + + this.protocol = this[kSession].socket.encrypted ? 'https:' : 'http:'; + } else if (options.agent === false) { + this.agent = new Agent$3({maxEmptySessions: 0}); + } else if (typeof options.agent === 'undefined' || options.agent === null) { + this.agent = globalAgent$4; + } else if (typeof options.agent.request === 'function') { + this.agent = options.agent; + } else { + throw new ERR_INVALID_ARG_TYPE$2('options.agent', ['http2wrapper.Agent-like Object', 'undefined', 'false'], options.agent); + } + + if (this.agent) { + this.protocol = this.agent.protocol; + } + + if (options.protocol && options.protocol !== this.protocol) { + throw new ERR_INVALID_PROTOCOL(options.protocol, this.protocol); + } + + if (!options.port) { + options.port = options.defaultPort || (this.agent && this.agent.defaultPort) || 443; + } + + options.host = options.hostname || options.host || 'localhost'; + + // Unused + delete options.hostname; + + const {timeout} = options; + options.timeout = undefined; + + this[kHeaders] = Object.create(null); + this[kJobs] = []; + + this[kPendingAgentPromise] = undefined; + + this.socket = null; + this.connection = null; + + this.method = options.method || 'GET'; + + if (!(this.method === 'CONNECT' && (options.path === '/' || options.path === undefined))) { + this.path = options.path; + } + + this.res = null; + this.aborted = false; + this.reusedSocket = false; + + const {headers} = options; + if (headers) { + // eslint-disable-next-line guard-for-in + for (const header in headers) { + this.setHeader(header, headers[header]); + } + } + + if (options.auth && !('authorization' in this[kHeaders])) { + this[kHeaders].authorization = 'Basic ' + Buffer.from(options.auth).toString('base64'); + } + + options.session = options.tlsSession; + options.path = options.socketPath; + + this[kOptions] = options; + + // Clients that generate HTTP/2 requests directly SHOULD use the :authority pseudo-header field instead of the Host header field. + this[kOrigin] = new URL$6(`${this.protocol}//${options.servername || options.host}:${options.port}`); + + // A socket is being reused + const reuseSocket = options._reuseSocket; + if (reuseSocket) { + options.createConnection = (...args) => { + if (reuseSocket.destroyed) { + return this.agent.createConnection(...args); + } + + return reuseSocket; + }; + + // eslint-disable-next-line promise/prefer-await-to-then + this.agent.getSession(this[kOrigin], this[kOptions]).catch(() => {}); + } + + if (timeout) { + this.setTimeout(timeout); + } + + if (callback) { + this.once('response', callback); + } + + this[kFlushedHeaders] = false; + } + + get method() { + return this[kHeaders][HTTP2_HEADER_METHOD]; + } + + set method(value) { + if (value) { + this[kHeaders][HTTP2_HEADER_METHOD] = value.toUpperCase(); + } + } + + get path() { + const header = this.method === 'CONNECT' ? HTTP2_HEADER_AUTHORITY : HTTP2_HEADER_PATH; + + return this[kHeaders][header]; + } + + set path(value) { + if (value) { + const header = this.method === 'CONNECT' ? HTTP2_HEADER_AUTHORITY : HTTP2_HEADER_PATH; + + this[kHeaders][header] = value; + } + } + + get host() { + return this[kOrigin].hostname; + } + + set host(_value) { + // Do nothing as this is read only. + } + + get _mustNotHaveABody() { + return this.method === 'GET' || this.method === 'HEAD' || this.method === 'DELETE'; + } + + _write(chunk, encoding, callback) { + // https://github.com/nodejs/node/blob/654df09ae0c5e17d1b52a900a545f0664d8c7627/lib/internal/http2/util.js#L148-L156 + if (this._mustNotHaveABody) { + callback(new Error('The GET, HEAD and DELETE methods must NOT have a body')); + /* istanbul ignore next: Node.js 12 throws directly */ + return; + } + + this.flushHeaders(); + + const callWrite = () => this._request.write(chunk, encoding, callback); + if (this._request) { + callWrite(); + } else { + this[kJobs].push(callWrite); + } + } + + _final(callback) { + this.flushHeaders(); + + const callEnd = () => { + // For GET, HEAD and DELETE and CONNECT + if (this._mustNotHaveABody || this.method === 'CONNECT') { + callback(); + return; + } + + this._request.end(callback); + }; + + if (this._request) { + callEnd(); + } else { + this[kJobs].push(callEnd); + } + } + + abort() { + if (this.res && this.res.complete) { + return; + } + + if (!this.aborted) { + process.nextTick(() => this.emit('abort')); + } + + this.aborted = true; + + this.destroy(); + } + + async _destroy(error, callback) { + if (this.res) { + this.res._dump(); + } + + if (this._request) { + this._request.destroy(); + } else { + process.nextTick(() => { + this.emit('close'); + }); + } + + try { + await this[kPendingAgentPromise]; + } catch (internalError) { + if (this.aborted) { + error = internalError; + } + } + + callback(error); + } + + async flushHeaders() { + if (this[kFlushedHeaders] || this.destroyed) { + return; + } + + this[kFlushedHeaders] = true; + + const isConnectMethod = this.method === HTTP2_METHOD_CONNECT; + + // The real magic is here + const onStream = stream => { + this._request = stream; + + if (this.destroyed) { + stream.destroy(); + return; + } + + // Forwards `timeout`, `continue`, `close` and `error` events to this instance. + if (!isConnectMethod) { + // TODO: Should we proxy `close` here? + proxyEvents(stream, this, ['timeout', 'continue']); + } + + stream.once('error', error => { + this.destroy(error); + }); + + stream.once('aborted', () => { + const {res} = this; + if (res) { + res.aborted = true; + res.emit('aborted'); + res.destroy(); + } else { + this.destroy(new Error('The server aborted the HTTP/2 stream')); + } + }); + + const onResponse = (headers, flags, rawHeaders) => { + // If we were to emit raw request stream, it would be as fast as the native approach. + // Note that wrapping the raw stream in a Proxy instance won't improve the performance (already tested it). + const response = new IncomingMessage$1(this.socket, stream.readableHighWaterMark); + this.res = response; + + // Undocumented, but it is used by `cacheable-request` + response.url = `${this[kOrigin].origin}${this.path}`; + + response.req = this; + response.statusCode = headers[HTTP2_HEADER_STATUS]; + response.headers = headers; + response.rawHeaders = rawHeaders; + + response.once('end', () => { + response.complete = true; + + // Has no effect, just be consistent with the Node.js behavior + response.socket = null; + response.connection = null; + }); + + if (isConnectMethod) { + response.upgrade = true; + + // The HTTP1 API says the socket is detached here, + // but we can't do that so we pass the original HTTP2 request. + if (this.emit('connect', response, stream, Buffer.alloc(0))) { + this.emit('close'); + } else { + // No listeners attached, destroy the original request. + stream.destroy(); + } + } else { + // Forwards data + stream.on('data', chunk => { + if (!response._dumped && !response.push(chunk)) { + stream.pause(); + } + }); + + stream.once('end', () => { + if (!this.aborted) { + response.push(null); + } + }); + + if (!this.emit('response', response)) { + // No listeners attached, dump the response. + response._dump(); + } + } + }; + + // This event tells we are ready to listen for the data. + stream.once('response', onResponse); + + // Emits `information` event + stream.once('headers', headers => this.emit('information', {statusCode: headers[HTTP2_HEADER_STATUS]})); + + stream.once('trailers', (trailers, flags, rawTrailers) => { + const {res} = this; + + // https://github.com/nodejs/node/issues/41251 + if (res === null) { + onResponse(trailers, flags, rawTrailers); + return; + } + + // Assigns trailers to the response object. + res.trailers = trailers; + res.rawTrailers = rawTrailers; + }); + + stream.once('close', () => { + const {aborted, res} = this; + if (res) { + if (aborted) { + res.aborted = true; + res.emit('aborted'); + res.destroy(); + } + + const finish = () => { + res.emit('close'); + + this.destroy(); + this.emit('close'); + }; + + if (res.readable) { + res.once('end', finish); + } else { + finish(); + } + + return; + } + + if (!this.destroyed) { + this.destroy(new Error('The HTTP/2 stream has been early terminated')); + this.emit('close'); + return; + } + + this.destroy(); + this.emit('close'); + }); + + this.socket = new Proxy(stream, proxySocketHandler); + + for (const job of this[kJobs]) { + job(); + } + + this[kJobs].length = 0; + + this.emit('socket', this.socket); + }; + + if (!(HTTP2_HEADER_AUTHORITY in this[kHeaders]) && !isConnectMethod) { + this[kHeaders][HTTP2_HEADER_AUTHORITY] = this[kOrigin].host; + } + + // Makes a HTTP2 request + if (this[kSession]) { + try { + onStream(this[kSession].request(this[kHeaders])); + } catch (error) { + this.destroy(error); + } + } else { + this.reusedSocket = true; + + try { + const promise = this.agent.request(this[kOrigin], this[kOptions], this[kHeaders]); + this[kPendingAgentPromise] = promise; + + onStream(await promise); + + this[kPendingAgentPromise] = false; + } catch (error) { + this[kPendingAgentPromise] = false; + + this.destroy(error); + } + } + } + + get connection() { + return this.socket; + } + + set connection(value) { + this.socket = value; + } + + getHeaderNames() { + return Object.keys(this[kHeaders]); + } + + hasHeader(name) { + if (typeof name !== 'string') { + throw new ERR_INVALID_ARG_TYPE$2('name', 'string', name); + } + + return Boolean(this[kHeaders][name.toLowerCase()]); + } + + getHeader(name) { + if (typeof name !== 'string') { + throw new ERR_INVALID_ARG_TYPE$2('name', 'string', name); + } + + return this[kHeaders][name.toLowerCase()]; + } + + get headersSent() { + return this[kFlushedHeaders]; + } + + removeHeader(name) { + if (typeof name !== 'string') { + throw new ERR_INVALID_ARG_TYPE$2('name', 'string', name); + } + + if (this.headersSent) { + throw new ERR_HTTP_HEADERS_SENT('remove'); + } + + delete this[kHeaders][name.toLowerCase()]; + } + + setHeader(name, value) { + if (this.headersSent) { + throw new ERR_HTTP_HEADERS_SENT('set'); + } + + validateHeaderName$2(name); + validateHeaderValue$2(name, value); + + const lowercased = name.toLowerCase(); + + if (lowercased === 'connection') { + if (value.toLowerCase() === 'keep-alive') { + return; + } + + throw new Error(`Invalid 'connection' header: ${value}`); + } + + if (lowercased === 'host' && this.method === 'CONNECT') { + this[kHeaders][HTTP2_HEADER_AUTHORITY] = value; + } else { + this[kHeaders][lowercased] = value; + } + } + + setNoDelay() { + // HTTP2 sockets cannot be malformed, do nothing. + } + + setSocketKeepAlive() { + // HTTP2 sockets cannot be malformed, do nothing. + } + + setTimeout(ms, callback) { + const applyTimeout = () => this._request.setTimeout(ms, callback); + + if (this._request) { + applyTimeout(); + } else { + this[kJobs].push(applyTimeout); + } + + return this; + } + + get maxHeadersCount() { + if (!this.destroyed && this._request) { + return this._request.session.localSettings.maxHeaderListSize; + } + + return undefined; + } + + set maxHeadersCount(_value) { + // Updating HTTP2 settings would affect all requests, do nothing. + } +}; + +var clientRequest = ClientRequest$5; + +var auto$1 = {exports: {}}; + +const tls$2 = require$$1$3; + +var resolveAlpn = (options = {}, connect = tls$2.connect) => new Promise((resolve, reject) => { + let timeout = false; + + let socket; + + const callback = async () => { + await socketPromise; + + socket.off('timeout', onTimeout); + socket.off('error', reject); + + if (options.resolveSocket) { + resolve({alpnProtocol: socket.alpnProtocol, socket, timeout}); + + if (timeout) { + await Promise.resolve(); + socket.emit('timeout'); + } + } else { + socket.destroy(); + resolve({alpnProtocol: socket.alpnProtocol, timeout}); + } + }; + + const onTimeout = async () => { + timeout = true; + callback(); + }; + + const socketPromise = (async () => { + try { + socket = await connect(options, callback); + + socket.on('error', reject); + socket.once('timeout', onTimeout); + } catch (error) { + reject(error); + } + })(); +}); + +const {isIP: isIP$1} = require$$0$f; +const assert$1 = require$$5$1; + +const getHost = host => { + if (host[0] === '[') { + const idx = host.indexOf(']'); + + assert$1(idx !== -1); + return host.slice(1, idx); + } + + const idx = host.indexOf(':'); + if (idx === -1) { + return host; + } + + return host.slice(0, idx); +}; + +var calculateServerName$1 = host => { + const servername = getHost(host); + + if (isIP$1(servername)) { + return ''; + } + + return servername; +}; + +// See https://github.com/facebook/jest/issues/2549 +// eslint-disable-next-line node/prefer-global/url +const {URL: URL$5, urlToHttpOptions} = require$$0$e; +const http$8 = require$$0$a; +const https$6 = require$$1$4; +const resolveALPN = resolveAlpn; +const QuickLRU = quickLru; +const {Agent: Agent$2, globalAgent: globalAgent$3} = agent; +const Http2ClientRequest = clientRequest; +const calculateServerName = calculateServerName$1; +const delayAsyncDestroy = delayAsyncDestroy$2; + +const cache$1 = new QuickLRU({maxSize: 100}); +const queue$1 = new Map(); + +const installSocket = (agent, socket, options) => { + socket._httpMessage = {shouldKeepAlive: true}; + + const onFree = () => { + agent.emit('free', socket, options); + }; + + socket.on('free', onFree); + + const onClose = () => { + agent.removeSocket(socket, options); + }; + + socket.on('close', onClose); + + const onTimeout = () => { + const {freeSockets} = agent; + + for (const sockets of Object.values(freeSockets)) { + if (sockets.includes(socket)) { + socket.destroy(); + return; + } + } + }; + + socket.on('timeout', onTimeout); + + const onRemove = () => { + agent.removeSocket(socket, options); + socket.off('close', onClose); + socket.off('free', onFree); + socket.off('timeout', onTimeout); + socket.off('agentRemove', onRemove); + }; + + socket.on('agentRemove', onRemove); + + agent.emit('free', socket, options); +}; + +const createResolveProtocol = (cache, queue = new Map(), connect = undefined) => { + return async options => { + const name = `${options.host}:${options.port}:${options.ALPNProtocols.sort()}`; + + if (!cache.has(name)) { + if (queue.has(name)) { + const result = await queue.get(name); + return {alpnProtocol: result.alpnProtocol}; + } + + const {path} = options; + options.path = options.socketPath; + + const resultPromise = resolveALPN(options, connect); + queue.set(name, resultPromise); + + try { + const result = await resultPromise; + + cache.set(name, result.alpnProtocol); + queue.delete(name); + + options.path = path; + + return result; + } catch (error) { + queue.delete(name); + + options.path = path; + + throw error; + } + } + + return {alpnProtocol: cache.get(name)}; + }; +}; + +const defaultResolveProtocol = createResolveProtocol(cache$1, queue$1); + +auto$1.exports = async (input, options, callback) => { + if (typeof input === 'string') { + input = urlToHttpOptions(new URL$5(input)); + } else if (input instanceof URL$5) { + input = urlToHttpOptions(input); + } else { + input = {...input}; + } + + if (typeof options === 'function' || options === undefined) { + // (options, callback) + callback = options; + options = input; + } else { + // (input, options, callback) + options = Object.assign(input, options); + } + + options.ALPNProtocols = options.ALPNProtocols || ['h2', 'http/1.1']; + + if (!Array.isArray(options.ALPNProtocols) || options.ALPNProtocols.length === 0) { + throw new Error('The `ALPNProtocols` option must be an Array with at least one entry'); + } + + options.protocol = options.protocol || 'https:'; + const isHttps = options.protocol === 'https:'; + + options.host = options.hostname || options.host || 'localhost'; + options.session = options.tlsSession; + options.servername = options.servername || calculateServerName((options.headers && options.headers.host) || options.host); + options.port = options.port || (isHttps ? 443 : 80); + options._defaultAgent = isHttps ? https$6.globalAgent : http$8.globalAgent; + + const resolveProtocol = options.resolveProtocol || defaultResolveProtocol; + + // Note: We don't support `h2session` here + + let {agent} = options; + if (agent !== undefined && agent !== false && agent.constructor.name !== 'Object') { + throw new Error('The `options.agent` can be only an object `http`, `https` or `http2` properties'); + } + + if (isHttps) { + options.resolveSocket = true; + + let {socket, alpnProtocol, timeout} = await resolveProtocol(options); + + if (timeout) { + if (socket) { + socket.destroy(); + } + + const error = new Error(`Timed out resolving ALPN: ${options.timeout} ms`); + error.code = 'ETIMEDOUT'; + error.ms = options.timeout; + + throw error; + } + + // We can't accept custom `createConnection` because the API is different for HTTP/2 + if (socket && options.createConnection) { + socket.destroy(); + socket = undefined; + } + + delete options.resolveSocket; + + const isHttp2 = alpnProtocol === 'h2'; + + if (agent) { + agent = isHttp2 ? agent.http2 : agent.https; + options.agent = agent; + } + + if (agent === undefined) { + agent = isHttp2 ? globalAgent$3 : https$6.globalAgent; + } + + if (socket) { + if (agent === false) { + socket.destroy(); + } else { + const defaultCreateConnection = (isHttp2 ? Agent$2 : https$6.Agent).prototype.createConnection; + + if (agent.createConnection === defaultCreateConnection) { + if (isHttp2) { + options._reuseSocket = socket; + } else { + installSocket(agent, socket, options); + } + } else { + socket.destroy(); + } + } + } + + if (isHttp2) { + return delayAsyncDestroy(new Http2ClientRequest(options, callback)); + } + } else if (agent) { + options.agent = agent.http; + } + + return delayAsyncDestroy(http$8.request(options, callback)); +}; + +auto$1.exports.protocolCache = cache$1; +auto$1.exports.resolveProtocol = defaultResolveProtocol; +auto$1.exports.createResolveProtocol = createResolveProtocol; + +var autoExports = auto$1.exports; + +const stream$2 = Stream$3; +const tls$1 = require$$1$3; + +// Really awesome hack. +const JSStreamSocket$2 = (new tls$1.TLSSocket(new stream$2.PassThrough()))._handle._parentWrap.constructor; + +var jsStreamSocket = JSStreamSocket$2; + +let UnexpectedStatusCodeError$2 = class UnexpectedStatusCodeError extends Error { + constructor(statusCode, statusMessage = '') { + super(`The proxy server rejected the request with status code ${statusCode} (${statusMessage || 'empty status message'})`); + this.statusCode = statusCode; + this.statusMessage = statusMessage; + } +}; + +var unexpectedStatusCodeError = UnexpectedStatusCodeError$2; + +const checkType$1 = (name, value, types) => { + const valid = types.some(type => { + const typeofType = typeof type; + if (typeofType === 'string') { + return typeof value === type; + } + + return value instanceof type; + }); + + if (!valid) { + const names = types.map(type => typeof type === 'string' ? type : type.name); + + throw new TypeError(`Expected '${name}' to be a type of ${names.join(' or ')}, got ${typeof value}`); + } +}; + +var checkType_1 = checkType$1; + +// See https://github.com/facebook/jest/issues/2549 +// eslint-disable-next-line node/prefer-global/url +const {URL: URL$4} = require$$0$e; +const checkType = checkType_1; + +var initialize$2 = (self, proxyOptions) => { + checkType('proxyOptions', proxyOptions, ['object']); + checkType('proxyOptions.headers', proxyOptions.headers, ['object', 'undefined']); + checkType('proxyOptions.raw', proxyOptions.raw, ['boolean', 'undefined']); + checkType('proxyOptions.url', proxyOptions.url, [URL$4, 'string']); + + const url = new URL$4(proxyOptions.url); + + self.proxyOptions = { + raw: true, + ...proxyOptions, + headers: {...proxyOptions.headers}, + url + }; +}; + +var getAuthHeaders = self => { + const {username, password} = self.proxyOptions.url; + + if (username || password) { + const data = `${username}:${password}`; + const authorization = `Basic ${Buffer.from(data).toString('base64')}`; + + return { + 'proxy-authorization': authorization, + authorization + }; + } + + return {}; +}; + +const tls = require$$1$3; +const http$7 = require$$0$a; +const https$5 = require$$1$4; +const JSStreamSocket$1 = jsStreamSocket; +const {globalAgent: globalAgent$2} = agent; +const UnexpectedStatusCodeError$1 = unexpectedStatusCodeError; +const initialize$1 = initialize$2; +const getAuthorizationHeaders$2 = getAuthHeaders; + +const createConnection = (self, options, callback) => { + (async () => { + try { + const {proxyOptions} = self; + const {url, headers, raw} = proxyOptions; + + const stream = await globalAgent$2.request(url, proxyOptions, { + ...getAuthorizationHeaders$2(self), + ...headers, + ':method': 'CONNECT', + ':authority': `${options.host}:${options.port}` + }); + + stream.once('error', callback); + stream.once('response', headers => { + const statusCode = headers[':status']; + + if (statusCode !== 200) { + callback(new UnexpectedStatusCodeError$1(statusCode, '')); + return; + } + + const encrypted = self instanceof https$5.Agent; + + if (raw && encrypted) { + options.socket = stream; + const secureStream = tls.connect(options); + + secureStream.once('close', () => { + stream.destroy(); + }); + + callback(null, secureStream); + return; + } + + const socket = new JSStreamSocket$1(stream); + socket.encrypted = false; + socket._handle.getpeername = out => { + out.family = undefined; + out.address = undefined; + out.port = undefined; + }; + + callback(null, socket); + }); + } catch (error) { + callback(error); + } + })(); +}; + +let HttpOverHttp2$1 = class HttpOverHttp2 extends http$7.Agent { + constructor(options) { + super(options); + + initialize$1(this, options.proxyOptions); + } + + createConnection(options, callback) { + createConnection(this, options, callback); + } +}; + +let HttpsOverHttp2$1 = class HttpsOverHttp2 extends https$5.Agent { + constructor(options) { + super(options); + + initialize$1(this, options.proxyOptions); + } + + createConnection(options, callback) { + createConnection(this, options, callback); + } +}; + +var h1OverH2 = { + HttpOverHttp2: HttpOverHttp2$1, + HttpsOverHttp2: HttpsOverHttp2$1 +}; + +const {Agent: Agent$1} = agent; +const JSStreamSocket = jsStreamSocket; +const UnexpectedStatusCodeError = unexpectedStatusCodeError; +const initialize = initialize$2; + +let Http2OverHttpX$2 = class Http2OverHttpX extends Agent$1 { + constructor(options) { + super(options); + + initialize(this, options.proxyOptions); + } + + async createConnection(origin, options) { + const authority = `${origin.hostname}:${origin.port || 443}`; + + const [stream, statusCode, statusMessage] = await this._getProxyStream(authority); + if (statusCode !== 200) { + throw new UnexpectedStatusCodeError(statusCode, statusMessage); + } + + if (this.proxyOptions.raw) { + options.socket = stream; + } else { + const socket = new JSStreamSocket(stream); + socket.encrypted = false; + socket._handle.getpeername = out => { + out.family = undefined; + out.address = undefined; + out.port = undefined; + }; + + return socket; + } + + return super.createConnection(origin, options); + } +}; + +var h2OverHx = Http2OverHttpX$2; + +const {globalAgent: globalAgent$1} = agent; +const Http2OverHttpX$1 = h2OverHx; +const getAuthorizationHeaders$1 = getAuthHeaders; + +const getStatusCode$1 = stream => new Promise((resolve, reject) => { + stream.once('error', reject); + stream.once('response', headers => { + stream.off('error', reject); + resolve(headers[':status']); + }); +}); + +let Http2OverHttp2$1 = class Http2OverHttp2 extends Http2OverHttpX$1 { + async _getProxyStream(authority) { + const {proxyOptions} = this; + + const headers = { + ...getAuthorizationHeaders$1(this), + ...proxyOptions.headers, + ':method': 'CONNECT', + ':authority': authority + }; + + const stream = await globalAgent$1.request(proxyOptions.url, proxyOptions, headers); + const statusCode = await getStatusCode$1(stream); + + return [stream, statusCode, '']; + } +}; + +var h2OverH2 = Http2OverHttp2$1; + +const http$6 = require$$0$a; +const https$4 = require$$1$4; +const Http2OverHttpX = h2OverHx; +const getAuthorizationHeaders = getAuthHeaders; + +const getStream$1 = request => new Promise((resolve, reject) => { + const onConnect = (response, socket, head) => { + socket.unshift(head); + + request.off('error', reject); + resolve([socket, response.statusCode, response.statusMessage]); + }; + + request.once('error', reject); + request.once('connect', onConnect); +}); + +let Http2OverHttp$1 = class Http2OverHttp extends Http2OverHttpX { + async _getProxyStream(authority) { + const {proxyOptions} = this; + const {url, headers} = this.proxyOptions; + + const network = url.protocol === 'https:' ? https$4 : http$6; + + // `new URL('https://localhost/httpbin.org:443')` results in + // a `/httpbin.org:443` path, which has an invalid leading slash. + const request = network.request({ + ...proxyOptions, + hostname: url.hostname, + port: url.port, + path: authority, + headers: { + ...getAuthorizationHeaders(this), + ...headers, + host: authority + }, + method: 'CONNECT' + }).end(); + + return getStream$1(request); + } +}; + +var h2OverH1 = { + Http2OverHttp: Http2OverHttp$1, + Http2OverHttps: Http2OverHttp$1 +}; + +const http2 = require$$3$4; +const { + Agent, + globalAgent +} = agent; +const ClientRequest$4 = clientRequest; +const IncomingMessage = incomingMessage; +const auto = autoExports; +const { + HttpOverHttp2, + HttpsOverHttp2 +} = h1OverH2; +const Http2OverHttp2 = h2OverH2; +const { + Http2OverHttp, + Http2OverHttps +} = h2OverH1; +const validateHeaderName$1 = validateHeaderName$3; +const validateHeaderValue$1 = validateHeaderValue$3; + +const request$4 = (url, options, callback) => new ClientRequest$4(url, options, callback); + +const get$9 = (url, options, callback) => { + // eslint-disable-next-line unicorn/prevent-abbreviations + const req = new ClientRequest$4(url, options, callback); + req.end(); + + return req; +}; + +var source$2 = { + ...http2, + ClientRequest: ClientRequest$4, + IncomingMessage, + Agent, + globalAgent, + request: request$4, + get: get$9, + auto, + proxies: { + HttpOverHttp2, + HttpsOverHttp2, + Http2OverHttp2, + Http2OverHttp, + Http2OverHttps + }, + validateHeaderName: validateHeaderName$1, + validateHeaderValue: validateHeaderValue$1 +}; + +var http2wrapper = /*@__PURE__*/getDefaultExportFromCjs(source$2); + +function parseLinkHeader$1(link) { + const parsed = []; + const items = link.split(','); + for (const item of items) { + // https://tools.ietf.org/html/rfc5988#section-5 + const [rawUriReference, ...rawLinkParameters] = item.split(';'); + const trimmedUriReference = rawUriReference.trim(); + // eslint-disable-next-line @typescript-eslint/prefer-string-starts-ends-with + if (trimmedUriReference[0] !== '<' || trimmedUriReference[trimmedUriReference.length - 1] !== '>') { + throw new Error(`Invalid format of the Link header reference: ${trimmedUriReference}`); + } + const reference = trimmedUriReference.slice(1, -1); + const parameters = {}; + if (rawLinkParameters.length === 0) { + throw new Error(`Unexpected end of Link header parameters: ${rawLinkParameters.join(';')}`); + } + for (const rawParameter of rawLinkParameters) { + const trimmedRawParameter = rawParameter.trim(); + const center = trimmedRawParameter.indexOf('='); + if (center === -1) { + throw new Error(`Failed to parse Link header: ${link}`); + } + const name = trimmedRawParameter.slice(0, center).trim(); + const value = trimmedRawParameter.slice(center + 1).trim(); + parameters[name] = value; + } + parsed.push({ + reference, + parameters, + }); + } + return parsed; +} + +const [major, minor] = process$3.versions.node.split('.').map(Number); +function validateSearchParameters(searchParameters) { + // eslint-disable-next-line guard-for-in + for (const key in searchParameters) { + const value = searchParameters[key]; + assert$2.any([is$5.string, is$5.number, is$5.boolean, is$5.null_, is$5.undefined], value); + } +} +const globalCache = new Map(); +let globalDnsCache; +const getGlobalDnsCache = () => { + if (globalDnsCache) { + return globalDnsCache; + } + globalDnsCache = new CacheableLookup(); + return globalDnsCache; +}; +const defaultInternals = { + request: undefined, + agent: { + http: undefined, + https: undefined, + http2: undefined, + }, + h2session: undefined, + decompress: true, + timeout: { + connect: undefined, + lookup: undefined, + read: undefined, + request: undefined, + response: undefined, + secureConnect: undefined, + send: undefined, + socket: undefined, + }, + prefixUrl: '', + body: undefined, + form: undefined, + json: undefined, + cookieJar: undefined, + ignoreInvalidCookies: false, + searchParams: undefined, + dnsLookup: undefined, + dnsCache: undefined, + context: {}, + hooks: { + init: [], + beforeRequest: [], + beforeError: [], + beforeRedirect: [], + beforeRetry: [], + afterResponse: [], + }, + followRedirect: true, + maxRedirects: 10, + cache: undefined, + throwHttpErrors: true, + username: '', + password: '', + http2: false, + allowGetBody: false, + headers: { + 'user-agent': 'got (https://github.com/sindresorhus/got)', + }, + methodRewriting: false, + dnsLookupIpVersion: undefined, + parseJson: JSON.parse, + stringifyJson: JSON.stringify, + retry: { + limit: 2, + methods: [ + 'GET', + 'PUT', + 'HEAD', + 'DELETE', + 'OPTIONS', + 'TRACE', + ], + statusCodes: [ + 408, + 413, + 429, + 500, + 502, + 503, + 504, + 521, + 522, + 524, + ], + errorCodes: [ + 'ETIMEDOUT', + 'ECONNRESET', + 'EADDRINUSE', + 'ECONNREFUSED', + 'EPIPE', + 'ENOTFOUND', + 'ENETUNREACH', + 'EAI_AGAIN', + ], + maxRetryAfter: undefined, + calculateDelay: ({ computedValue }) => computedValue, + backoffLimit: Number.POSITIVE_INFINITY, + noise: 100, + }, + localAddress: undefined, + method: 'GET', + createConnection: undefined, + cacheOptions: { + shared: undefined, + cacheHeuristic: undefined, + immutableMinTimeToLive: undefined, + ignoreCargoCult: undefined, + }, + https: { + alpnProtocols: undefined, + rejectUnauthorized: undefined, + checkServerIdentity: undefined, + certificateAuthority: undefined, + key: undefined, + certificate: undefined, + passphrase: undefined, + pfx: undefined, + ciphers: undefined, + honorCipherOrder: undefined, + minVersion: undefined, + maxVersion: undefined, + signatureAlgorithms: undefined, + tlsSessionLifetime: undefined, + dhparam: undefined, + ecdhCurve: undefined, + certificateRevocationLists: undefined, + }, + encoding: undefined, + resolveBodyOnly: false, + isStream: false, + responseType: 'text', + url: undefined, + pagination: { + transform(response) { + if (response.request.options.responseType === 'json') { + return response.body; + } + return JSON.parse(response.body); + }, + paginate({ response }) { + const rawLinkHeader = response.headers.link; + if (typeof rawLinkHeader !== 'string' || rawLinkHeader.trim() === '') { + return false; + } + const parsed = parseLinkHeader$1(rawLinkHeader); + const next = parsed.find(entry => entry.parameters.rel === 'next' || entry.parameters.rel === '"next"'); + if (next) { + return { + url: new urlLib.URL(next.reference, response.url), + }; + } + return false; + }, + filter: () => true, + shouldContinue: () => true, + countLimit: Number.POSITIVE_INFINITY, + backoff: 0, + requestLimit: 10000, + stackAllItems: false, + }, + setHost: true, + maxHeaderSize: undefined, + signal: undefined, + enableUnixSockets: true, +}; +const cloneInternals = (internals) => { + const { hooks, retry } = internals; + const result = { + ...internals, + context: { ...internals.context }, + cacheOptions: { ...internals.cacheOptions }, + https: { ...internals.https }, + agent: { ...internals.agent }, + headers: { ...internals.headers }, + retry: { + ...retry, + errorCodes: [...retry.errorCodes], + methods: [...retry.methods], + statusCodes: [...retry.statusCodes], + }, + timeout: { ...internals.timeout }, + hooks: { + init: [...hooks.init], + beforeRequest: [...hooks.beforeRequest], + beforeError: [...hooks.beforeError], + beforeRedirect: [...hooks.beforeRedirect], + beforeRetry: [...hooks.beforeRetry], + afterResponse: [...hooks.afterResponse], + }, + searchParams: internals.searchParams ? new urlLib.URLSearchParams(internals.searchParams) : undefined, + pagination: { ...internals.pagination }, + }; + if (result.url !== undefined) { + result.prefixUrl = ''; + } + return result; +}; +const cloneRaw = (raw) => { + const { hooks, retry } = raw; + const result = { ...raw }; + if (is$5.object(raw.context)) { + result.context = { ...raw.context }; + } + if (is$5.object(raw.cacheOptions)) { + result.cacheOptions = { ...raw.cacheOptions }; + } + if (is$5.object(raw.https)) { + result.https = { ...raw.https }; + } + if (is$5.object(raw.cacheOptions)) { + result.cacheOptions = { ...result.cacheOptions }; + } + if (is$5.object(raw.agent)) { + result.agent = { ...raw.agent }; + } + if (is$5.object(raw.headers)) { + result.headers = { ...raw.headers }; + } + if (is$5.object(retry)) { + result.retry = { ...retry }; + if (is$5.array(retry.errorCodes)) { + result.retry.errorCodes = [...retry.errorCodes]; + } + if (is$5.array(retry.methods)) { + result.retry.methods = [...retry.methods]; + } + if (is$5.array(retry.statusCodes)) { + result.retry.statusCodes = [...retry.statusCodes]; + } + } + if (is$5.object(raw.timeout)) { + result.timeout = { ...raw.timeout }; + } + if (is$5.object(hooks)) { + result.hooks = { + ...hooks, + }; + if (is$5.array(hooks.init)) { + result.hooks.init = [...hooks.init]; + } + if (is$5.array(hooks.beforeRequest)) { + result.hooks.beforeRequest = [...hooks.beforeRequest]; + } + if (is$5.array(hooks.beforeError)) { + result.hooks.beforeError = [...hooks.beforeError]; + } + if (is$5.array(hooks.beforeRedirect)) { + result.hooks.beforeRedirect = [...hooks.beforeRedirect]; + } + if (is$5.array(hooks.beforeRetry)) { + result.hooks.beforeRetry = [...hooks.beforeRetry]; + } + if (is$5.array(hooks.afterResponse)) { + result.hooks.afterResponse = [...hooks.afterResponse]; + } + } + // TODO: raw.searchParams + if (is$5.object(raw.pagination)) { + result.pagination = { ...raw.pagination }; + } + return result; +}; +const getHttp2TimeoutOption = (internals) => { + const delays = [internals.timeout.socket, internals.timeout.connect, internals.timeout.lookup, internals.timeout.request, internals.timeout.secureConnect].filter(delay => typeof delay === 'number'); + if (delays.length > 0) { + return Math.min(...delays); + } + return undefined; +}; +const init = (options, withOptions, self) => { + const initHooks = options.hooks?.init; + if (initHooks) { + for (const hook of initHooks) { + hook(withOptions, self); + } + } +}; +let Options$2 = class Options { + constructor(input, options, defaults) { + Object.defineProperty(this, "_unixOptions", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "_internals", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "_merging", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "_init", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + assert$2.any([is$5.string, is$5.urlInstance, is$5.object, is$5.undefined], input); + assert$2.any([is$5.object, is$5.undefined], options); + assert$2.any([is$5.object, is$5.undefined], defaults); + if (input instanceof Options || options instanceof Options) { + throw new TypeError('The defaults must be passed as the third argument'); + } + this._internals = cloneInternals(defaults?._internals ?? defaults ?? defaultInternals); + this._init = [...(defaults?._init ?? [])]; + this._merging = false; + this._unixOptions = undefined; + // This rule allows `finally` to be considered more important. + // Meaning no matter the error thrown in the `try` block, + // if `finally` throws then the `finally` error will be thrown. + // + // Yes, we want this. If we set `url` first, then the `url.searchParams` + // would get merged. Instead we set the `searchParams` first, then + // `url.searchParams` is overwritten as expected. + // + /* eslint-disable no-unsafe-finally */ + try { + if (is$5.plainObject(input)) { + try { + this.merge(input); + this.merge(options); + } + finally { + this.url = input.url; + } + } + else { + try { + this.merge(options); + } + finally { + if (options?.url !== undefined) { + if (input === undefined) { + this.url = options.url; + } + else { + throw new TypeError('The `url` option is mutually exclusive with the `input` argument'); + } + } + else if (input !== undefined) { + this.url = input; + } + } + } + } + catch (error) { + error.options = this; + throw error; + } + /* eslint-enable no-unsafe-finally */ + } + merge(options) { + if (!options) { + return; + } + if (options instanceof Options) { + for (const init of options._init) { + this.merge(init); + } + return; + } + options = cloneRaw(options); + init(this, options, this); + init(options, options, this); + this._merging = true; + // Always merge `isStream` first + if ('isStream' in options) { + this.isStream = options.isStream; + } + try { + let push = false; + for (const key in options) { + // `got.extend()` options + if (key === 'mutableDefaults' || key === 'handlers') { + continue; + } + // Never merge `url` + if (key === 'url') { + continue; + } + if (!(key in this)) { + throw new Error(`Unexpected option: ${key}`); + } + // @ts-expect-error Type 'unknown' is not assignable to type 'never'. + this[key] = options[key]; + push = true; + } + if (push) { + this._init.push(options); + } + } + finally { + this._merging = false; + } + } + /** + Custom request function. + The main purpose of this is to [support HTTP2 using a wrapper](https://github.com/szmarczak/http2-wrapper). + + @default http.request | https.request + */ + get request() { + return this._internals.request; + } + set request(value) { + assert$2.any([is$5.function_, is$5.undefined], value); + this._internals.request = value; + } + /** + An object representing `http`, `https` and `http2` keys for [`http.Agent`](https://nodejs.org/api/http.html#http_class_http_agent), [`https.Agent`](https://nodejs.org/api/https.html#https_class_https_agent) and [`http2wrapper.Agent`](https://github.com/szmarczak/http2-wrapper#new-http2agentoptions) instance. + This is necessary because a request to one protocol might redirect to another. + In such a scenario, Got will switch over to the right protocol agent for you. + + If a key is not present, it will default to a global agent. + + @example + ``` + import got from 'got'; + import HttpAgent from 'agentkeepalive'; + + const {HttpsAgent} = HttpAgent; + + await got('https://sindresorhus.com', { + agent: { + http: new HttpAgent(), + https: new HttpsAgent() + } + }); + ``` + */ + get agent() { + return this._internals.agent; + } + set agent(value) { + assert$2.plainObject(value); + // eslint-disable-next-line guard-for-in + for (const key in value) { + if (!(key in this._internals.agent)) { + throw new TypeError(`Unexpected agent option: ${key}`); + } + // @ts-expect-error - No idea why `value[key]` doesn't work here. + assert$2.any([is$5.object, is$5.undefined], value[key]); + } + if (this._merging) { + Object.assign(this._internals.agent, value); + } + else { + this._internals.agent = { ...value }; + } + } + get h2session() { + return this._internals.h2session; + } + set h2session(value) { + this._internals.h2session = value; + } + /** + Decompress the response automatically. + + This will set the `accept-encoding` header to `gzip, deflate, br` unless you set it yourself. + + If this is disabled, a compressed response is returned as a `Buffer`. + This may be useful if you want to handle decompression yourself or stream the raw compressed data. + + @default true + */ + get decompress() { + return this._internals.decompress; + } + set decompress(value) { + assert$2.boolean(value); + this._internals.decompress = value; + } + /** + Milliseconds to wait for the server to end the response before aborting the request with `got.TimeoutError` error (a.k.a. `request` property). + By default, there's no timeout. + + This also accepts an `object` with the following fields to constrain the duration of each phase of the request lifecycle: + + - `lookup` starts when a socket is assigned and ends when the hostname has been resolved. + Does not apply when using a Unix domain socket. + - `connect` starts when `lookup` completes (or when the socket is assigned if lookup does not apply to the request) and ends when the socket is connected. + - `secureConnect` starts when `connect` completes and ends when the handshaking process completes (HTTPS only). + - `socket` starts when the socket is connected. See [request.setTimeout](https://nodejs.org/api/http.html#http_request_settimeout_timeout_callback). + - `response` starts when the request has been written to the socket and ends when the response headers are received. + - `send` starts when the socket is connected and ends with the request has been written to the socket. + - `request` starts when the request is initiated and ends when the response's end event fires. + */ + get timeout() { + // We always return `Delays` here. + // It has to be `Delays | number`, otherwise TypeScript will error because the getter and the setter have incompatible types. + return this._internals.timeout; + } + set timeout(value) { + assert$2.plainObject(value); + // eslint-disable-next-line guard-for-in + for (const key in value) { + if (!(key in this._internals.timeout)) { + throw new Error(`Unexpected timeout option: ${key}`); + } + // @ts-expect-error - No idea why `value[key]` doesn't work here. + assert$2.any([is$5.number, is$5.undefined], value[key]); + } + if (this._merging) { + Object.assign(this._internals.timeout, value); + } + else { + this._internals.timeout = { ...value }; + } + } + /** + When specified, `prefixUrl` will be prepended to `url`. + The prefix can be any valid URL, either relative or absolute. + A trailing slash `/` is optional - one will be added automatically. + + __Note__: `prefixUrl` will be ignored if the `url` argument is a URL instance. + + __Note__: Leading slashes in `input` are disallowed when using this option to enforce consistency and avoid confusion. + For example, when the prefix URL is `https://example.com/foo` and the input is `/bar`, there's ambiguity whether the resulting URL would become `https://example.com/foo/bar` or `https://example.com/bar`. + The latter is used by browsers. + + __Tip__: Useful when used with `got.extend()` to create niche-specific Got instances. + + __Tip__: You can change `prefixUrl` using hooks as long as the URL still includes the `prefixUrl`. + If the URL doesn't include it anymore, it will throw. + + @example + ``` + import got from 'got'; + + await got('unicorn', {prefixUrl: 'https://cats.com'}); + //=> 'https://cats.com/unicorn' + + const instance = got.extend({ + prefixUrl: 'https://google.com' + }); + + await instance('unicorn', { + hooks: { + beforeRequest: [ + options => { + options.prefixUrl = 'https://cats.com'; + } + ] + } + }); + //=> 'https://cats.com/unicorn' + ``` + */ + get prefixUrl() { + // We always return `string` here. + // It has to be `string | URL`, otherwise TypeScript will error because the getter and the setter have incompatible types. + return this._internals.prefixUrl; + } + set prefixUrl(value) { + assert$2.any([is$5.string, is$5.urlInstance], value); + if (value === '') { + this._internals.prefixUrl = ''; + return; + } + value = value.toString(); + if (!value.endsWith('/')) { + value += '/'; + } + if (this._internals.prefixUrl && this._internals.url) { + const { href } = this._internals.url; + this._internals.url.href = value + href.slice(this._internals.prefixUrl.length); + } + this._internals.prefixUrl = value; + } + /** + __Note #1__: The `body` option cannot be used with the `json` or `form` option. + + __Note #2__: If you provide this option, `got.stream()` will be read-only. + + __Note #3__: If you provide a payload with the `GET` or `HEAD` method, it will throw a `TypeError` unless the method is `GET` and the `allowGetBody` option is set to `true`. + + __Note #4__: This option is not enumerable and will not be merged with the instance defaults. + + The `content-length` header will be automatically set if `body` is a `string` / `Buffer` / [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData) / [`form-data` instance](https://github.com/form-data/form-data), and `content-length` and `transfer-encoding` are not manually set in `options.headers`. + + Since Got 12, the `content-length` is not automatically set when `body` is a `fs.createReadStream`. + */ + get body() { + return this._internals.body; + } + set body(value) { + assert$2.any([is$5.string, is$5.buffer, is$5.nodeStream, is$5.generator, is$5.asyncGenerator, isFormData$1, is$5.undefined], value); + if (is$5.nodeStream(value)) { + assert$2.truthy(value.readable); + } + if (value !== undefined) { + assert$2.undefined(this._internals.form); + assert$2.undefined(this._internals.json); + } + this._internals.body = value; + } + /** + The form body is converted to a query string using [`(new URLSearchParams(object)).toString()`](https://nodejs.org/api/url.html#url_constructor_new_urlsearchparams_obj). + + If the `Content-Type` header is not present, it will be set to `application/x-www-form-urlencoded`. + + __Note #1__: If you provide this option, `got.stream()` will be read-only. + + __Note #2__: This option is not enumerable and will not be merged with the instance defaults. + */ + get form() { + return this._internals.form; + } + set form(value) { + assert$2.any([is$5.plainObject, is$5.undefined], value); + if (value !== undefined) { + assert$2.undefined(this._internals.body); + assert$2.undefined(this._internals.json); + } + this._internals.form = value; + } + /** + JSON body. If the `Content-Type` header is not set, it will be set to `application/json`. + + __Note #1__: If you provide this option, `got.stream()` will be read-only. + + __Note #2__: This option is not enumerable and will not be merged with the instance defaults. + */ + get json() { + return this._internals.json; + } + set json(value) { + if (value !== undefined) { + assert$2.undefined(this._internals.body); + assert$2.undefined(this._internals.form); + } + this._internals.json = value; + } + /** + The URL to request, as a string, a [`https.request` options object](https://nodejs.org/api/https.html#https_https_request_options_callback), or a [WHATWG `URL`](https://nodejs.org/api/url.html#url_class_url). + + Properties from `options` will override properties in the parsed `url`. + + If no protocol is specified, it will throw a `TypeError`. + + __Note__: The query string is **not** parsed as search params. + + @example + ``` + await got('https://example.com/?query=a b'); //=> https://example.com/?query=a%20b + await got('https://example.com/', {searchParams: {query: 'a b'}}); //=> https://example.com/?query=a+b + + // The query string is overridden by `searchParams` + await got('https://example.com/?query=a b', {searchParams: {query: 'a b'}}); //=> https://example.com/?query=a+b + ``` + */ + get url() { + return this._internals.url; + } + set url(value) { + assert$2.any([is$5.string, is$5.urlInstance, is$5.undefined], value); + if (value === undefined) { + this._internals.url = undefined; + return; + } + if (is$5.string(value) && value.startsWith('/')) { + throw new Error('`url` must not start with a slash'); + } + const urlString = `${this.prefixUrl}${value.toString()}`; + const url = new urlLib.URL(urlString); + this._internals.url = url; + if (url.protocol === 'unix:') { + url.href = `http://unix${url.pathname}${url.search}`; + } + if (url.protocol !== 'http:' && url.protocol !== 'https:') { + const error = new Error(`Unsupported protocol: ${url.protocol}`); + error.code = 'ERR_UNSUPPORTED_PROTOCOL'; + throw error; + } + if (this._internals.username) { + url.username = this._internals.username; + this._internals.username = ''; + } + if (this._internals.password) { + url.password = this._internals.password; + this._internals.password = ''; + } + if (this._internals.searchParams) { + url.search = this._internals.searchParams.toString(); + this._internals.searchParams = undefined; + } + if (url.hostname === 'unix') { + if (!this._internals.enableUnixSockets) { + throw new Error('Using UNIX domain sockets but option `enableUnixSockets` is not enabled'); + } + const matches = /(?.+?):(?.+)/.exec(`${url.pathname}${url.search}`); + if (matches?.groups) { + const { socketPath, path } = matches.groups; + this._unixOptions = { + socketPath, + path, + host: '', + }; + } + else { + this._unixOptions = undefined; + } + return; + } + this._unixOptions = undefined; + } + /** + Cookie support. You don't have to care about parsing or how to store them. + + __Note__: If you provide this option, `options.headers.cookie` will be overridden. + */ + get cookieJar() { + return this._internals.cookieJar; + } + set cookieJar(value) { + assert$2.any([is$5.object, is$5.undefined], value); + if (value === undefined) { + this._internals.cookieJar = undefined; + return; + } + let { setCookie, getCookieString } = value; + assert$2.function_(setCookie); + assert$2.function_(getCookieString); + /* istanbul ignore next: Horrible `tough-cookie` v3 check */ + if (setCookie.length === 4 && getCookieString.length === 0) { + setCookie = node_util.promisify(setCookie.bind(value)); + getCookieString = node_util.promisify(getCookieString.bind(value)); + this._internals.cookieJar = { + setCookie, + getCookieString: getCookieString, + }; + } + else { + this._internals.cookieJar = value; + } + } + /** + You can abort the `request` using [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController). + + *Requires Node.js 16 or later.* + + @example + ``` + import got from 'got'; + + const abortController = new AbortController(); + + const request = got('https://httpbin.org/anything', { + signal: abortController.signal + }); + + setTimeout(() => { + abortController.abort(); + }, 100); + ``` + */ + // TODO: Replace `any` with `AbortSignal` when targeting Node 16. + get signal() { + return this._internals.signal; + } + // TODO: Replace `any` with `AbortSignal` when targeting Node 16. + set signal(value) { + assert$2.object(value); + this._internals.signal = value; + } + /** + Ignore invalid cookies instead of throwing an error. + Only useful when the `cookieJar` option has been set. Not recommended. + + @default false + */ + get ignoreInvalidCookies() { + return this._internals.ignoreInvalidCookies; + } + set ignoreInvalidCookies(value) { + assert$2.boolean(value); + this._internals.ignoreInvalidCookies = value; + } + /** + Query string that will be added to the request URL. + This will override the query string in `url`. + + If you need to pass in an array, you can do it using a `URLSearchParams` instance. + + @example + ``` + import got from 'got'; + + const searchParams = new URLSearchParams([['key', 'a'], ['key', 'b']]); + + await got('https://example.com', {searchParams}); + + console.log(searchParams.toString()); + //=> 'key=a&key=b' + ``` + */ + get searchParams() { + if (this._internals.url) { + return this._internals.url.searchParams; + } + if (this._internals.searchParams === undefined) { + this._internals.searchParams = new urlLib.URLSearchParams(); + } + return this._internals.searchParams; + } + set searchParams(value) { + assert$2.any([is$5.string, is$5.object, is$5.undefined], value); + const url = this._internals.url; + if (value === undefined) { + this._internals.searchParams = undefined; + if (url) { + url.search = ''; + } + return; + } + const searchParameters = this.searchParams; + let updated; + if (is$5.string(value)) { + updated = new urlLib.URLSearchParams(value); + } + else if (value instanceof urlLib.URLSearchParams) { + updated = value; + } + else { + validateSearchParameters(value); + updated = new urlLib.URLSearchParams(); + // eslint-disable-next-line guard-for-in + for (const key in value) { + const entry = value[key]; + if (entry === null) { + updated.append(key, ''); + } + else if (entry === undefined) { + searchParameters.delete(key); + } + else { + updated.append(key, entry); + } + } + } + if (this._merging) { + // These keys will be replaced + for (const key of updated.keys()) { + searchParameters.delete(key); + } + for (const [key, value] of updated) { + searchParameters.append(key, value); + } + } + else if (url) { + url.search = searchParameters.toString(); + } + else { + this._internals.searchParams = searchParameters; + } + } + get searchParameters() { + throw new Error('The `searchParameters` option does not exist. Use `searchParams` instead.'); + } + set searchParameters(_value) { + throw new Error('The `searchParameters` option does not exist. Use `searchParams` instead.'); + } + get dnsLookup() { + return this._internals.dnsLookup; + } + set dnsLookup(value) { + assert$2.any([is$5.function_, is$5.undefined], value); + this._internals.dnsLookup = value; + } + /** + An instance of [`CacheableLookup`](https://github.com/szmarczak/cacheable-lookup) used for making DNS lookups. + Useful when making lots of requests to different *public* hostnames. + + `CacheableLookup` uses `dns.resolver4(..)` and `dns.resolver6(...)` under the hood and fall backs to `dns.lookup(...)` when the first two fail, which may lead to additional delay. + + __Note__: This should stay disabled when making requests to internal hostnames such as `localhost`, `database.local` etc. + + @default false + */ + get dnsCache() { + return this._internals.dnsCache; + } + set dnsCache(value) { + assert$2.any([is$5.object, is$5.boolean, is$5.undefined], value); + if (value === true) { + this._internals.dnsCache = getGlobalDnsCache(); + } + else if (value === false) { + this._internals.dnsCache = undefined; + } + else { + this._internals.dnsCache = value; + } + } + /** + User data. `context` is shallow merged and enumerable. If it contains non-enumerable properties they will NOT be merged. + + @example + ``` + import got from 'got'; + + const instance = got.extend({ + hooks: { + beforeRequest: [ + options => { + if (!options.context || !options.context.token) { + throw new Error('Token required'); + } + + options.headers.token = options.context.token; + } + ] + } + }); + + const context = { + token: 'secret' + }; + + const response = await instance('https://httpbin.org/headers', {context}); + + // Let's see the headers + console.log(response.body); + ``` + */ + get context() { + return this._internals.context; + } + set context(value) { + assert$2.object(value); + if (this._merging) { + Object.assign(this._internals.context, value); + } + else { + this._internals.context = { ...value }; + } + } + /** + Hooks allow modifications during the request lifecycle. + Hook functions may be async and are run serially. + */ + get hooks() { + return this._internals.hooks; + } + set hooks(value) { + assert$2.object(value); + // eslint-disable-next-line guard-for-in + for (const knownHookEvent in value) { + if (!(knownHookEvent in this._internals.hooks)) { + throw new Error(`Unexpected hook event: ${knownHookEvent}`); + } + const typedKnownHookEvent = knownHookEvent; + const hooks = value[typedKnownHookEvent]; + assert$2.any([is$5.array, is$5.undefined], hooks); + if (hooks) { + for (const hook of hooks) { + assert$2.function_(hook); + } + } + if (this._merging) { + if (hooks) { + // @ts-expect-error FIXME + this._internals.hooks[typedKnownHookEvent].push(...hooks); + } + } + else { + if (!hooks) { + throw new Error(`Missing hook event: ${knownHookEvent}`); + } + // @ts-expect-error FIXME + this._internals.hooks[knownHookEvent] = [...hooks]; + } + } + } + /** + Defines if redirect responses should be followed automatically. + + Note that if a `303` is sent by the server in response to any request type (`POST`, `DELETE`, etc.), Got will automatically request the resource pointed to in the location header via `GET`. + This is in accordance with [the spec](https://tools.ietf.org/html/rfc7231#section-6.4.4). You can optionally turn on this behavior also for other redirect codes - see `methodRewriting`. + + @default true + */ + get followRedirect() { + return this._internals.followRedirect; + } + set followRedirect(value) { + assert$2.boolean(value); + this._internals.followRedirect = value; + } + get followRedirects() { + throw new TypeError('The `followRedirects` option does not exist. Use `followRedirect` instead.'); + } + set followRedirects(_value) { + throw new TypeError('The `followRedirects` option does not exist. Use `followRedirect` instead.'); + } + /** + If exceeded, the request will be aborted and a `MaxRedirectsError` will be thrown. + + @default 10 + */ + get maxRedirects() { + return this._internals.maxRedirects; + } + set maxRedirects(value) { + assert$2.number(value); + this._internals.maxRedirects = value; + } + /** + A cache adapter instance for storing cached response data. + + @default false + */ + get cache() { + return this._internals.cache; + } + set cache(value) { + assert$2.any([is$5.object, is$5.string, is$5.boolean, is$5.undefined], value); + if (value === true) { + this._internals.cache = globalCache; + } + else if (value === false) { + this._internals.cache = undefined; + } + else { + this._internals.cache = value; + } + } + /** + Determines if a `got.HTTPError` is thrown for unsuccessful responses. + + If this is disabled, requests that encounter an error status code will be resolved with the `response` instead of throwing. + This may be useful if you are checking for resource availability and are expecting error responses. + + @default true + */ + get throwHttpErrors() { + return this._internals.throwHttpErrors; + } + set throwHttpErrors(value) { + assert$2.boolean(value); + this._internals.throwHttpErrors = value; + } + get username() { + const url = this._internals.url; + const value = url ? url.username : this._internals.username; + return decodeURIComponent(value); + } + set username(value) { + assert$2.string(value); + const url = this._internals.url; + const fixedValue = encodeURIComponent(value); + if (url) { + url.username = fixedValue; + } + else { + this._internals.username = fixedValue; + } + } + get password() { + const url = this._internals.url; + const value = url ? url.password : this._internals.password; + return decodeURIComponent(value); + } + set password(value) { + assert$2.string(value); + const url = this._internals.url; + const fixedValue = encodeURIComponent(value); + if (url) { + url.password = fixedValue; + } + else { + this._internals.password = fixedValue; + } + } + /** + If set to `true`, Got will additionally accept HTTP2 requests. + + It will choose either HTTP/1.1 or HTTP/2 depending on the ALPN protocol. + + __Note__: This option requires Node.js 15.10.0 or newer as HTTP/2 support on older Node.js versions is very buggy. + + __Note__: Overriding `options.request` will disable HTTP2 support. + + @default false + + @example + ``` + import got from 'got'; + + const {headers} = await got('https://nghttp2.org/httpbin/anything', {http2: true}); + + console.log(headers.via); + //=> '2 nghttpx' + ``` + */ + get http2() { + return this._internals.http2; + } + set http2(value) { + assert$2.boolean(value); + this._internals.http2 = value; + } + /** + Set this to `true` to allow sending body for the `GET` method. + However, the [HTTP/2 specification](https://tools.ietf.org/html/rfc7540#section-8.1.3) says that `An HTTP GET request includes request header fields and no payload body`, therefore when using the HTTP/2 protocol this option will have no effect. + This option is only meant to interact with non-compliant servers when you have no other choice. + + __Note__: The [RFC 7231](https://tools.ietf.org/html/rfc7231#section-4.3.1) doesn't specify any particular behavior for the GET method having a payload, therefore __it's considered an [anti-pattern](https://en.wikipedia.org/wiki/Anti-pattern)__. + + @default false + */ + get allowGetBody() { + return this._internals.allowGetBody; + } + set allowGetBody(value) { + assert$2.boolean(value); + this._internals.allowGetBody = value; + } + /** + Request headers. + + Existing headers will be overwritten. Headers set to `undefined` will be omitted. + + @default {} + */ + get headers() { + return this._internals.headers; + } + set headers(value) { + assert$2.plainObject(value); + if (this._merging) { + Object.assign(this._internals.headers, lowercaseKeys(value)); + } + else { + this._internals.headers = lowercaseKeys(value); + } + } + /** + Specifies if the HTTP request method should be [rewritten as `GET`](https://tools.ietf.org/html/rfc7231#section-6.4) on redirects. + + As the [specification](https://tools.ietf.org/html/rfc7231#section-6.4) prefers to rewrite the HTTP method only on `303` responses, this is Got's default behavior. + Setting `methodRewriting` to `true` will also rewrite `301` and `302` responses, as allowed by the spec. This is the behavior followed by `curl` and browsers. + + __Note__: Got never performs method rewriting on `307` and `308` responses, as this is [explicitly prohibited by the specification](https://www.rfc-editor.org/rfc/rfc7231#section-6.4.7). + + @default false + */ + get methodRewriting() { + return this._internals.methodRewriting; + } + set methodRewriting(value) { + assert$2.boolean(value); + this._internals.methodRewriting = value; + } + /** + Indicates which DNS record family to use. + + Values: + - `undefined`: IPv4 (if present) or IPv6 + - `4`: Only IPv4 + - `6`: Only IPv6 + + @default undefined + */ + get dnsLookupIpVersion() { + return this._internals.dnsLookupIpVersion; + } + set dnsLookupIpVersion(value) { + if (value !== undefined && value !== 4 && value !== 6) { + throw new TypeError(`Invalid DNS lookup IP version: ${value}`); + } + this._internals.dnsLookupIpVersion = value; + } + /** + A function used to parse JSON responses. + + @example + ``` + import got from 'got'; + import Bourne from '@hapi/bourne'; + + const parsed = await got('https://example.com', { + parseJson: text => Bourne.parse(text) + }).json(); + + console.log(parsed); + ``` + */ + get parseJson() { + return this._internals.parseJson; + } + set parseJson(value) { + assert$2.function_(value); + this._internals.parseJson = value; + } + /** + A function used to stringify the body of JSON requests. + + @example + ``` + import got from 'got'; + + await got.post('https://example.com', { + stringifyJson: object => JSON.stringify(object, (key, value) => { + if (key.startsWith('_')) { + return; + } + + return value; + }), + json: { + some: 'payload', + _ignoreMe: 1234 + } + }); + ``` + + @example + ``` + import got from 'got'; + + await got.post('https://example.com', { + stringifyJson: object => JSON.stringify(object, (key, value) => { + if (typeof value === 'number') { + return value.toString(); + } + + return value; + }), + json: { + some: 'payload', + number: 1 + } + }); + ``` + */ + get stringifyJson() { + return this._internals.stringifyJson; + } + set stringifyJson(value) { + assert$2.function_(value); + this._internals.stringifyJson = value; + } + /** + An object representing `limit`, `calculateDelay`, `methods`, `statusCodes`, `maxRetryAfter` and `errorCodes` fields for maximum retry count, retry handler, allowed methods, allowed status codes, maximum [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) time and allowed error codes. + + Delays between retries counts with function `1000 * Math.pow(2, retry) + Math.random() * 100`, where `retry` is attempt number (starts from 1). + + The `calculateDelay` property is a `function` that receives an object with `attemptCount`, `retryOptions`, `error` and `computedValue` properties for current retry count, the retry options, error and default computed value. + The function must return a delay in milliseconds (or a Promise resolving with it) (`0` return value cancels retry). + + By default, it retries *only* on the specified methods, status codes, and on these network errors: + + - `ETIMEDOUT`: One of the [timeout](#timeout) limits were reached. + - `ECONNRESET`: Connection was forcibly closed by a peer. + - `EADDRINUSE`: Could not bind to any free port. + - `ECONNREFUSED`: Connection was refused by the server. + - `EPIPE`: The remote side of the stream being written has been closed. + - `ENOTFOUND`: Couldn't resolve the hostname to an IP address. + - `ENETUNREACH`: No internet connection. + - `EAI_AGAIN`: DNS lookup timed out. + + __Note__: If `maxRetryAfter` is set to `undefined`, it will use `options.timeout`. + __Note__: If [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) header is greater than `maxRetryAfter`, it will cancel the request. + */ + get retry() { + return this._internals.retry; + } + set retry(value) { + assert$2.plainObject(value); + assert$2.any([is$5.function_, is$5.undefined], value.calculateDelay); + assert$2.any([is$5.number, is$5.undefined], value.maxRetryAfter); + assert$2.any([is$5.number, is$5.undefined], value.limit); + assert$2.any([is$5.array, is$5.undefined], value.methods); + assert$2.any([is$5.array, is$5.undefined], value.statusCodes); + assert$2.any([is$5.array, is$5.undefined], value.errorCodes); + assert$2.any([is$5.number, is$5.undefined], value.noise); + if (value.noise && Math.abs(value.noise) > 100) { + throw new Error(`The maximum acceptable retry noise is +/- 100ms, got ${value.noise}`); + } + for (const key in value) { + if (!(key in this._internals.retry)) { + throw new Error(`Unexpected retry option: ${key}`); + } + } + if (this._merging) { + Object.assign(this._internals.retry, value); + } + else { + this._internals.retry = { ...value }; + } + const { retry } = this._internals; + retry.methods = [...new Set(retry.methods.map(method => method.toUpperCase()))]; + retry.statusCodes = [...new Set(retry.statusCodes)]; + retry.errorCodes = [...new Set(retry.errorCodes)]; + } + /** + From `http.RequestOptions`. + + The IP address used to send the request from. + */ + get localAddress() { + return this._internals.localAddress; + } + set localAddress(value) { + assert$2.any([is$5.string, is$5.undefined], value); + this._internals.localAddress = value; + } + /** + The HTTP method used to make the request. + + @default 'GET' + */ + get method() { + return this._internals.method; + } + set method(value) { + assert$2.string(value); + this._internals.method = value.toUpperCase(); + } + get createConnection() { + return this._internals.createConnection; + } + set createConnection(value) { + assert$2.any([is$5.function_, is$5.undefined], value); + this._internals.createConnection = value; + } + /** + From `http-cache-semantics` + + @default {} + */ + get cacheOptions() { + return this._internals.cacheOptions; + } + set cacheOptions(value) { + assert$2.plainObject(value); + assert$2.any([is$5.boolean, is$5.undefined], value.shared); + assert$2.any([is$5.number, is$5.undefined], value.cacheHeuristic); + assert$2.any([is$5.number, is$5.undefined], value.immutableMinTimeToLive); + assert$2.any([is$5.boolean, is$5.undefined], value.ignoreCargoCult); + for (const key in value) { + if (!(key in this._internals.cacheOptions)) { + throw new Error(`Cache option \`${key}\` does not exist`); + } + } + if (this._merging) { + Object.assign(this._internals.cacheOptions, value); + } + else { + this._internals.cacheOptions = { ...value }; + } + } + /** + Options for the advanced HTTPS API. + */ + get https() { + return this._internals.https; + } + set https(value) { + assert$2.plainObject(value); + assert$2.any([is$5.boolean, is$5.undefined], value.rejectUnauthorized); + assert$2.any([is$5.function_, is$5.undefined], value.checkServerIdentity); + assert$2.any([is$5.string, is$5.object, is$5.array, is$5.undefined], value.certificateAuthority); + assert$2.any([is$5.string, is$5.object, is$5.array, is$5.undefined], value.key); + assert$2.any([is$5.string, is$5.object, is$5.array, is$5.undefined], value.certificate); + assert$2.any([is$5.string, is$5.undefined], value.passphrase); + assert$2.any([is$5.string, is$5.buffer, is$5.array, is$5.undefined], value.pfx); + assert$2.any([is$5.array, is$5.undefined], value.alpnProtocols); + assert$2.any([is$5.string, is$5.undefined], value.ciphers); + assert$2.any([is$5.string, is$5.buffer, is$5.undefined], value.dhparam); + assert$2.any([is$5.string, is$5.undefined], value.signatureAlgorithms); + assert$2.any([is$5.string, is$5.undefined], value.minVersion); + assert$2.any([is$5.string, is$5.undefined], value.maxVersion); + assert$2.any([is$5.boolean, is$5.undefined], value.honorCipherOrder); + assert$2.any([is$5.number, is$5.undefined], value.tlsSessionLifetime); + assert$2.any([is$5.string, is$5.undefined], value.ecdhCurve); + assert$2.any([is$5.string, is$5.buffer, is$5.array, is$5.undefined], value.certificateRevocationLists); + for (const key in value) { + if (!(key in this._internals.https)) { + throw new Error(`HTTPS option \`${key}\` does not exist`); + } + } + if (this._merging) { + Object.assign(this._internals.https, value); + } + else { + this._internals.https = { ...value }; + } + } + /** + [Encoding](https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings) to be used on `setEncoding` of the response data. + + To get a [`Buffer`](https://nodejs.org/api/buffer.html), you need to set `responseType` to `buffer` instead. + Don't set this option to `null`. + + __Note__: This doesn't affect streams! Instead, you need to do `got.stream(...).setEncoding(encoding)`. + + @default 'utf-8' + */ + get encoding() { + return this._internals.encoding; + } + set encoding(value) { + if (value === null) { + throw new TypeError('To get a Buffer, set `options.responseType` to `buffer` instead'); + } + assert$2.any([is$5.string, is$5.undefined], value); + this._internals.encoding = value; + } + /** + When set to `true` the promise will return the Response body instead of the Response object. + + @default false + */ + get resolveBodyOnly() { + return this._internals.resolveBodyOnly; + } + set resolveBodyOnly(value) { + assert$2.boolean(value); + this._internals.resolveBodyOnly = value; + } + /** + Returns a `Stream` instead of a `Promise`. + This is equivalent to calling `got.stream(url, options?)`. + + @default false + */ + get isStream() { + return this._internals.isStream; + } + set isStream(value) { + assert$2.boolean(value); + this._internals.isStream = value; + } + /** + The parsing method. + + The promise also has `.text()`, `.json()` and `.buffer()` methods which return another Got promise for the parsed body. + + It's like setting the options to `{responseType: 'json', resolveBodyOnly: true}` but without affecting the main Got promise. + + __Note__: When using streams, this option is ignored. + + @example + ``` + const responsePromise = got(url); + const bufferPromise = responsePromise.buffer(); + const jsonPromise = responsePromise.json(); + + const [response, buffer, json] = Promise.all([responsePromise, bufferPromise, jsonPromise]); + // `response` is an instance of Got Response + // `buffer` is an instance of Buffer + // `json` is an object + ``` + + @example + ``` + // This + const body = await got(url).json(); + + // is semantically the same as this + const body = await got(url, {responseType: 'json', resolveBodyOnly: true}); + ``` + */ + get responseType() { + return this._internals.responseType; + } + set responseType(value) { + if (value === undefined) { + this._internals.responseType = 'text'; + return; + } + if (value !== 'text' && value !== 'buffer' && value !== 'json') { + throw new Error(`Invalid \`responseType\` option: ${value}`); + } + this._internals.responseType = value; + } + get pagination() { + return this._internals.pagination; + } + set pagination(value) { + assert$2.object(value); + if (this._merging) { + Object.assign(this._internals.pagination, value); + } + else { + this._internals.pagination = value; + } + } + get auth() { + throw new Error('Parameter `auth` is deprecated. Use `username` / `password` instead.'); + } + set auth(_value) { + throw new Error('Parameter `auth` is deprecated. Use `username` / `password` instead.'); + } + get setHost() { + return this._internals.setHost; + } + set setHost(value) { + assert$2.boolean(value); + this._internals.setHost = value; + } + get maxHeaderSize() { + return this._internals.maxHeaderSize; + } + set maxHeaderSize(value) { + assert$2.any([is$5.number, is$5.undefined], value); + this._internals.maxHeaderSize = value; + } + get enableUnixSockets() { + return this._internals.enableUnixSockets; + } + set enableUnixSockets(value) { + assert$2.boolean(value); + this._internals.enableUnixSockets = value; + } + // eslint-disable-next-line @typescript-eslint/naming-convention + toJSON() { + return { ...this._internals }; + } + [Symbol.for('nodejs.util.inspect.custom')](_depth, options) { + return node_util.inspect(this._internals, options); + } + createNativeRequestOptions() { + const internals = this._internals; + const url = internals.url; + let agent; + if (url.protocol === 'https:') { + agent = internals.http2 ? internals.agent : internals.agent.https; + } + else { + agent = internals.agent.http; + } + const { https } = internals; + let { pfx } = https; + if (is$5.array(pfx) && is$5.plainObject(pfx[0])) { + pfx = pfx.map(object => ({ + buf: object.buffer, + passphrase: object.passphrase, + })); + } + return { + ...internals.cacheOptions, + ...this._unixOptions, + // HTTPS options + // eslint-disable-next-line @typescript-eslint/naming-convention + ALPNProtocols: https.alpnProtocols, + ca: https.certificateAuthority, + cert: https.certificate, + key: https.key, + passphrase: https.passphrase, + pfx: https.pfx, + rejectUnauthorized: https.rejectUnauthorized, + checkServerIdentity: https.checkServerIdentity ?? node_tls.checkServerIdentity, + ciphers: https.ciphers, + honorCipherOrder: https.honorCipherOrder, + minVersion: https.minVersion, + maxVersion: https.maxVersion, + sigalgs: https.signatureAlgorithms, + sessionTimeout: https.tlsSessionLifetime, + dhparam: https.dhparam, + ecdhCurve: https.ecdhCurve, + crl: https.certificateRevocationLists, + // HTTP options + lookup: internals.dnsLookup ?? internals.dnsCache?.lookup, + family: internals.dnsLookupIpVersion, + agent, + setHost: internals.setHost, + method: internals.method, + maxHeaderSize: internals.maxHeaderSize, + localAddress: internals.localAddress, + headers: internals.headers, + createConnection: internals.createConnection, + timeout: internals.http2 ? getHttp2TimeoutOption(internals) : undefined, + // HTTP/2 options + h2session: internals.h2session, + }; + } + getRequestFunction() { + const url = this._internals.url; + const { request } = this._internals; + if (!request && url) { + return this.getFallbackRequestFunction(); + } + return request; + } + getFallbackRequestFunction() { + const url = this._internals.url; + if (!url) { + return; + } + if (url.protocol === 'https:') { + if (this._internals.http2) { + if (major < 15 || (major === 15 && minor < 10)) { + const error = new Error('To use the `http2` option, install Node.js 15.10.0 or above'); + error.code = 'EUNSUPPORTED'; + throw error; + } + return http2wrapper.auto; + } + return https$8.request; + } + return http$a.request; + } + freeze() { + const options = this._internals; + Object.freeze(options); + Object.freeze(options.hooks); + Object.freeze(options.hooks.afterResponse); + Object.freeze(options.hooks.beforeError); + Object.freeze(options.hooks.beforeRedirect); + Object.freeze(options.hooks.beforeRequest); + Object.freeze(options.hooks.beforeRetry); + Object.freeze(options.hooks.init); + Object.freeze(options.https); + Object.freeze(options.cacheOptions); + Object.freeze(options.agent); + Object.freeze(options.headers); + Object.freeze(options.timeout); + Object.freeze(options.retry); + Object.freeze(options.retry.errorCodes); + Object.freeze(options.retry.methods); + Object.freeze(options.retry.statusCodes); + } +}; + +const isResponseOk = (response) => { + const { statusCode } = response; + const limitStatusCode = response.request.options.followRedirect ? 299 : 399; + return (statusCode >= 200 && statusCode <= limitStatusCode) || statusCode === 304; +}; +/** +An error to be thrown when server response code is 2xx, and parsing body fails. +Includes a `response` property. +*/ +class ParseError extends RequestError$1 { + constructor(error, response) { + const { options } = response.request; + super(`${error.message} in "${options.url.toString()}"`, error, response.request); + this.name = 'ParseError'; + this.code = 'ERR_BODY_PARSE_FAILURE'; + } +} +const parseBody$1 = (response, responseType, parseJson, encoding) => { + const { rawBody } = response; + try { + if (responseType === 'text') { + return rawBody.toString(encoding); + } + if (responseType === 'json') { + return rawBody.length === 0 ? '' : parseJson(rawBody.toString(encoding)); + } + if (responseType === 'buffer') { + return rawBody; + } + } + catch (error) { + throw new ParseError(error, response); + } + throw new ParseError({ + message: `Unknown body type '${responseType}'`, + name: 'Error', + }, response); +}; + +function isClientRequest(clientRequest) { + return clientRequest.writable && !clientRequest.writableEnded; +} + +// eslint-disable-next-line @typescript-eslint/naming-convention +function isUnixSocketURL(url) { + return url.protocol === 'unix:' || url.hostname === 'unix'; +} + +const { buffer: getBuffer } = getStream$3; +const supportsBrotli = is$5.string(process$3.versions.brotli); +const methodsWithoutBody = new Set(['GET', 'HEAD']); +const cacheableStore = new WeakableMap(); +const redirectCodes = new Set([300, 301, 302, 303, 304, 307, 308]); +const proxiedRequestEvents$1 = [ + 'socket', + 'connect', + 'continue', + 'information', + 'upgrade', +]; +const noop$5 = () => { }; +let Request$3 = class Request extends Stream$4.Duplex { + constructor(url, options, defaults) { + super({ + // Don't destroy immediately, as the error may be emitted on unsuccessful retry + autoDestroy: false, + // It needs to be zero because we're just proxying the data to another stream + highWaterMark: 0, + }); + // @ts-expect-error - Ignoring for now. + Object.defineProperty(this, 'constructor', { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "_noPipe", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + // @ts-expect-error https://github.com/microsoft/TypeScript/issues/9568 + Object.defineProperty(this, "options", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "response", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "requestUrl", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "redirectUrls", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "retryCount", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "_stopRetry", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "_downloadedSize", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "_uploadedSize", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "_stopReading", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "_pipedServerResponses", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "_request", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "_responseSize", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "_bodySize", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "_unproxyEvents", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "_isFromCache", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "_cannotHaveBody", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "_triggerRead", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "_cancelTimeouts", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "_removeListeners", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "_nativeResponse", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "_flushed", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "_aborted", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + // We need this because `this._request` if `undefined` when using cache + Object.defineProperty(this, "_requestInitialized", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this._downloadedSize = 0; + this._uploadedSize = 0; + this._stopReading = false; + this._pipedServerResponses = new Set(); + this._cannotHaveBody = false; + this._unproxyEvents = noop$5; + this._triggerRead = false; + this._cancelTimeouts = noop$5; + this._removeListeners = noop$5; + this._jobs = []; + this._flushed = false; + this._requestInitialized = false; + this._aborted = false; + this.redirectUrls = []; + this.retryCount = 0; + this._stopRetry = noop$5; + this.on('pipe', (source) => { + if (source?.headers) { + Object.assign(this.options.headers, source.headers); + } + }); + this.on('newListener', event => { + if (event === 'retry' && this.listenerCount('retry') > 0) { + throw new Error('A retry listener has been attached already.'); + } + }); + try { + this.options = new Options$2(url, options, defaults); + if (!this.options.url) { + if (this.options.prefixUrl === '') { + throw new TypeError('Missing `url` property'); + } + this.options.url = ''; + } + this.requestUrl = this.options.url; + } + catch (error) { + const { options } = error; + if (options) { + this.options = options; + } + this.flush = async () => { + this.flush = async () => { }; + this.destroy(error); + }; + return; + } + // Important! If you replace `body` in a handler with another stream, make sure it's readable first. + // The below is run only once. + const { body } = this.options; + if (is$5.nodeStream(body)) { + body.once('error', error => { + if (this._flushed) { + this._beforeError(new UploadError(error, this)); + } + else { + this.flush = async () => { + this.flush = async () => { }; + this._beforeError(new UploadError(error, this)); + }; + } + }); + } + if (this.options.signal) { + const abort = () => { + this.destroy(new AbortError$3(this)); + }; + if (this.options.signal.aborted) { + abort(); + } + else { + this.options.signal.addEventListener('abort', abort); + this._removeListeners = () => { + this.options.signal.removeEventListener('abort', abort); + }; + } + } + } + async flush() { + if (this._flushed) { + return; + } + this._flushed = true; + try { + await this._finalizeBody(); + if (this.destroyed) { + return; + } + await this._makeRequest(); + if (this.destroyed) { + this._request?.destroy(); + return; + } + // Queued writes etc. + for (const job of this._jobs) { + job(); + } + // Prevent memory leak + this._jobs.length = 0; + this._requestInitialized = true; + } + catch (error) { + this._beforeError(error); + } + } + _beforeError(error) { + if (this._stopReading) { + return; + } + const { response, options } = this; + const attemptCount = this.retryCount + (error.name === 'RetryError' ? 0 : 1); + this._stopReading = true; + if (!(error instanceof RequestError$1)) { + error = new RequestError$1(error.message, error, this); + } + const typedError = error; + void (async () => { + // Node.js parser is really weird. + // It emits post-request Parse Errors on the same instance as previous request. WTF. + // Therefore we need to check if it has been destroyed as well. + // + // Furthermore, Node.js 16 `response.destroy()` doesn't immediately destroy the socket, + // but makes the response unreadable. So we additionally need to check `response.readable`. + if (response?.readable && !response.rawBody && !this._request?.socket?.destroyed) { + // @types/node has incorrect typings. `setEncoding` accepts `null` as well. + response.setEncoding(this.readableEncoding); + const success = await this._setRawBody(response); + if (success) { + response.body = response.rawBody.toString(); + } + } + if (this.listenerCount('retry') !== 0) { + let backoff; + try { + let retryAfter; + if (response && 'retry-after' in response.headers) { + retryAfter = Number(response.headers['retry-after']); + if (Number.isNaN(retryAfter)) { + retryAfter = Date.parse(response.headers['retry-after']) - Date.now(); + if (retryAfter <= 0) { + retryAfter = 1; + } + } + else { + retryAfter *= 1000; + } + } + const retryOptions = options.retry; + backoff = await retryOptions.calculateDelay({ + attemptCount, + retryOptions, + error: typedError, + retryAfter, + computedValue: calculateRetryDelay$1({ + attemptCount, + retryOptions, + error: typedError, + retryAfter, + computedValue: retryOptions.maxRetryAfter ?? options.timeout.request ?? Number.POSITIVE_INFINITY, + }), + }); + } + catch (error_) { + void this._error(new RequestError$1(error_.message, error_, this)); + return; + } + if (backoff) { + await new Promise(resolve => { + const timeout = setTimeout(resolve, backoff); + this._stopRetry = () => { + clearTimeout(timeout); + resolve(); + }; + }); + // Something forced us to abort the retry + if (this.destroyed) { + return; + } + try { + for (const hook of this.options.hooks.beforeRetry) { + // eslint-disable-next-line no-await-in-loop + await hook(typedError, this.retryCount + 1); + } + } + catch (error_) { + void this._error(new RequestError$1(error_.message, error, this)); + return; + } + // Something forced us to abort the retry + if (this.destroyed) { + return; + } + this.destroy(); + this.emit('retry', this.retryCount + 1, error, (updatedOptions) => { + const request = new Request(options.url, updatedOptions, options); + request.retryCount = this.retryCount + 1; + process$3.nextTick(() => { + void request.flush(); + }); + return request; + }); + return; + } + } + void this._error(typedError); + })(); + } + _read() { + this._triggerRead = true; + const { response } = this; + if (response && !this._stopReading) { + // We cannot put this in the `if` above + // because `.read()` also triggers the `end` event + if (response.readableLength) { + this._triggerRead = false; + } + let data; + while ((data = response.read()) !== null) { + this._downloadedSize += data.length; // eslint-disable-line @typescript-eslint/restrict-plus-operands + const progress = this.downloadProgress; + if (progress.percent < 1) { + this.emit('downloadProgress', progress); + } + this.push(data); + } + } + } + _write(chunk, encoding, callback) { + const write = () => { + this._writeRequest(chunk, encoding, callback); + }; + if (this._requestInitialized) { + write(); + } + else { + this._jobs.push(write); + } + } + _final(callback) { + const endRequest = () => { + // We need to check if `this._request` is present, + // because it isn't when we use cache. + if (!this._request || this._request.destroyed) { + callback(); + return; + } + this._request.end((error) => { + // The request has been destroyed before `_final` finished. + // See https://github.com/nodejs/node/issues/39356 + if (this._request._writableState?.errored) { + return; + } + if (!error) { + this._bodySize = this._uploadedSize; + this.emit('uploadProgress', this.uploadProgress); + this._request.emit('upload-complete'); + } + callback(error); + }); + }; + if (this._requestInitialized) { + endRequest(); + } + else { + this._jobs.push(endRequest); + } + } + _destroy(error, callback) { + this._stopReading = true; + this.flush = async () => { }; + // Prevent further retries + this._stopRetry(); + this._cancelTimeouts(); + this._removeListeners(); + if (this.options) { + const { body } = this.options; + if (is$5.nodeStream(body)) { + body.destroy(); + } + } + if (this._request) { + this._request.destroy(); + } + if (error !== null && !is$5.undefined(error) && !(error instanceof RequestError$1)) { + error = new RequestError$1(error.message, error, this); + } + callback(error); + } + pipe(destination, options) { + if (destination instanceof http$a.ServerResponse) { + this._pipedServerResponses.add(destination); + } + return super.pipe(destination, options); + } + unpipe(destination) { + if (destination instanceof http$a.ServerResponse) { + this._pipedServerResponses.delete(destination); + } + super.unpipe(destination); + return this; + } + async _finalizeBody() { + const { options } = this; + const { headers } = options; + const isForm = !is$5.undefined(options.form); + // eslint-disable-next-line @typescript-eslint/naming-convention + const isJSON = !is$5.undefined(options.json); + const isBody = !is$5.undefined(options.body); + const cannotHaveBody = methodsWithoutBody.has(options.method) && !(options.method === 'GET' && options.allowGetBody); + this._cannotHaveBody = cannotHaveBody; + if (isForm || isJSON || isBody) { + if (cannotHaveBody) { + throw new TypeError(`The \`${options.method}\` method cannot be used with a body`); + } + // Serialize body + const noContentType = !is$5.string(headers['content-type']); + if (isBody) { + // Body is spec-compliant FormData + if (isFormData$1(options.body)) { + const encoder = new FormDataEncoder(options.body); + if (noContentType) { + headers['content-type'] = encoder.headers['Content-Type']; + } + if ('Content-Length' in encoder.headers) { + headers['content-length'] = encoder.headers['Content-Length']; + } + options.body = encoder.encode(); + } + // Special case for https://github.com/form-data/form-data + if (isFormData(options.body) && noContentType) { + headers['content-type'] = `multipart/form-data; boundary=${options.body.getBoundary()}`; + } + } + else if (isForm) { + if (noContentType) { + headers['content-type'] = 'application/x-www-form-urlencoded'; + } + const { form } = options; + options.form = undefined; + options.body = (new urlLib.URLSearchParams(form)).toString(); + } + else { + if (noContentType) { + headers['content-type'] = 'application/json'; + } + const { json } = options; + options.json = undefined; + options.body = options.stringifyJson(json); + } + const uploadBodySize = await getBodySize(options.body, options.headers); + // See https://tools.ietf.org/html/rfc7230#section-3.3.2 + // A user agent SHOULD send a Content-Length in a request message when + // no Transfer-Encoding is sent and the request method defines a meaning + // for an enclosed payload body. For example, a Content-Length header + // field is normally sent in a POST request even when the value is 0 + // (indicating an empty payload body). A user agent SHOULD NOT send a + // Content-Length header field when the request message does not contain + // a payload body and the method semantics do not anticipate such a + // body. + if (is$5.undefined(headers['content-length']) && is$5.undefined(headers['transfer-encoding']) && !cannotHaveBody && !is$5.undefined(uploadBodySize)) { + headers['content-length'] = String(uploadBodySize); + } + } + if (options.responseType === 'json' && !('accept' in options.headers)) { + options.headers.accept = 'application/json'; + } + this._bodySize = Number(headers['content-length']) || undefined; + } + async _onResponseBase(response) { + // This will be called e.g. when using cache so we need to check if this request has been aborted. + if (this.isAborted) { + return; + } + const { options } = this; + const { url } = options; + this._nativeResponse = response; + if (options.decompress) { + response = decompressResponse$1(response); + } + const statusCode = response.statusCode; + const typedResponse = response; + typedResponse.statusMessage = typedResponse.statusMessage ?? http$a.STATUS_CODES[statusCode]; + typedResponse.url = options.url.toString(); + typedResponse.requestUrl = this.requestUrl; + typedResponse.redirectUrls = this.redirectUrls; + typedResponse.request = this; + typedResponse.isFromCache = this._nativeResponse.fromCache ?? false; + typedResponse.ip = this.ip; + typedResponse.retryCount = this.retryCount; + typedResponse.ok = isResponseOk(typedResponse); + this._isFromCache = typedResponse.isFromCache; + this._responseSize = Number(response.headers['content-length']) || undefined; + this.response = typedResponse; + response.once('end', () => { + this._responseSize = this._downloadedSize; + this.emit('downloadProgress', this.downloadProgress); + }); + response.once('error', (error) => { + this._aborted = true; + // Force clean-up, because some packages don't do this. + // TODO: Fix decompress-response + response.destroy(); + this._beforeError(new ReadError(error, this)); + }); + response.once('aborted', () => { + this._aborted = true; + this._beforeError(new ReadError({ + name: 'Error', + message: 'The server aborted pending request', + code: 'ECONNRESET', + }, this)); + }); + this.emit('downloadProgress', this.downloadProgress); + const rawCookies = response.headers['set-cookie']; + if (is$5.object(options.cookieJar) && rawCookies) { + let promises = rawCookies.map(async (rawCookie) => options.cookieJar.setCookie(rawCookie, url.toString())); + if (options.ignoreInvalidCookies) { + promises = promises.map(async (promise) => { + try { + await promise; + } + catch { } + }); + } + try { + await Promise.all(promises); + } + catch (error) { + this._beforeError(error); + return; + } + } + // The above is running a promise, therefore we need to check if this request has been aborted yet again. + if (this.isAborted) { + return; + } + if (options.followRedirect && response.headers.location && redirectCodes.has(statusCode)) { + // We're being redirected, we don't care about the response. + // It'd be best to abort the request, but we can't because + // we would have to sacrifice the TCP connection. We don't want that. + response.resume(); + this._cancelTimeouts(); + this._unproxyEvents(); + if (this.redirectUrls.length >= options.maxRedirects) { + this._beforeError(new MaxRedirectsError(this)); + return; + } + this._request = undefined; + const updatedOptions = new Options$2(undefined, undefined, this.options); + const serverRequestedGet = statusCode === 303 && updatedOptions.method !== 'GET' && updatedOptions.method !== 'HEAD'; + const canRewrite = statusCode !== 307 && statusCode !== 308; + const userRequestedGet = updatedOptions.methodRewriting && canRewrite; + if (serverRequestedGet || userRequestedGet) { + updatedOptions.method = 'GET'; + updatedOptions.body = undefined; + updatedOptions.json = undefined; + updatedOptions.form = undefined; + delete updatedOptions.headers['content-length']; + } + try { + // We need this in order to support UTF-8 + const redirectBuffer = node_buffer.Buffer.from(response.headers.location, 'binary').toString(); + const redirectUrl = new urlLib.URL(redirectBuffer, url); + if (!isUnixSocketURL(url) && isUnixSocketURL(redirectUrl)) { + this._beforeError(new RequestError$1('Cannot redirect to UNIX socket', {}, this)); + return; + } + // Redirecting to a different site, clear sensitive data. + if (redirectUrl.hostname !== url.hostname || redirectUrl.port !== url.port) { + if ('host' in updatedOptions.headers) { + delete updatedOptions.headers.host; + } + if ('cookie' in updatedOptions.headers) { + delete updatedOptions.headers.cookie; + } + if ('authorization' in updatedOptions.headers) { + delete updatedOptions.headers.authorization; + } + if (updatedOptions.username || updatedOptions.password) { + updatedOptions.username = ''; + updatedOptions.password = ''; + } + } + else { + redirectUrl.username = updatedOptions.username; + redirectUrl.password = updatedOptions.password; + } + this.redirectUrls.push(redirectUrl); + updatedOptions.prefixUrl = ''; + updatedOptions.url = redirectUrl; + for (const hook of updatedOptions.hooks.beforeRedirect) { + // eslint-disable-next-line no-await-in-loop + await hook(updatedOptions, typedResponse); + } + this.emit('redirect', updatedOptions, typedResponse); + this.options = updatedOptions; + await this._makeRequest(); + } + catch (error) { + this._beforeError(error); + return; + } + return; + } + // `HTTPError`s always have `error.response.body` defined. + // Therefore we cannot retry if `options.throwHttpErrors` is false. + // On the last retry, if `options.throwHttpErrors` is false, we would need to return the body, + // but that wouldn't be possible since the body would be already read in `error.response.body`. + if (options.isStream && options.throwHttpErrors && !isResponseOk(typedResponse)) { + this._beforeError(new HTTPError(typedResponse)); + return; + } + response.on('readable', () => { + if (this._triggerRead) { + this._read(); + } + }); + this.on('resume', () => { + response.resume(); + }); + this.on('pause', () => { + response.pause(); + }); + response.once('end', () => { + this.push(null); + }); + if (this._noPipe) { + const success = await this._setRawBody(); + if (success) { + this.emit('response', response); + } + return; + } + this.emit('response', response); + for (const destination of this._pipedServerResponses) { + if (destination.headersSent) { + continue; + } + // eslint-disable-next-line guard-for-in + for (const key in response.headers) { + const isAllowed = options.decompress ? key !== 'content-encoding' : true; + const value = response.headers[key]; + if (isAllowed) { + destination.setHeader(key, value); + } + } + destination.statusCode = statusCode; + } + } + async _setRawBody(from = this) { + if (from.readableEnded) { + return false; + } + try { + // Errors are emitted via the `error` event + const rawBody = await getBuffer(from); + // On retry Request is destroyed with no error, therefore the above will successfully resolve. + // So in order to check if this was really successfull, we need to check if it has been properly ended. + if (!this.isAborted) { + this.response.rawBody = rawBody; + return true; + } + } + catch { } + return false; + } + async _onResponse(response) { + try { + await this._onResponseBase(response); + } + catch (error) { + /* istanbul ignore next: better safe than sorry */ + this._beforeError(error); + } + } + _onRequest(request) { + const { options } = this; + const { timeout, url } = options; + timer$1(request); + if (this.options.http2) { + // Unset stream timeout, as the `timeout` option was used only for connection timeout. + request.setTimeout(0); + } + this._cancelTimeouts = timedOut(request, timeout, url); + const responseEventName = options.cache ? 'cacheableResponse' : 'response'; + request.once(responseEventName, (response) => { + void this._onResponse(response); + }); + request.once('error', (error) => { + this._aborted = true; + // Force clean-up, because some packages (e.g. nock) don't do this. + request.destroy(); + error = error instanceof TimeoutError ? new TimeoutError$1(error, this.timings, this) : new RequestError$1(error.message, error, this); + this._beforeError(error); + }); + this._unproxyEvents = proxyEvents$2(request, this, proxiedRequestEvents$1); + this._request = request; + this.emit('uploadProgress', this.uploadProgress); + this._sendBody(); + this.emit('request', request); + } + async _asyncWrite(chunk) { + return new Promise((resolve, reject) => { + super.write(chunk, error => { + if (error) { + reject(error); + return; + } + resolve(); + }); + }); + } + _sendBody() { + // Send body + const { body } = this.options; + const currentRequest = this.redirectUrls.length === 0 ? this : this._request ?? this; + if (is$5.nodeStream(body)) { + body.pipe(currentRequest); + } + else if (is$5.generator(body) || is$5.asyncGenerator(body)) { + (async () => { + try { + for await (const chunk of body) { + await this._asyncWrite(chunk); + } + super.end(); + } + catch (error) { + this._beforeError(error); + } + })(); + } + else if (!is$5.undefined(body)) { + this._writeRequest(body, undefined, () => { }); + currentRequest.end(); + } + else if (this._cannotHaveBody || this._noPipe) { + currentRequest.end(); + } + } + _prepareCache(cache) { + if (!cacheableStore.has(cache)) { + const cacheableRequest = new CacheableRequest$1(((requestOptions, handler) => { + const result = requestOptions._request(requestOptions, handler); + // TODO: remove this when `cacheable-request` supports async request functions. + if (is$5.promise(result)) { + // We only need to implement the error handler in order to support HTTP2 caching. + // The result will be a promise anyway. + // @ts-expect-error ignore + // eslint-disable-next-line @typescript-eslint/promise-function-async + result.once = (event, handler) => { + if (event === 'error') { + (async () => { + try { + await result; + } + catch (error) { + handler(error); + } + })(); + } + else if (event === 'abort') { + // The empty catch is needed here in case when + // it rejects before it's `await`ed in `_makeRequest`. + (async () => { + try { + const request = (await result); + request.once('abort', handler); + } + catch { } + })(); + } + else { + /* istanbul ignore next: safety check */ + throw new Error(`Unknown HTTP2 promise event: ${event}`); + } + return result; + }; + } + return result; + }), cache); + cacheableStore.set(cache, cacheableRequest.request()); + } + } + async _createCacheableRequest(url, options) { + return new Promise((resolve, reject) => { + // TODO: Remove `utils/url-to-options.ts` when `cacheable-request` is fixed + Object.assign(options, urlToOptions$1(url)); + let request; + // TODO: Fix `cacheable-response`. This is ugly. + const cacheRequest = cacheableStore.get(options.cache)(options, async (response) => { + response._readableState.autoDestroy = false; + if (request) { + const fix = () => { + if (response.req) { + response.complete = response.req.res.complete; + } + }; + response.prependOnceListener('end', fix); + fix(); + (await request).emit('cacheableResponse', response); + } + resolve(response); + }); + cacheRequest.once('error', reject); + cacheRequest.once('request', async (requestOrPromise) => { + request = requestOrPromise; + resolve(request); + }); + }); + } + async _makeRequest() { + const { options } = this; + const { headers, username, password } = options; + const cookieJar = options.cookieJar; + for (const key in headers) { + if (is$5.undefined(headers[key])) { + // eslint-disable-next-line @typescript-eslint/no-dynamic-delete + delete headers[key]; + } + else if (is$5.null_(headers[key])) { + throw new TypeError(`Use \`undefined\` instead of \`null\` to delete the \`${key}\` header`); + } + } + if (options.decompress && is$5.undefined(headers['accept-encoding'])) { + headers['accept-encoding'] = supportsBrotli ? 'gzip, deflate, br' : 'gzip, deflate'; + } + if (username || password) { + const credentials = node_buffer.Buffer.from(`${username}:${password}`).toString('base64'); + headers.authorization = `Basic ${credentials}`; + } + // Set cookies + if (cookieJar) { + const cookieString = await cookieJar.getCookieString(options.url.toString()); + if (is$5.nonEmptyString(cookieString)) { + headers.cookie = cookieString; + } + } + // Reset `prefixUrl` + options.prefixUrl = ''; + let request; + for (const hook of options.hooks.beforeRequest) { + // eslint-disable-next-line no-await-in-loop + const result = await hook(options); + if (!is$5.undefined(result)) { + // @ts-expect-error Skip the type mismatch to support abstract responses + request = () => result; + break; + } + } + if (!request) { + request = options.getRequestFunction(); + } + const url = options.url; + this._requestOptions = options.createNativeRequestOptions(); + if (options.cache) { + this._requestOptions._request = request; + this._requestOptions.cache = options.cache; + this._requestOptions.body = options.body; + this._prepareCache(options.cache); + } + // Cache support + const fn = options.cache ? this._createCacheableRequest : request; + try { + // We can't do `await fn(...)`, + // because stream `error` event can be emitted before `Promise.resolve()`. + let requestOrResponse = fn(url, this._requestOptions); + if (is$5.promise(requestOrResponse)) { + requestOrResponse = await requestOrResponse; + } + // Fallback + if (is$5.undefined(requestOrResponse)) { + requestOrResponse = options.getFallbackRequestFunction()(url, this._requestOptions); + if (is$5.promise(requestOrResponse)) { + requestOrResponse = await requestOrResponse; + } + } + if (isClientRequest(requestOrResponse)) { + this._onRequest(requestOrResponse); + } + else if (this.writable) { + this.once('finish', () => { + void this._onResponse(requestOrResponse); + }); + this._sendBody(); + } + else { + void this._onResponse(requestOrResponse); + } + } + catch (error) { + if (error instanceof CacheError) { + throw new CacheError$1(error, this); + } + throw error; + } + } + async _error(error) { + try { + if (error instanceof HTTPError && !this.options.throwHttpErrors) { + // This branch can be reached only when using the Promise API + // Skip calling the hooks on purpose. + // See https://github.com/sindresorhus/got/issues/2103 + } + else { + for (const hook of this.options.hooks.beforeError) { + // eslint-disable-next-line no-await-in-loop + error = await hook(error); + } + } + } + catch (error_) { + error = new RequestError$1(error_.message, error_, this); + } + this.destroy(error); + } + _writeRequest(chunk, encoding, callback) { + if (!this._request || this._request.destroyed) { + // Probably the `ClientRequest` instance will throw + return; + } + this._request.write(chunk, encoding, (error) => { + // The `!destroyed` check is required to prevent `uploadProgress` being emitted after the stream was destroyed + if (!error && !this._request.destroyed) { + this._uploadedSize += node_buffer.Buffer.byteLength(chunk, encoding); + const progress = this.uploadProgress; + if (progress.percent < 1) { + this.emit('uploadProgress', progress); + } + } + callback(error); + }); + } + /** + The remote IP address. + */ + get ip() { + return this.socket?.remoteAddress; + } + /** + Indicates whether the request has been aborted or not. + */ + get isAborted() { + return this._aborted; + } + get socket() { + return this._request?.socket ?? undefined; + } + /** + Progress event for downloading (receiving a response). + */ + get downloadProgress() { + let percent; + if (this._responseSize) { + percent = this._downloadedSize / this._responseSize; + } + else if (this._responseSize === this._downloadedSize) { + percent = 1; + } + else { + percent = 0; + } + return { + percent, + transferred: this._downloadedSize, + total: this._responseSize, + }; + } + /** + Progress event for uploading (sending a request). + */ + get uploadProgress() { + let percent; + if (this._bodySize) { + percent = this._uploadedSize / this._bodySize; + } + else if (this._bodySize === this._uploadedSize) { + percent = 1; + } + else { + percent = 0; + } + return { + percent, + transferred: this._uploadedSize, + total: this._bodySize, + }; + } + /** + The object contains the following properties: + + - `start` - Time when the request started. + - `socket` - Time when a socket was assigned to the request. + - `lookup` - Time when the DNS lookup finished. + - `connect` - Time when the socket successfully connected. + - `secureConnect` - Time when the socket securely connected. + - `upload` - Time when the request finished uploading. + - `response` - Time when the request fired `response` event. + - `end` - Time when the response fired `end` event. + - `error` - Time when the request fired `error` event. + - `abort` - Time when the request fired `abort` event. + - `phases` + - `wait` - `timings.socket - timings.start` + - `dns` - `timings.lookup - timings.socket` + - `tcp` - `timings.connect - timings.lookup` + - `tls` - `timings.secureConnect - timings.connect` + - `request` - `timings.upload - (timings.secureConnect || timings.connect)` + - `firstByte` - `timings.response - timings.upload` + - `download` - `timings.end - timings.response` + - `total` - `(timings.end || timings.error || timings.abort) - timings.start` + + If something has not been measured yet, it will be `undefined`. + + __Note__: The time is a `number` representing the milliseconds elapsed since the UNIX epoch. + */ + get timings() { + return this._request?.timings; + } + /** + Whether the response was retrieved from the cache. + */ + get isFromCache() { + return this._isFromCache; + } + get reusedSocket() { + return this._request?.reusedSocket; + } +}; + +/** +An error to be thrown when the request is aborted with `.cancel()`. +*/ +class CancelError extends RequestError$1 { + constructor(request) { + super('Promise was canceled', {}, request); + this.name = 'CancelError'; + this.code = 'ERR_CANCELED'; + } + /** + Whether the promise is canceled. + */ + get isCanceled() { + return true; + } +} + +const proxiedRequestEvents = [ + 'request', + 'response', + 'redirect', + 'uploadProgress', + 'downloadProgress', +]; +function asPromise(firstRequest) { + let globalRequest; + let globalResponse; + let normalizedOptions; + const emitter = new EventEmitter$3.EventEmitter(); + const promise = new PCancelable((resolve, reject, onCancel) => { + onCancel(() => { + globalRequest.destroy(); + }); + onCancel.shouldReject = false; + onCancel(() => { + reject(new CancelError(globalRequest)); + }); + const makeRequest = (retryCount) => { + // Errors when a new request is made after the promise settles. + // Used to detect a race condition. + // See https://github.com/sindresorhus/got/issues/1489 + onCancel(() => { }); + const request = firstRequest ?? new Request$3(undefined, undefined, normalizedOptions); + request.retryCount = retryCount; + request._noPipe = true; + globalRequest = request; + request.once('response', async (response) => { + // Parse body + const contentEncoding = (response.headers['content-encoding'] ?? '').toLowerCase(); + const isCompressed = contentEncoding === 'gzip' || contentEncoding === 'deflate' || contentEncoding === 'br'; + const { options } = request; + if (isCompressed && !options.decompress) { + response.body = response.rawBody; + } + else { + try { + response.body = parseBody$1(response, options.responseType, options.parseJson, options.encoding); + } + catch (error) { + // Fall back to `utf8` + response.body = response.rawBody.toString(); + if (isResponseOk(response)) { + request._beforeError(error); + return; + } + } + } + try { + const hooks = options.hooks.afterResponse; + for (const [index, hook] of hooks.entries()) { + // @ts-expect-error TS doesn't notice that CancelableRequest is a Promise + // eslint-disable-next-line no-await-in-loop + response = await hook(response, async (updatedOptions) => { + options.merge(updatedOptions); + options.prefixUrl = ''; + if (updatedOptions.url) { + options.url = updatedOptions.url; + } + // Remove any further hooks for that request, because we'll call them anyway. + // The loop continues. We don't want duplicates (asPromise recursion). + options.hooks.afterResponse = options.hooks.afterResponse.slice(0, index); + throw new RetryError(request); + }); + if (!(is$5.object(response) && is$5.number(response.statusCode) && !is$5.nullOrUndefined(response.body))) { + throw new TypeError('The `afterResponse` hook returned an invalid value'); + } + } + } + catch (error) { + request._beforeError(error); + return; + } + globalResponse = response; + if (!isResponseOk(response)) { + request._beforeError(new HTTPError(response)); + return; + } + request.destroy(); + resolve(request.options.resolveBodyOnly ? response.body : response); + }); + const onError = (error) => { + if (promise.isCanceled) { + return; + } + const { options } = request; + if (error instanceof HTTPError && !options.throwHttpErrors) { + const { response } = error; + request.destroy(); + resolve(request.options.resolveBodyOnly ? response.body : response); + return; + } + reject(error); + }; + request.once('error', onError); + const previousBody = request.options?.body; + request.once('retry', (newRetryCount, error) => { + firstRequest = undefined; + const newBody = request.options.body; + if (previousBody === newBody && is$5.nodeStream(newBody)) { + error.message = 'Cannot retry with consumed body stream'; + onError(error); + return; + } + // This is needed! We need to reuse `request.options` because they can get modified! + // For example, by calling `promise.json()`. + normalizedOptions = request.options; + makeRequest(newRetryCount); + }); + proxyEvents$2(request, emitter, proxiedRequestEvents); + if (is$5.undefined(firstRequest)) { + void request.flush(); + } + }; + makeRequest(0); + }); + promise.on = (event, fn) => { + emitter.on(event, fn); + return promise; + }; + promise.off = (event, fn) => { + emitter.off(event, fn); + return promise; + }; + const shortcut = (responseType) => { + const newPromise = (async () => { + // Wait until downloading has ended + await promise; + const { options } = globalResponse.request; + return parseBody$1(globalResponse, responseType, options.parseJson, options.encoding); + })(); + // eslint-disable-next-line @typescript-eslint/no-floating-promises + Object.defineProperties(newPromise, Object.getOwnPropertyDescriptors(promise)); + return newPromise; + }; + promise.json = () => { + if (globalRequest.options) { + const { headers } = globalRequest.options; + if (!globalRequest.writableFinished && !('accept' in headers)) { + headers.accept = 'application/json'; + } + } + return shortcut('json'); + }; + promise.buffer = () => shortcut('buffer'); + promise.text = () => shortcut('text'); + return promise; +} + +// The `delay` package weighs 10KB (!) +const delay$1 = async (ms) => new Promise(resolve => { + setTimeout(resolve, ms); +}); +const isGotInstance = (value) => is$5.function_(value); +const aliases$2 = [ + 'get', + 'post', + 'put', + 'patch', + 'head', + 'delete', +]; +const create$3 = (defaults) => { + defaults = { + options: new Options$2(undefined, undefined, defaults.options), + handlers: [...defaults.handlers], + mutableDefaults: defaults.mutableDefaults, + }; + Object.defineProperty(defaults, 'mutableDefaults', { + enumerable: true, + configurable: false, + writable: false, + }); + // Got interface + const got = ((url, options, defaultOptions = defaults.options) => { + const request = new Request$3(url, options, defaultOptions); + let promise; + const lastHandler = (normalized) => { + // Note: `options` is `undefined` when `new Options(...)` fails + request.options = normalized; + request._noPipe = !normalized.isStream; + void request.flush(); + if (normalized.isStream) { + return request; + } + if (!promise) { + promise = asPromise(request); + } + return promise; + }; + let iteration = 0; + const iterateHandlers = (newOptions) => { + const handler = defaults.handlers[iteration++] ?? lastHandler; + const result = handler(newOptions, iterateHandlers); + if (is$5.promise(result) && !request.options.isStream) { + if (!promise) { + promise = asPromise(request); + } + if (result !== promise) { + const descriptors = Object.getOwnPropertyDescriptors(promise); + for (const key in descriptors) { + if (key in result) { + // eslint-disable-next-line @typescript-eslint/no-dynamic-delete + delete descriptors[key]; + } + } + // eslint-disable-next-line @typescript-eslint/no-floating-promises + Object.defineProperties(result, descriptors); + result.cancel = promise.cancel; + } + } + return result; + }; + return iterateHandlers(request.options); + }); + got.extend = (...instancesOrOptions) => { + const options = new Options$2(undefined, undefined, defaults.options); + const handlers = [...defaults.handlers]; + let mutableDefaults; + for (const value of instancesOrOptions) { + if (isGotInstance(value)) { + options.merge(value.defaults.options); + handlers.push(...value.defaults.handlers); + mutableDefaults = value.defaults.mutableDefaults; + } + else { + options.merge(value); + if (value.handlers) { + handlers.push(...value.handlers); + } + mutableDefaults = value.mutableDefaults; + } + } + return create$3({ + options, + handlers, + mutableDefaults: Boolean(mutableDefaults), + }); + }; + // Pagination + const paginateEach = (async function* (url, options) { + let normalizedOptions = new Options$2(url, options, defaults.options); + normalizedOptions.resolveBodyOnly = false; + const { pagination } = normalizedOptions; + assert$2.function_(pagination.transform); + assert$2.function_(pagination.shouldContinue); + assert$2.function_(pagination.filter); + assert$2.function_(pagination.paginate); + assert$2.number(pagination.countLimit); + assert$2.number(pagination.requestLimit); + assert$2.number(pagination.backoff); + const allItems = []; + let { countLimit } = pagination; + let numberOfRequests = 0; + while (numberOfRequests < pagination.requestLimit) { + if (numberOfRequests !== 0) { + // eslint-disable-next-line no-await-in-loop + await delay$1(pagination.backoff); + } + // eslint-disable-next-line no-await-in-loop + const response = (await got(undefined, undefined, normalizedOptions)); + // eslint-disable-next-line no-await-in-loop + const parsed = await pagination.transform(response); + const currentItems = []; + assert$2.array(parsed); + for (const item of parsed) { + if (pagination.filter({ item, currentItems, allItems })) { + if (!pagination.shouldContinue({ item, currentItems, allItems })) { + return; + } + yield item; + if (pagination.stackAllItems) { + allItems.push(item); + } + currentItems.push(item); + if (--countLimit <= 0) { + return; + } + } + } + const optionsToMerge = pagination.paginate({ + response, + currentItems, + allItems, + }); + if (optionsToMerge === false) { + return; + } + if (optionsToMerge === response.request.options) { + normalizedOptions = response.request.options; + } + else { + normalizedOptions.merge(optionsToMerge); + assert$2.any([is$5.urlInstance, is$5.undefined], optionsToMerge.url); + if (optionsToMerge.url !== undefined) { + normalizedOptions.prefixUrl = ''; + normalizedOptions.url = optionsToMerge.url; + } + } + numberOfRequests++; + } + }); + got.paginate = paginateEach; + got.paginate.all = (async (url, options) => { + const results = []; + for await (const item of paginateEach(url, options)) { + results.push(item); + } + return results; + }); + // For those who like very descriptive names + got.paginate.each = paginateEach; + // Stream API + got.stream = ((url, options) => got(url, { ...options, isStream: true })); + // Shortcuts + for (const method of aliases$2) { + got[method] = ((url, options) => got(url, { ...options, method })); + got.stream[method] = ((url, options) => got(url, { ...options, method, isStream: true })); + } + if (!defaults.mutableDefaults) { + Object.freeze(defaults.handlers); + defaults.options.freeze(); + } + Object.defineProperty(got, 'defaults', { + value: defaults, + writable: false, + configurable: false, + enumerable: true, + }); + return got; +}; +var create$4 = create$3; + +const defaults$c = { + options: new Options$2(), + handlers: [], + mutableDefaults: false, +}; +const got = create$4(defaults$c); +var got$1 = got; + +var utils$9 = {}; + +var ini$3 = {}; + +ini$3.parse = ini$3.decode = decode$1; + +ini$3.stringify = ini$3.encode = encode$1; + +ini$3.safe = safe$1; +ini$3.unsafe = unsafe$1; + +var eol$1 = typeof process !== 'undefined' && + process.platform === 'win32' ? '\r\n' : '\n'; + +function encode$1 (obj, opt) { + var children = []; + var out = ''; + + if (typeof opt === 'string') { + opt = { + section: opt, + whitespace: false, + }; + } else { + opt = opt || {}; + opt.whitespace = opt.whitespace === true; + } + + var separator = opt.whitespace ? ' = ' : '='; + + Object.keys(obj).forEach(function (k, _, __) { + var val = obj[k]; + if (val && Array.isArray(val)) { + val.forEach(function (item) { + out += safe$1(k + '[]') + separator + safe$1(item) + '\n'; + }); + } else if (val && typeof val === 'object') + children.push(k); + else + out += safe$1(k) + separator + safe$1(val) + eol$1; + }); + + if (opt.section && out.length) + out = '[' + safe$1(opt.section) + ']' + eol$1 + out; + + children.forEach(function (k, _, __) { + var nk = dotSplit$1(k).join('\\.'); + var section = (opt.section ? opt.section + '.' : '') + nk; + var child = encode$1(obj[k], { + section: section, + whitespace: opt.whitespace, + }); + if (out.length && child.length) + out += eol$1; + + out += child; + }); + + return out +} + +function dotSplit$1 (str) { + return str.replace(/\1/g, '\u0002LITERAL\\1LITERAL\u0002') + .replace(/\\\./g, '\u0001') + .split(/\./).map(function (part) { + return part.replace(/\1/g, '\\.') + .replace(/\2LITERAL\\1LITERAL\2/g, '\u0001') + }) +} + +function decode$1 (str) { + var out = {}; + var p = out; + var section = null; + // section |key = value + var re = /^\[([^\]]*)\]$|^([^=]+)(=(.*))?$/i; + var lines = str.split(/[\r\n]+/g); + + lines.forEach(function (line, _, __) { + if (!line || line.match(/^\s*[;#]/)) + return + var match = line.match(re); + if (!match) + return + if (match[1] !== undefined) { + section = unsafe$1(match[1]); + if (section === '__proto__') { + // not allowed + // keep parsing the section, but don't attach it. + p = {}; + return + } + p = out[section] = out[section] || {}; + return + } + var key = unsafe$1(match[2]); + if (key === '__proto__') + return + var value = match[3] ? unsafe$1(match[4]) : true; + switch (value) { + case 'true': + case 'false': + case 'null': value = JSON.parse(value); + } + + // Convert keys with '[]' suffix to an array + if (key.length > 2 && key.slice(-2) === '[]') { + key = key.substring(0, key.length - 2); + if (key === '__proto__') + return + if (!p[key]) + p[key] = []; + else if (!Array.isArray(p[key])) + p[key] = [p[key]]; + } + + // safeguard against resetting a previously defined + // array by accidentally forgetting the brackets + if (Array.isArray(p[key])) + p[key].push(value); + else + p[key] = value; + }); + + // {a:{y:1},"a.b":{x:2}} --> {a:{y:1,b:{x:2}}} + // use a filter to return the keys that have to be deleted. + Object.keys(out).filter(function (k, _, __) { + if (!out[k] || + typeof out[k] !== 'object' || + Array.isArray(out[k])) + return false + + // see if the parent section is also an object. + // if so, add it to that, and mark this one for deletion + var parts = dotSplit$1(k); + var p = out; + var l = parts.pop(); + var nl = l.replace(/\\\./g, '.'); + parts.forEach(function (part, _, __) { + if (part === '__proto__') + return + if (!p[part] || typeof p[part] !== 'object') + p[part] = {}; + p = p[part]; + }); + if (p === out && nl === l) + return false + + p[nl] = out[k]; + return true + }).forEach(function (del, _, __) { + delete out[del]; + }); + + return out +} + +function isQuoted$1 (val) { + return (val.charAt(0) === '"' && val.slice(-1) === '"') || + (val.charAt(0) === "'" && val.slice(-1) === "'") +} + +function safe$1 (val) { + return (typeof val !== 'string' || + val.match(/[=\r\n]/) || + val.match(/^\[/) || + (val.length > 1 && + isQuoted$1(val)) || + val !== val.trim()) + ? JSON.stringify(val) + : val.replace(/;/g, '\\;').replace(/#/g, '\\#') +} + +function unsafe$1 (val, doUnesc) { + val = (val || '').trim(); + if (isQuoted$1(val)) { + // remove the single quotes before calling JSON.parse + if (val.charAt(0) === "'") + val = val.substr(1, val.length - 2); + + try { + val = JSON.parse(val); + } catch (_) {} + } else { + // walk the val to find the first not-escaped ; character + var esc = false; + var unesc = ''; + for (var i = 0, l = val.length; i < l; i++) { + var c = val.charAt(i); + if (esc) { + if ('\\;#'.indexOf(c) !== -1) + unesc += c; + else + unesc += '\\' + c; + + esc = false; + } else if (';#'.indexOf(c) !== -1) + break + else if (c === '\\') + esc = true; + else + unesc += c; + } + if (esc) + unesc += '\\'; + + return unesc.trim() + } + return val +} + +var singleComment = 1; +var multiComment = 2; + +function stripWithoutWhitespace() { + return ''; +} + +function stripWithWhitespace(str, start, end) { + return str.slice(start, end).replace(/\S/g, ' '); +} + +var stripJsonComments$1 = function (str, opts) { + opts = opts || {}; + + var currentChar; + var nextChar; + var insideString = false; + var insideComment = false; + var offset = 0; + var ret = ''; + var strip = opts.whitespace === false ? stripWithoutWhitespace : stripWithWhitespace; + + for (var i = 0; i < str.length; i++) { + currentChar = str[i]; + nextChar = str[i + 1]; + + if (!insideComment && currentChar === '"') { + var escaped = str[i - 1] === '\\' && str[i - 2] !== '\\'; + if (!escaped) { + insideString = !insideString; + } + } + + if (insideString) { + continue; + } + + if (!insideComment && currentChar + nextChar === '//') { + ret += str.slice(offset, i); + offset = i; + insideComment = singleComment; + i++; + } else if (insideComment === singleComment && currentChar + nextChar === '\r\n') { + i++; + insideComment = false; + ret += strip(str, offset, i); + offset = i; + continue; + } else if (insideComment === singleComment && currentChar === '\n') { + insideComment = false; + ret += strip(str, offset, i); + offset = i; + } else if (!insideComment && currentChar + nextChar === '/*') { + ret += str.slice(offset, i); + offset = i; + insideComment = multiComment; + i++; + continue; + } else if (insideComment === multiComment && currentChar + nextChar === '*/') { + i++; + insideComment = false; + ret += strip(str, offset, i + 1); + offset = i + 1; + continue; + } + } + + return ret + (insideComment ? strip(str.substr(offset)) : str.substr(offset)); +}; + +var fs$d = require$$0$8; +var ini$2 = ini$3; +var path$a = require$$0$b; +var stripJsonComments = stripJsonComments$1; + +var parse$e = utils$9.parse = function (content) { + + //if it ends in .json or starts with { then it must be json. + //must be done this way, because ini accepts everything. + //can't just try and parse it and let it throw if it's not ini. + //everything is ini. even json with a syntax error. + + if(/^\s*{/.test(content)) + return JSON.parse(stripJsonComments(content)) + return ini$2.parse(content) + +}; + +var file$1 = utils$9.file = function () { + var args = [].slice.call(arguments).filter(function (arg) { return arg != null }); + + //path.join breaks if it's a not a string, so just skip this. + for(var i in args) + if('string' !== typeof args[i]) + return + + var file = path$a.join.apply(null, args); + try { + return fs$d.readFileSync(file,'utf-8') + } catch (err) { + return + } +}; + +utils$9.json = function () { + var content = file$1.apply(null, arguments); + return content ? parse$e(content) : null +}; + +utils$9.env = function (prefix, env) { + env = env || process.env; + var obj = {}; + var l = prefix.length; + for(var k in env) { + if(k.toLowerCase().indexOf(prefix.toLowerCase()) === 0) { + + var keypath = k.substring(l).split('__'); + + // Trim empty strings from keypath array + var _emptyStringIndex; + while ((_emptyStringIndex=keypath.indexOf('')) > -1) { + keypath.splice(_emptyStringIndex, 1); + } + + var cursor = obj; + keypath.forEach(function _buildSubObj(_subkey,i){ + + // (check for _subkey first so we ignore empty strings) + // (check for cursor to avoid assignment to primitive objects) + if (!_subkey || typeof cursor !== 'object') + return + + // If this is the last key, just stuff the value in there + // Assigns actual value from env variable to final key + // (unless it's just an empty string- in that case use the last valid key) + if (i === keypath.length-1) + cursor[_subkey] = env[k]; + + + // Build sub-object if nothing already exists at the keypath + if (cursor[_subkey] === undefined) + cursor[_subkey] = {}; + + // Increment cursor used to track the object at the current depth + cursor = cursor[_subkey]; + + }); + + } + + } + + return obj +}; + +utils$9.find = function () { + var rel = path$a.join.apply(null, [].slice.call(arguments)); + + function find(start, rel) { + var file = path$a.join(start, rel); + try { + fs$d.statSync(file); + return file + } catch (err) { + if(path$a.dirname(start) !== start) // root + return find(path$a.dirname(start), rel) + } + } + return find(process.cwd(), rel) +}; + +var deepExtend$2 = {exports: {}}; + +/*! + * @description Recursive object extending + * @author Viacheslav Lotsmanov + * @license MIT + * + * The MIT License (MIT) + * + * Copyright (c) 2013-2018 Viacheslav Lotsmanov + * + * 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 isSpecificValue(val) { + return ( + val instanceof Buffer + || val instanceof Date + || val instanceof RegExp + ) ? true : false; +} + +function cloneSpecificValue(val) { + if (val instanceof Buffer) { + var x = Buffer.alloc + ? Buffer.alloc(val.length) + : new Buffer(val.length); + val.copy(x); + return x; + } else if (val instanceof Date) { + return new Date(val.getTime()); + } else if (val instanceof RegExp) { + return new RegExp(val); + } else { + throw new Error('Unexpected situation'); + } +} + +/** + * Recursive cloning array. + */ +function deepCloneArray(arr) { + var clone = []; + arr.forEach(function (item, index) { + if (typeof item === 'object' && item !== null) { + if (Array.isArray(item)) { + clone[index] = deepCloneArray(item); + } else if (isSpecificValue(item)) { + clone[index] = cloneSpecificValue(item); + } else { + clone[index] = deepExtend$1({}, item); + } + } else { + clone[index] = item; + } + }); + return clone; +} + +function safeGetProperty(object, property) { + return property === '__proto__' ? undefined : object[property]; +} + +/** + * Extening object that entered in first argument. + * + * Returns extended object or false if have no target object or incorrect type. + * + * If you wish to clone source object (without modify it), just use empty new + * object as first argument, like this: + * deepExtend({}, yourObj_1, [yourObj_N]); + */ +var deepExtend$1 = deepExtend$2.exports = function (/*obj_1, [obj_2], [obj_N]*/) { + if (arguments.length < 1 || typeof arguments[0] !== 'object') { + return false; + } + + if (arguments.length < 2) { + return arguments[0]; + } + + var target = arguments[0]; + + // convert arguments to array and cut off target object + var args = Array.prototype.slice.call(arguments, 1); + + var val, src; + + args.forEach(function (obj) { + // skip argument if isn't an object, is null, or is an array + if (typeof obj !== 'object' || obj === null || Array.isArray(obj)) { + return; + } + + Object.keys(obj).forEach(function (key) { + src = safeGetProperty(target, key); // source value + val = safeGetProperty(obj, key); // new value + + // recursion prevention + if (val === target) { + return; + + /** + * if new value isn't object then just overwrite by new value + * instead of extending. + */ + } else if (typeof val !== 'object' || val === null) { + target[key] = val; + return; + + // just clone arrays (and recursive clone objects inside) + } else if (Array.isArray(val)) { + target[key] = deepCloneArray(val); + return; + + // custom cloning and overwrite for specific objects + } else if (isSpecificValue(val)) { + target[key] = cloneSpecificValue(val); + return; + + // overwrite by new value if source isn't object or array + } else if (typeof src !== 'object' || src === null || Array.isArray(src)) { + target[key] = deepExtend$1({}, val); + return; + + // source value and new value is objects both, extending... + } else { + target[key] = deepExtend$1(src, val); + return; + } + }); + }); + + return target; +}; + +var deepExtendExports = deepExtend$2.exports; + +var minimist; +var hasRequiredMinimist; + +function requireMinimist () { + if (hasRequiredMinimist) return minimist; + hasRequiredMinimist = 1; + + function hasKey(obj, keys) { + var o = obj; + keys.slice(0, -1).forEach(function (key) { + o = o[key] || {}; + }); + + var key = keys[keys.length - 1]; + return key in o; + } + + function isNumber(x) { + if (typeof x === 'number') { return true; } + if ((/^0x[0-9a-f]+$/i).test(x)) { return true; } + return (/^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/).test(x); + } + + function isConstructorOrProto(obj, key) { + return (key === 'constructor' && typeof obj[key] === 'function') || key === '__proto__'; + } + + minimist = function (args, opts) { + if (!opts) { opts = {}; } + + var flags = { + bools: {}, + strings: {}, + unknownFn: null, + }; + + if (typeof opts.unknown === 'function') { + flags.unknownFn = opts.unknown; + } + + if (typeof opts.boolean === 'boolean' && opts.boolean) { + flags.allBools = true; + } else { + [].concat(opts.boolean).filter(Boolean).forEach(function (key) { + flags.bools[key] = true; + }); + } + + var aliases = {}; + + function aliasIsBoolean(key) { + return aliases[key].some(function (x) { + return flags.bools[x]; + }); + } + + Object.keys(opts.alias || {}).forEach(function (key) { + aliases[key] = [].concat(opts.alias[key]); + aliases[key].forEach(function (x) { + aliases[x] = [key].concat(aliases[key].filter(function (y) { + return x !== y; + })); + }); + }); + + [].concat(opts.string).filter(Boolean).forEach(function (key) { + flags.strings[key] = true; + if (aliases[key]) { + [].concat(aliases[key]).forEach(function (k) { + flags.strings[k] = true; + }); + } + }); + + var defaults = opts.default || {}; + + var argv = { _: [] }; + + function argDefined(key, arg) { + return (flags.allBools && (/^--[^=]+$/).test(arg)) + || flags.strings[key] + || flags.bools[key] + || aliases[key]; + } + + function setKey(obj, keys, value) { + var o = obj; + for (var i = 0; i < keys.length - 1; i++) { + var key = keys[i]; + if (isConstructorOrProto(o, key)) { return; } + if (o[key] === undefined) { o[key] = {}; } + if ( + o[key] === Object.prototype + || o[key] === Number.prototype + || o[key] === String.prototype + ) { + o[key] = {}; + } + if (o[key] === Array.prototype) { o[key] = []; } + o = o[key]; + } + + var lastKey = keys[keys.length - 1]; + if (isConstructorOrProto(o, lastKey)) { return; } + if ( + o === Object.prototype + || o === Number.prototype + || o === String.prototype + ) { + o = {}; + } + if (o === Array.prototype) { o = []; } + if (o[lastKey] === undefined || flags.bools[lastKey] || typeof o[lastKey] === 'boolean') { + o[lastKey] = value; + } else if (Array.isArray(o[lastKey])) { + o[lastKey].push(value); + } else { + o[lastKey] = [o[lastKey], value]; + } + } + + function setArg(key, val, arg) { + if (arg && flags.unknownFn && !argDefined(key, arg)) { + if (flags.unknownFn(arg) === false) { return; } + } + + var value = !flags.strings[key] && isNumber(val) + ? Number(val) + : val; + setKey(argv, key.split('.'), value); + + (aliases[key] || []).forEach(function (x) { + setKey(argv, x.split('.'), value); + }); + } + + Object.keys(flags.bools).forEach(function (key) { + setArg(key, defaults[key] === undefined ? false : defaults[key]); + }); + + var notFlags = []; + + if (args.indexOf('--') !== -1) { + notFlags = args.slice(args.indexOf('--') + 1); + args = args.slice(0, args.indexOf('--')); + } + + for (var i = 0; i < args.length; i++) { + var arg = args[i]; + var key; + var next; + + if ((/^--.+=/).test(arg)) { + // Using [\s\S] instead of . because js doesn't support the + // 'dotall' regex modifier. See: + // http://stackoverflow.com/a/1068308/13216 + var m = arg.match(/^--([^=]+)=([\s\S]*)$/); + key = m[1]; + var value = m[2]; + if (flags.bools[key]) { + value = value !== 'false'; + } + setArg(key, value, arg); + } else if ((/^--no-.+/).test(arg)) { + key = arg.match(/^--no-(.+)/)[1]; + setArg(key, false, arg); + } else if ((/^--.+/).test(arg)) { + key = arg.match(/^--(.+)/)[1]; + next = args[i + 1]; + if ( + next !== undefined + && !(/^(-|--)[^-]/).test(next) + && !flags.bools[key] + && !flags.allBools + && (aliases[key] ? !aliasIsBoolean(key) : true) + ) { + setArg(key, next, arg); + i += 1; + } else if ((/^(true|false)$/).test(next)) { + setArg(key, next === 'true', arg); + i += 1; + } else { + setArg(key, flags.strings[key] ? '' : true, arg); + } + } else if ((/^-[^-]+/).test(arg)) { + var letters = arg.slice(1, -1).split(''); + + var broken = false; + for (var j = 0; j < letters.length; j++) { + next = arg.slice(j + 2); + + if (next === '-') { + setArg(letters[j], next, arg); + continue; + } + + if ((/[A-Za-z]/).test(letters[j]) && next[0] === '=') { + setArg(letters[j], next.slice(1), arg); + broken = true; + break; + } + + if ( + (/[A-Za-z]/).test(letters[j]) + && (/-?\d+(\.\d*)?(e-?\d+)?$/).test(next) + ) { + setArg(letters[j], next, arg); + broken = true; + break; + } + + if (letters[j + 1] && letters[j + 1].match(/\W/)) { + setArg(letters[j], arg.slice(j + 2), arg); + broken = true; + break; + } else { + setArg(letters[j], flags.strings[letters[j]] ? '' : true, arg); + } + } + + key = arg.slice(-1)[0]; + if (!broken && key !== '-') { + if ( + args[i + 1] + && !(/^(-|--)[^-]/).test(args[i + 1]) + && !flags.bools[key] + && (aliases[key] ? !aliasIsBoolean(key) : true) + ) { + setArg(key, args[i + 1], arg); + i += 1; + } else if (args[i + 1] && (/^(true|false)$/).test(args[i + 1])) { + setArg(key, args[i + 1] === 'true', arg); + i += 1; + } else { + setArg(key, flags.strings[key] ? '' : true, arg); + } + } + } else { + if (!flags.unknownFn || flags.unknownFn(arg) !== false) { + argv._.push(flags.strings._ || !isNumber(arg) ? arg : Number(arg)); + } + if (opts.stopEarly) { + argv._.push.apply(argv._, args.slice(i + 1)); + break; + } + } + } + + Object.keys(defaults).forEach(function (k) { + if (!hasKey(argv, k.split('.'))) { + setKey(argv, k.split('.'), defaults[k]); + + (aliases[k] || []).forEach(function (x) { + setKey(argv, x.split('.'), defaults[k]); + }); + } + }); + + if (opts['--']) { + argv['--'] = notFlags.slice(); + } else { + notFlags.forEach(function (k) { + argv._.push(k); + }); + } + + return argv; + }; + return minimist; +} + +var cc = utils$9; +var join = require$$0$b.join; +var deepExtend = deepExtendExports; +var etc = '/etc'; +var win = process.platform === "win32"; +var home = win + ? process.env.USERPROFILE + : process.env.HOME; + +var rc = function (name, defaults, argv, parse) { + if('string' !== typeof name) + throw new Error('rc(name): name *must* be string') + if(!argv) + argv = requireMinimist()(process.argv.slice(2)); + defaults = ( + 'string' === typeof defaults + ? cc.json(defaults) : defaults + ) || {}; + + parse = parse || cc.parse; + + var env = cc.env(name + '_'); + + var configs = [defaults]; + var configFiles = []; + function addConfigFile (file) { + if (configFiles.indexOf(file) >= 0) return + var fileConfig = cc.file(file); + if (fileConfig) { + configs.push(parse(fileConfig)); + configFiles.push(file); + } + } + + // which files do we look at? + if (!win) + [join(etc, name, 'config'), + join(etc, name + 'rc')].forEach(addConfigFile); + if (home) + [join(home, '.config', name, 'config'), + join(home, '.config', name), + join(home, '.' + name, 'config'), + join(home, '.' + name + 'rc')].forEach(addConfigFile); + addConfigFile(cc.find('.'+name+'rc')); + if (env.config) addConfigFile(env.config); + if (argv.config) addConfigFile(argv.config); + + return deepExtend.apply(null, configs.concat([ + env, + argv, + configFiles.length ? {configs: configFiles, config: configFiles[configFiles.length - 1]} : undefined, + ])) +}; + +var rc$1 = /*@__PURE__*/getDefaultExportFromCjs(rc); + +function registryUrl$1(scope) { + const result = rc$1('npm', {registry: 'https://registry.npmjs.org/'}); + const url = result[`${scope}:registry`] || result.config_registry || result.registry; + return url.slice(-1) === '/' ? url : `${url}/`; +} + +var npmConf$1 = {exports: {}}; + +var dist$7 = {}; + +var caFile = {}; + +var constants = require$$0$c; + +var origCwd = process.cwd; +var cwd = null; + +var platform$1 = 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.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$1 === "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.O_WRONLY | constants.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.O_WRONLY | constants.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.hasOwnProperty("O_SYMLINK") && fs.futimes) { + fs.lutimes = function (path, at, mt, cb) { + fs.open(path, constants.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.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$1 = Stream$3.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$1.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$1.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$1 = clone$a; + +var getPrototypeOf$1 = Object.getPrototypeOf || function (obj) { + return obj.__proto__ +}; + +function clone$a (obj) { + if (obj === null || typeof obj !== 'object') + return obj + + if (obj instanceof Object) + var copy = { __proto__: getPrototypeOf$1(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$c = require$$0$8; +var polyfills = polyfills$1; +var legacy = legacyStreams; +var clone$9 = clone_1$1; + +var util$e = require$$0$9; + +/* 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$2 = noop$4; +if (util$e.debuglog) + debug$2 = util$e.debuglog('gfs4'); +else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) + debug$2 = function() { + var m = util$e.format.apply(util$e, arguments); + m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: '); + console.error(m); + }; + +// Once time initialization +if (!fs$c[gracefulQueue]) { + // This queue can be shared by multiple loaded instances + var queue = commonjsGlobal[gracefulQueue] || []; + publishQueue(fs$c, 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$c.close = (function (fs$close) { + function close (fd, cb) { + return fs$close.call(fs$c, 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$c.close); + + fs$c.closeSync = (function (fs$closeSync) { + function closeSync (fd) { + // This function uses the graceful-fs shared queue + fs$closeSync.apply(fs$c, arguments); + resetQueue(); + } + + Object.defineProperty(closeSync, previousSymbol, { + value: fs$closeSync + }); + return closeSync + })(fs$c.closeSync); + + if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) { + process.on('exit', function() { + debug$2(fs$c[gracefulQueue]); + require$$5$1.equal(fs$c[gracefulQueue].length, 0); + }); + } +} + +if (!commonjsGlobal[gracefulQueue]) { + publishQueue(commonjsGlobal, fs$c[gracefulQueue]); +} + +var gracefulFs = patch(clone$9(fs$c)); +if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs$c.__patched) { + gracefulFs = patch(fs$c); + fs$c.__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$2('ENQUEUE', elem[0].name, elem[1]); + fs$c[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$c[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$c[gracefulQueue][i].length > 2) { + fs$c[gracefulQueue][i][3] = now; // startTime + fs$c[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$c[gracefulQueue].length === 0) + return + + var elem = fs$c[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$2('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$2('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$2('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$c[gracefulQueue].push(elem); + } + } + + // schedule our next run if one isn't already scheduled + if (retryTimer === undefined) { + retryTimer = setTimeout(retry, 0); + } +} + +var __importDefault$5 = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(caFile, "__esModule", { value: true }); +caFile.readCAFileSync = void 0; +const graceful_fs_1 = __importDefault$5(gracefulFs); +function readCAFileSync$1(filePath) { + try { + const contents = graceful_fs_1.default.readFileSync(filePath, 'utf8'); + const delim = '-----END CERTIFICATE-----'; + const output = contents + .split(delim) + .filter((ca) => Boolean(ca.trim())) + .map((ca) => `${ca.trimLeft()}${delim}`); + return output; + } + catch (err) { + if (err.code === 'ENOENT') + return undefined; + throw err; + } +} +caFile.readCAFileSync = readCAFileSync$1; + +(function (exports) { + var __createBinding = (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 __exportStar = (commonjsGlobal && commonjsGlobal.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); + }; + Object.defineProperty(exports, "__esModule", { value: true }); + __exportStar(caFile, exports); + +} (dist$7)); + +var configChain = {exports: {}}; + +var protoList = ProtoList$1; + +function setProto(obj, proto) { + if (typeof Object.setPrototypeOf === "function") + return Object.setPrototypeOf(obj, proto) + else + obj.__proto__ = proto; +} + +function ProtoList$1 () { + this.list = []; + var root = null; + Object.defineProperty(this, 'root', { + get: function () { return root }, + set: function (r) { + root = r; + if (this.list.length) { + setProto(this.list[this.list.length - 1], r); + } + }, + enumerable: true, + configurable: true + }); +} + +ProtoList$1.prototype = + { get length () { return this.list.length } + , get keys () { + var k = []; + for (var i in this.list[0]) k.push(i); + return k + } + , get snapshot () { + var o = {}; + this.keys.forEach(function (k) { o[k] = this.get(k); }, this); + return o + } + , get store () { + return this.list[0] + } + , push : function (obj) { + if (typeof obj !== "object") obj = {valueOf:obj}; + if (this.list.length >= 1) { + setProto(this.list[this.list.length - 1], obj); + } + setProto(obj, this.root); + return this.list.push(obj) + } + , pop : function () { + if (this.list.length >= 2) { + setProto(this.list[this.list.length - 2], this.root); + } + return this.list.pop() + } + , unshift : function (obj) { + setProto(obj, this.list[0] || this.root); + return this.list.unshift(obj) + } + , shift : function () { + if (this.list.length === 1) { + setProto(this.list[0], this.root); + } + return this.list.shift() + } + , get : function (key) { + return this.list[0][key] + } + , set : function (key, val, save) { + if (!this.length) this.push({}); + if (save && this.list[0].hasOwnProperty(key)) this.push({}); + return this.list[0][key] = val + } + , forEach : function (fn, thisp) { + for (var key in this.list[0]) fn.call(thisp, key, this.list[0][key]); + } + , slice : function () { + return this.list.slice.apply(this.list, arguments) + } + , splice : function () { + // handle injections + var ret = this.list.splice.apply(this.list, arguments); + for (var i = 0, l = this.list.length; i < l; i++) { + setProto(this.list[i], this.list[i + 1] || this.root); + } + return ret + } + }; + +var ProtoList = protoList + , path$9 = require$$0$b + , fs$b = require$$0$8 + , ini$1 = ini$3 + , EE = require$$2$3.EventEmitter + , url$e = require$$0$e + , http$5 = require$$0$a; + +var exports$1 = configChain.exports = function () { + var args = [].slice.call(arguments) + , conf = new ConfigChain$1(); + + while(args.length) { + var a = args.shift(); + if(a) conf.push + ( 'string' === typeof a + ? json$6(a) + : a ); + } + + return conf +}; + +//recursively find a file... + +exports$1.find = function () { + var rel = path$9.join.apply(null, [].slice.call(arguments)); + + function find(start, rel) { + var file = path$9.join(start, rel); + try { + fs$b.statSync(file); + return file + } catch (err) { + if(path$9.dirname(start) !== start) // root + return find(path$9.dirname(start), rel) + } + } + return find(__dirname, rel) +}; + +var parse$d = exports$1.parse = function (content, file, type) { + content = '' + content; + // if we don't know what it is, try json and fall back to ini + // if we know what it is, then it must be that. + if (!type) { + try { return JSON.parse(content) } + catch (er) { return ini$1.parse(content) } + } else if (type === 'json') { + if (this.emit) { + try { return JSON.parse(content) } + catch (er) { this.emit('error', er); } + } else { + return JSON.parse(content) + } + } else { + return ini$1.parse(content) + } +}; + +var json$6 = exports$1.json = function () { + var args = [].slice.call(arguments).filter(function (arg) { return arg != null }); + var file = path$9.join.apply(null, args); + var content; + try { + content = fs$b.readFileSync(file,'utf-8'); + } catch (err) { + return + } + return parse$d(content, file, 'json') +}; + +exports$1.env = function (prefix, env) { + env = env || process.env; + var obj = {}; + var l = prefix.length; + for(var k in env) { + if(k.indexOf(prefix) === 0) + obj[k.substring(l)] = env[k]; + } + + return obj +}; + +exports$1.ConfigChain = ConfigChain$1; +function ConfigChain$1 () { + EE.apply(this); + ProtoList.apply(this, arguments); + this._awaiting = 0; + this._saving = 0; + this.sources = {}; +} + +// multi-inheritance-ish +var extras = { + constructor: { value: ConfigChain$1 } +}; +Object.keys(EE.prototype).forEach(function (k) { + extras[k] = Object.getOwnPropertyDescriptor(EE.prototype, k); +}); +ConfigChain$1.prototype = Object.create(ProtoList.prototype, extras); + +ConfigChain$1.prototype.del = function (key, where) { + // if not specified where, then delete from the whole chain, scorched + // earth style + if (where) { + var target = this.sources[where]; + target = target && target.data; + if (!target) { + return this.emit('error', new Error('not found '+where)) + } + delete target[key]; + } else { + for (var i = 0, l = this.list.length; i < l; i ++) { + delete this.list[i][key]; + } + } + return this +}; + +ConfigChain$1.prototype.set = function (key, value, where) { + var target; + + if (where) { + target = this.sources[where]; + target = target && target.data; + if (!target) { + return this.emit('error', new Error('not found '+where)) + } + } else { + target = this.list[0]; + if (!target) { + return this.emit('error', new Error('cannot set, no confs!')) + } + } + target[key] = value; + return this +}; + +ConfigChain$1.prototype.get = function (key, where) { + if (where) { + where = this.sources[where]; + if (where) where = where.data; + if (where && Object.hasOwnProperty.call(where, key)) return where[key] + return undefined + } + return this.list[0][key] +}; + +ConfigChain$1.prototype.save = function (where, type, cb) { + if (typeof type === 'function') cb = type, type = null; + var target = this.sources[where]; + if (!target || !(target.path || target.source) || !target.data) { + // TODO: maybe save() to a url target could be a PUT or something? + // would be easy to swap out with a reddis type thing, too + return this.emit('error', new Error('bad save target: '+where)) + } + + if (target.source) { + var pref = target.prefix || ''; + Object.keys(target.data).forEach(function (k) { + target.source[pref + k] = target.data[k]; + }); + return this + } + + var type = type || target.type; + var data = target.data; + if (target.type === 'json') { + data = JSON.stringify(data); + } else { + data = ini$1.stringify(data); + } + + this._saving ++; + fs$b.writeFile(target.path, data, 'utf8', function (er) { + this._saving --; + if (er) { + if (cb) return cb(er) + else return this.emit('error', er) + } + if (this._saving === 0) { + if (cb) cb(); + this.emit('save'); + } + }.bind(this)); + return this +}; + +ConfigChain$1.prototype.addFile = function (file, type, name) { + name = name || file; + var marker = {__source__:name}; + this.sources[name] = { path: file, type: type }; + this.push(marker); + this._await(); + fs$b.readFile(file, 'utf8', function (er, data) { + if (er) this.emit('error', er); + this.addString(data, file, type, marker); + }.bind(this)); + return this +}; + +ConfigChain$1.prototype.addEnv = function (prefix, env, name) { + name = name || 'env'; + var data = exports$1.env(prefix, env); + this.sources[name] = { data: data, source: env, prefix: prefix }; + return this.add(data, name) +}; + +ConfigChain$1.prototype.addUrl = function (req, type, name) { + this._await(); + var href = url$e.format(req); + name = name || href; + var marker = {__source__:name}; + this.sources[name] = { href: href, type: type }; + this.push(marker); + http$5.request(req, function (res) { + var c = []; + var ct = res.headers['content-type']; + if (!type) { + type = ct.indexOf('json') !== -1 ? 'json' + : ct.indexOf('ini') !== -1 ? 'ini' + : href.match(/\.json$/) ? 'json' + : href.match(/\.ini$/) ? 'ini' + : null; + marker.type = type; + } + + res.on('data', c.push.bind(c)) + .on('end', function () { + this.addString(Buffer.concat(c), href, type, marker); + }.bind(this)) + .on('error', this.emit.bind(this, 'error')); + + }.bind(this)) + .on('error', this.emit.bind(this, 'error')) + .end(); + + return this +}; + +ConfigChain$1.prototype.addString = function (data, file, type, marker) { + data = this.parse(data, file, type); + this.add(data, marker); + return this +}; + +ConfigChain$1.prototype.add = function (data, marker) { + if (marker && typeof marker === 'object') { + var i = this.list.indexOf(marker); + if (i === -1) { + return this.emit('error', new Error('bad marker')) + } + this.splice(i, 1, data); + marker = marker.__source__; + this.sources[marker] = this.sources[marker] || {}; + this.sources[marker].data = data; + // we were waiting for this. maybe emit 'load' + this._resolve(); + } else { + if (typeof marker === 'string') { + this.sources[marker] = this.sources[marker] || {}; + this.sources[marker].data = data; + } + // trigger the load event if nothing was already going to do so. + this._await(); + this.push(data); + process.nextTick(this._resolve.bind(this)); + } + return this +}; + +ConfigChain$1.prototype.parse = exports$1.parse; + +ConfigChain$1.prototype._await = function () { + this._awaiting++; +}; + +ConfigChain$1.prototype._resolve = function () { + this._awaiting--; + if (this._awaiting === 0) this.emit('load', this); +}; + +var configChainExports = configChain.exports; + +var envKeyToSetting$1 = function (x) { + const colonIndex = x.indexOf(':'); + if (colonIndex === -1) { + return normalize$1(x); + } + const firstPart = x.substr(0, colonIndex); + const secondPart = x.substr(colonIndex + 1); + return `${normalize$1(firstPart)}:${normalize$1(secondPart)}`; +}; + +function normalize$1 (s) { + s = s.toLowerCase(); + if (s === '_authtoken') return '_authToken'; + let r = s[0]; + for (let i = 1; i < s.length; i++) { + r += s[i] === '_' ? '-' : s[i]; + } + return r; +} + +var util$d = {}; + +var dist$6 = {}; + +var envReplace$2 = {}; + +Object.defineProperty(envReplace$2, "__esModule", { value: true }); +envReplace$2.envReplace = void 0; +const ENV_EXPR = /(? { + if (typeof field !== 'string') { + return field; + } + + const typeList = [].concat(types[key]); + const isPath = typeList.indexOf(path$8) !== -1; + const isBool = typeList.indexOf(Boolean) !== -1; + const isString = typeList.indexOf(String) !== -1; + const isNumber = typeList.indexOf(Number) !== -1; + + field = `${field}`.trim(); + + if (/^".*"$/.test(field)) { + try { + field = JSON.parse(field); + } catch (error) { + throw new Error(`Failed parsing JSON config key ${key}: ${field}`); + } + } + + if (isBool && !isString && field === '') { + return true; + } + + switch (field) { // eslint-disable-line default-case + case 'true': { + return true; + } + + case 'false': { + return false; + } + + case 'null': { + return null; + } + + case 'undefined': { + return undefined; + } + } + + field = envReplace(field, process.env); + + if (isPath) { + const regex = process.platform === 'win32' ? /^~(\/|\\)/ : /^~\//; + + if (regex.test(field) && process.env.HOME) { + field = path$8.resolve(process.env.HOME, field.substr(2)); + } + + field = path$8.resolve(field); + } + + if (isNumber && !isNaN(field)) { + field = Number(field); + } + + return field; +}; + +// https://github.com/npm/cli/blob/latest/lib/config/find-prefix.js +const findPrefix = name => { + name = path$8.resolve(name); + + let walkedUp = false; + + while (path$8.basename(name) === 'node_modules') { + name = path$8.dirname(name); + walkedUp = true; + } + + if (walkedUp) { + return name; + } + + const find = (name, original) => { + const regex = /^[a-zA-Z]:(\\|\/)?$/; + + if (name === '/' || (process.platform === 'win32' && regex.test(name))) { + return original; + } + + try { + const files = fs$a.readdirSync(name); + + if ( + files.includes('node_modules') || + files.includes('package.json') || + files.includes('package.json5') || + files.includes('package.yaml') || + files.includes('pnpm-workspace.yaml') + ) { + return name; + } + + const dirname = path$8.dirname(name); + + if (dirname === name) { + return original; + } + + return find(dirname, original); + } catch (error) { + if (name === original) { + if (error.code === 'ENOENT') { + return original; + } + + throw error; + } + + return original; + } + }; + + return find(name, name); +}; + +util$d.envReplace = envReplace; +util$d.findPrefix = findPrefix; +util$d.parseField = parseField; + +var types$4 = {}; + +var hasRequiredTypes; + +function requireTypes () { + if (hasRequiredTypes) return types$4; + hasRequiredTypes = 1; + const path = require$$0$b; + const Stream = Stream$3.Stream; + const url = require$$0$e; + + const Umask = () => {}; + const getLocalAddresses = () => []; + const semver = () => {}; + + types$4.types = { + access: [null, 'restricted', 'public'], + 'allow-same-version': Boolean, + 'always-auth': Boolean, + also: [null, 'dev', 'development'], + audit: Boolean, + 'auth-type': ['legacy', 'sso', 'saml', 'oauth'], + 'bin-links': Boolean, + browser: [null, String], + ca: [null, String, Array], + cafile: path, + cache: path, + 'cache-lock-stale': Number, + 'cache-lock-retries': Number, + 'cache-lock-wait': Number, + 'cache-max': Number, + 'cache-min': Number, + cert: [null, String], + cidr: [null, String, Array], + color: ['always', Boolean], + depth: Number, + description: Boolean, + dev: Boolean, + 'dry-run': Boolean, + editor: String, + 'engine-strict': Boolean, + force: Boolean, + 'fetch-retries': Number, + 'fetch-retry-factor': Number, + 'fetch-retry-mintimeout': Number, + 'fetch-retry-maxtimeout': Number, + git: String, + 'git-tag-version': Boolean, + 'commit-hooks': Boolean, + global: Boolean, + globalconfig: path, + 'global-style': Boolean, + group: [Number, String], + 'https-proxy': [null, url], + 'user-agent': String, + 'ham-it-up': Boolean, + 'heading': String, + 'if-present': Boolean, + 'ignore-prepublish': Boolean, + 'ignore-scripts': Boolean, + 'init-module': path, + 'init-author-name': String, + 'init-author-email': String, + 'init-author-url': ['', url], + 'init-license': String, + 'init-version': semver, + json: Boolean, + key: [null, String], + 'legacy-bundling': Boolean, + link: Boolean, + // local-address must be listed as an IP for a local network interface + // must be IPv4 due to node bug + 'local-address': getLocalAddresses(), + loglevel: ['silent', 'error', 'warn', 'notice', 'http', 'timing', 'info', 'verbose', 'silly'], + logstream: Stream, + 'logs-max': Number, + long: Boolean, + maxsockets: Number, + message: String, + 'metrics-registry': [null, String], + 'node-options': [null, String], + 'node-version': [null, semver], + 'no-proxy': [null, String, Array], + offline: Boolean, + 'onload-script': [null, String], + only: [null, 'dev', 'development', 'prod', 'production'], + optional: Boolean, + 'package-lock': Boolean, + otp: [null, String], + 'package-lock-only': Boolean, + parseable: Boolean, + 'prefer-offline': Boolean, + 'prefer-online': Boolean, + prefix: path, + production: Boolean, + progress: Boolean, + proxy: [null, false, url], + provenance: Boolean, + // allow proxy to be disabled explicitly + 'read-only': Boolean, + 'rebuild-bundle': Boolean, + registry: [null, url], + rollback: Boolean, + save: Boolean, + 'save-bundle': Boolean, + 'save-dev': Boolean, + 'save-exact': Boolean, + 'save-optional': Boolean, + 'save-prefix': String, + 'save-prod': Boolean, + scope: String, + 'script-shell': [null, String], + 'scripts-prepend-node-path': [false, true, 'auto', 'warn-only'], + searchopts: String, + searchexclude: [null, String], + searchlimit: Number, + searchstaleness: Number, + 'send-metrics': Boolean, + shell: String, + shrinkwrap: Boolean, + 'sign-git-tag': Boolean, + 'sso-poll-frequency': Number, + 'sso-type': [null, 'oauth', 'saml'], + 'strict-ssl': Boolean, + tag: String, + timing: Boolean, + tmp: path, + unicode: Boolean, + 'unsafe-perm': Boolean, + usage: Boolean, + user: [Number, String], + userconfig: path, + umask: Umask, + version: Boolean, + 'tag-version-prefix': String, + versions: Boolean, + viewer: String, + _exit: Boolean + }; + return types$4; +} + +const { readCAFileSync } = dist$7; +const fs$9 = require$$0$8; +const path$7 = require$$0$b; +const {ConfigChain} = configChainExports; +const envKeyToSetting = envKeyToSetting$1; +const util$c = util$d; + +class Conf extends ConfigChain { + // https://github.com/npm/cli/blob/latest/lib/config/core.js#L203-L217 + constructor(base, types) { + super(base); + this.root = base; + this._parseField = util$c.parseField.bind(null, types || requireTypes()); + } + + // https://github.com/npm/cli/blob/latest/lib/config/core.js#L326-L338 + add(data, marker) { + try { + for (const x of Object.keys(data)) { + data[x] = this._parseField(data[x], x); + } + } catch (error) { + throw error; + } + + return super.add(data, marker); + } + + // https://github.com/npm/cli/blob/latest/lib/config/core.js#L306-L319 + addFile(file, name) { + name = name || file; + + const marker = {__source__: name}; + + this.sources[name] = {path: file, type: 'ini'}; + this.push(marker); + this._await(); + + try { + const contents = fs$9.readFileSync(file, 'utf8'); + this.addString(contents, file, 'ini', marker); + } catch (error) { + if (error.code === 'ENOENT') { + this.add({}, marker); + } else { + return `Issue while reading "${file}". ${error.message}` + } + } + } + + // https://github.com/npm/cli/blob/latest/lib/config/core.js#L341-L357 + addEnv(env) { + env = env || process.env; + + const conf = {}; + + Object.keys(env) + .filter(x => /^npm_config_/i.test(x)) + .forEach(x => { + if (!env[x]) { + return; + } + + conf[envKeyToSetting(x.substr(11))] = env[x]; + }); + + return super.addEnv('', conf, 'env'); + } + + // https://github.com/npm/cli/blob/latest/lib/config/load-prefix.js + loadPrefix() { + const cli = this.list[0]; + + Object.defineProperty(this, 'prefix', { + enumerable: true, + set: prefix => { + const g = this.get('global'); + this[g ? 'globalPrefix' : 'localPrefix'] = prefix; + }, + get: () => { + const g = this.get('global'); + return g ? this.globalPrefix : this.localPrefix; + } + }); + + Object.defineProperty(this, 'globalPrefix', { + enumerable: true, + set: prefix => { + this.set('prefix', prefix); + }, + get: () => { + return path$7.resolve(this.get('prefix')); + } + }); + + let p; + + Object.defineProperty(this, 'localPrefix', { + enumerable: true, + set: prefix => { + p = prefix; + }, + get: () => { + return p; + } + }); + + if (Object.prototype.hasOwnProperty.call(cli, 'prefix')) { + p = path$7.resolve(cli.prefix); + } else { + try { + const prefix = util$c.findPrefix(process.cwd()); + p = prefix; + } catch (error) { + throw error; + } + } + + return p; + } + + // https://github.com/npm/cli/blob/latest/lib/config/load-cafile.js + loadCAFile(file) { + if (!file) { + return; + } + + const ca = readCAFileSync(file); + if (ca) { + this.set('ca', ca); + } + } + + // https://github.com/npm/cli/blob/latest/lib/config/set-user.js + loadUser() { + const defConf = this.root; + + if (this.get('global')) { + return; + } + + if (process.env.SUDO_UID) { + defConf.user = Number(process.env.SUDO_UID); + return; + } + + const prefix = path$7.resolve(this.get('prefix')); + + try { + const stats = fs$9.statSync(prefix); + defConf.user = stats.uid; + } catch (error) { + if (error.code === 'ENOENT') { + return; + } + + throw error; + } + } +} + +var conf = Conf; + +var defaults$b = {}; + +(function (exports) { + const os = require$$0$7; + const path = require$$0$b; + + const temp = os.tmpdir(); + const uidOrPid = process.getuid ? process.getuid() : process.pid; + const hasUnicode = () => true; + const isWindows = process.platform === 'win32'; + + const osenv = { + editor: () => process.env.EDITOR || process.env.VISUAL || (isWindows ? 'notepad.exe' : 'vi'), + shell: () => isWindows ? (process.env.COMSPEC || 'cmd.exe') : (process.env.SHELL || '/bin/bash') + }; + + const umask = { + fromString: () => process.umask() + }; + + let home = os.homedir(); + + if (home) { + process.env.HOME = home; + } else { + home = path.resolve(temp, 'npm-' + uidOrPid); + } + + const cacheExtra = process.platform === 'win32' ? 'npm-cache' : '.npm'; + const cacheRoot = process.platform === 'win32' && process.env.APPDATA || home; + const cache = path.resolve(cacheRoot, cacheExtra); + + let defaults; + let globalPrefix; + + Object.defineProperty(exports, 'defaults', { + get: function () { + if (defaults) return defaults; + + if (process.env.PREFIX) { + globalPrefix = process.env.PREFIX; + } else if (process.platform === 'win32') { + // c:\node\node.exe --> prefix=c:\node\ + globalPrefix = path.dirname(process.execPath); + } else { + // /usr/local/bin/node --> prefix=/usr/local + globalPrefix = path.dirname(path.dirname(process.execPath)); // destdir only is respected on Unix + + if (process.env.DESTDIR) { + globalPrefix = path.join(process.env.DESTDIR, globalPrefix); + } + } + + defaults = { + access: null, + 'allow-same-version': false, + 'always-auth': false, + also: null, + audit: true, + 'auth-type': 'legacy', + 'bin-links': true, + browser: null, + ca: null, + cafile: null, + cache: cache, + 'cache-lock-stale': 60000, + 'cache-lock-retries': 10, + 'cache-lock-wait': 10000, + 'cache-max': Infinity, + 'cache-min': 10, + cert: null, + cidr: null, + color: process.env.NO_COLOR == null, + depth: Infinity, + description: true, + dev: false, + 'dry-run': false, + editor: osenv.editor(), + 'engine-strict': false, + force: false, + 'fetch-retries': 2, + 'fetch-retry-factor': 10, + 'fetch-retry-mintimeout': 10000, + 'fetch-retry-maxtimeout': 60000, + git: 'git', + 'git-tag-version': true, + 'commit-hooks': true, + global: false, + globalconfig: path.resolve(globalPrefix, 'etc', 'npmrc'), + 'global-style': false, + group: process.platform === 'win32' ? 0 : process.env.SUDO_GID || process.getgid && process.getgid(), + 'ham-it-up': false, + heading: 'npm', + 'if-present': false, + 'ignore-prepublish': false, + 'ignore-scripts': false, + 'init-module': path.resolve(home, '.npm-init.js'), + 'init-author-name': '', + 'init-author-email': '', + 'init-author-url': '', + 'init-version': '1.0.0', + 'init-license': 'ISC', + json: false, + key: null, + 'legacy-bundling': false, + link: false, + 'local-address': undefined, + loglevel: 'notice', + logstream: process.stderr, + 'logs-max': 10, + long: false, + maxsockets: 50, + message: '%s', + 'metrics-registry': null, + 'node-options': null, + // We remove node-version to fix the issue described here: https://github.com/pnpm/pnpm/issues/4203#issuecomment-1133872769 + 'offline': false, + 'onload-script': false, + only: null, + optional: true, + otp: null, + 'package-lock': true, + 'package-lock-only': false, + parseable: false, + 'prefer-offline': false, + 'prefer-online': false, + prefix: globalPrefix, + production: process.env.NODE_ENV === 'production', + 'progress': !process.env.TRAVIS && !process.env.CI, + provenance: false, + proxy: null, + 'https-proxy': null, + 'no-proxy': null, + 'user-agent': 'npm/{npm-version} ' + 'node/{node-version} ' + '{platform} ' + '{arch}', + 'read-only': false, + 'rebuild-bundle': true, + registry: 'https://registry.npmjs.org/', + rollback: true, + save: true, + 'save-bundle': false, + 'save-dev': false, + 'save-exact': false, + 'save-optional': false, + 'save-prefix': '^', + 'save-prod': false, + scope: '', + 'script-shell': null, + 'scripts-prepend-node-path': 'warn-only', + searchopts: '', + searchexclude: null, + searchlimit: 20, + searchstaleness: 15 * 60, + 'send-metrics': false, + shell: osenv.shell(), + shrinkwrap: true, + 'sign-git-tag': false, + 'sso-poll-frequency': 500, + 'sso-type': 'oauth', + 'strict-ssl': true, + tag: 'latest', + 'tag-version-prefix': 'v', + timing: false, + tmp: temp, + unicode: hasUnicode(), + 'unsafe-perm': process.platform === 'win32' || process.platform === 'cygwin' || !(process.getuid && process.setuid && process.getgid && process.setgid) || process.getuid() !== 0, + usage: false, + user: process.platform === 'win32' ? 0 : 'nobody', + userconfig: path.resolve(home, '.npmrc'), + umask: process.umask ? process.umask() : umask.fromString('022'), + version: false, + versions: false, + viewer: process.platform === 'win32' ? 'browser' : 'man', + _exit: true + }; + return defaults; + } + }); +} (defaults$b)); + +(function (module) { + const path = require$$0$b; + const Conf = conf; + const _defaults = defaults$b; + + // https://github.com/npm/cli/blob/latest/lib/config/core.js#L101-L200 + module.exports = (opts, types, defaults) => { + const conf = new Conf(Object.assign({}, _defaults.defaults, defaults), types); + + conf.add(Object.assign({}, opts), 'cli'); + const warnings = []; + let failedToLoadBuiltInConfig = false; + + if (require.resolve.paths) { + const paths = require.resolve.paths('npm'); + // Assume that last path in resolve paths is builtin modules directory + let npmPath; + try { + npmPath = require.resolve('npm', {paths: paths.slice(-1)}); + } catch (error) { + // Error will be thrown if module cannot be found. + // Update the flag while loading builtin config failed. + failedToLoadBuiltInConfig = true; + } + + if (npmPath) { + /** + * According to https://github.com/npm/cli/blob/86f5bdb91f7a5971953a5171d32d6eeda6a2e972/lib/npm.js#L258 + * and https://github.com/npm/cli/blob/86f5bdb91f7a5971953a5171d32d6eeda6a2e972/lib/config/core.js#L92 + */ + warnings.push(conf.addFile(path.resolve(path.dirname(npmPath), '..', 'npmrc'), 'builtin')); + } + } + + conf.addEnv(); + conf.loadPrefix(); + + const projectConf = path.resolve(conf.localPrefix, '.npmrc'); + const userConf = conf.get('userconfig'); + + if (!conf.get('global') && projectConf !== userConf) { + warnings.push(conf.addFile(projectConf, 'project')); + } else { + conf.add({}, 'project'); + } + + // TODO: cover with tests that configs from workspace .npmrc have bigger priority + // than the ones in userconfig + if (conf.get('workspace-prefix') && conf.get('workspace-prefix') !== projectConf) { + const workspaceConf = path.resolve(conf.get('workspace-prefix'), '.npmrc'); + warnings.push(conf.addFile(workspaceConf, 'workspace')); + } + + warnings.push(conf.addFile(conf.get('userconfig'), 'user')); + + if (conf.get('prefix')) { + const etc = path.resolve(conf.get('prefix'), 'etc'); + conf.root.globalconfig = path.resolve(etc, 'npmrc'); + conf.root.globalignorefile = path.resolve(etc, 'npmignore'); + } + + warnings.push(conf.addFile(conf.get('globalconfig'), 'global')); + conf.loadUser(); + + const caFile = conf.get('cafile'); + + if (caFile) { + conf.loadCAFile(caFile); + } + + return { + config: conf, + warnings: warnings.filter(Boolean), + failedToLoadBuiltInConfig, + }; + }; + + Object.defineProperty(module.exports, 'defaults', { + get() { + return _defaults.defaults; + }, + enumerable: true + }); +} (npmConf$1)); + +var npmConfExports = npmConf$1.exports; + +const url$d = require$$0$e; +const npmConf = npmConfExports; + +const tokenKey = ':_authToken'; +const legacyTokenKey = ':_auth'; +const userKey = ':username'; +const passwordKey = ':_password'; + +var registryAuthToken = function getRegistryAuthToken () { + let checkUrl; + let options; + if (arguments.length >= 2) { + checkUrl = arguments[0]; + options = Object.assign({}, arguments[1]); + } else if (typeof arguments[0] === 'string') { + checkUrl = arguments[0]; + } else { + options = Object.assign({}, arguments[0]); + } + options = options || {}; + + const providedNpmrc = options.npmrc; + options.npmrc = (options.npmrc ? { + config: { + get: (key) => providedNpmrc[key] + } + } : npmConf()).config; + + checkUrl = checkUrl || options.npmrc.get('registry') || npmConf.defaults.registry; + return getRegistryAuthInfo(checkUrl, options) || getLegacyAuthInfo(options.npmrc) +}; + +function getRegistryAuthInfo (checkUrl, options) { + const parsed = url$d.parse(checkUrl, false, true); + let pathname; + + while (pathname !== '/' && parsed.pathname !== pathname) { + pathname = parsed.pathname || '/'; + + const regUrl = '//' + parsed.host + pathname.replace(/\/$/, ''); + const authInfo = getAuthInfoForUrl(regUrl, options.npmrc); + if (authInfo) { + return authInfo + } + + // break if not recursive + if (!options.recursive) { + return /\/$/.test(checkUrl) + ? undefined + : getRegistryAuthInfo(url$d.resolve(checkUrl, '.'), options) + } + + parsed.pathname = url$d.resolve(normalizePath$1(pathname), '..') || '/'; + } + + return undefined +} + +function getLegacyAuthInfo (npmrc) { + if (!npmrc.get('_auth')) { + return undefined + } + + const token = replaceEnvironmentVariable(npmrc.get('_auth')); + + return { token: token, type: 'Basic' } +} + +function normalizePath$1 (path) { + return path[path.length - 1] === '/' ? path : path + '/' +} + +function getAuthInfoForUrl (regUrl, npmrc) { + // try to get bearer token + const bearerAuth = getBearerToken(npmrc.get(regUrl + tokenKey) || npmrc.get(regUrl + '/' + tokenKey)); + if (bearerAuth) { + return bearerAuth + } + + // try to get basic token + const username = npmrc.get(regUrl + userKey) || npmrc.get(regUrl + '/' + userKey); + const password = npmrc.get(regUrl + passwordKey) || npmrc.get(regUrl + '/' + passwordKey); + const basicAuth = getTokenForUsernameAndPassword(username, password); + if (basicAuth) { + return basicAuth + } + + const basicAuthWithToken = getLegacyAuthToken(npmrc.get(regUrl + legacyTokenKey) || npmrc.get(regUrl + '/' + legacyTokenKey)); + if (basicAuthWithToken) { + return basicAuthWithToken + } + + return undefined +} + +function replaceEnvironmentVariable (token) { + return token.replace(/^\$\{?([^}]*)\}?$/, function (fullMatch, envVar) { + return process.env[envVar] + }) +} + +function getBearerToken (tok) { + if (!tok) { + return undefined + } + + // check if bearer token is set as environment variable + const token = replaceEnvironmentVariable(tok); + + return { token: token, type: 'Bearer' } +} + +function getTokenForUsernameAndPassword (username, password) { + if (!username || !password) { + return undefined + } + + // passwords are base64 encoded, so we need to decode it + // See https://github.com/npm/npm/blob/v3.10.6/lib/config/set-credentials-by-uri.js#L26 + const pass = Buffer.from(replaceEnvironmentVariable(password), 'base64').toString('utf8'); + + // a basic auth token is base64 encoded 'username:password' + // See https://github.com/npm/npm/blob/v3.10.6/lib/config/get-credentials-by-uri.js#L70 + const token = Buffer.from(username + ':' + pass, 'utf8').toString('base64'); + + // we found a basicToken token so let's exit the loop + return { + token: token, + type: 'Basic', + password: pass, + username: username + } +} + +function getLegacyAuthToken (tok) { + if (!tok) { + return undefined + } + + // check if legacy auth token is set as environment variable + const token = replaceEnvironmentVariable(tok); + + return { token: token, type: 'Basic' } +} + +var registryAuthToken$1 = /*@__PURE__*/getDefaultExportFromCjs(registryAuthToken); + +// These agent options are chosen to match the npm client defaults and help with performance +// See: `npm config get maxsockets` and #50 +const agentOptions = { + keepAlive: true, + maxSockets: 50, +}; + +const httpAgent = new http$a.Agent(agentOptions); +const httpsAgent = new https$8.Agent(agentOptions); + +class PackageNotFoundError extends Error { + constructor(packageName) { + super(`Package \`${packageName}\` could not be found`); + this.name = 'PackageNotFoundError'; + } +} + +class VersionNotFoundError extends Error { + constructor(packageName, version) { + super(`Version \`${version}\` for package \`${packageName}\` could not be found`); + this.name = 'VersionNotFoundError'; + } +} + +async function packageJson$1(packageName, options) { + options = { + version: 'latest', + ...options, + }; + + const scope = packageName.split('/')[0]; + const registryUrl_ = options.registryUrl || registryUrl$1(scope); + const packageUrl = new URL(encodeURIComponent(packageName).replace(/^%40/, '@'), registryUrl_); + const authInfo = registryAuthToken$1(registryUrl_.toString(), {recursive: true}); + + const headers = { + accept: 'application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*', + }; + + if (options.fullMetadata) { + delete headers.accept; + } + + if (authInfo) { + headers.authorization = `${authInfo.type} ${authInfo.token}`; + } + + const gotOptions = { + headers, + agent: { + http: httpAgent, + https: httpsAgent, + }, + }; + + if (options.agent) { + gotOptions.agent = options.agent; + } + + let data; + try { + data = await got$1(packageUrl, gotOptions).json(); + } catch (error) { + if (error?.response?.statusCode === 404) { + throw new PackageNotFoundError(packageName); + } + + throw error; + } + + if (options.allVersions) { + return data; + } + + let {version} = options; + const versionError = new VersionNotFoundError(packageName, version); + + if (data['dist-tags'][version]) { + const time = data.time; + data = data.versions[data['dist-tags'][version]]; + data.time = time; + } else if (version) { + if (!data.versions[version]) { + const versions = Object.keys(data.versions); + version = semver$1.maxSatisfying(versions, version); + + if (!version) { + throw versionError; + } + } + + const time = data.time; + data = data.versions[version]; + data.time = time; + + if (!data) { + throw versionError; + } + } + + return data; +} + +async function latestVersion(packageName, options) { + const {version} = await packageJson$1(packageName.toLowerCase(), options); + return version; +} + +const packageJson = process$3.env.npm_package_json; +const userAgent = process$3.env.npm_config_user_agent; +const isNpm6 = Boolean(userAgent && userAgent.startsWith('npm')); +const isNpm7 = Boolean(packageJson && packageJson.endsWith('package.json')); + +const isNpm = isNpm6 || isNpm7; +const isYarn = Boolean(userAgent && userAgent.startsWith('yarn')); +const isNpmOrYarn = isNpm || isYarn; + +var globalDirs$1 = {}; + +const { hasOwnProperty: hasOwnProperty$h } = Object.prototype; + +const eol = typeof process !== 'undefined' && + process.platform === 'win32' ? '\r\n' : '\n'; + +const encode = (obj, opt) => { + const children = []; + let out = ''; + + if (typeof opt === 'string') { + opt = { + section: opt, + whitespace: false, + }; + } else { + opt = opt || Object.create(null); + opt.whitespace = opt.whitespace === true; + } + + const separator = opt.whitespace ? ' = ' : '='; + + for (const k of Object.keys(obj)) { + const val = obj[k]; + if (val && Array.isArray(val)) { + for (const item of val) + out += safe(k + '[]') + separator + safe(item) + '\n'; + } else if (val && typeof val === 'object') + children.push(k); + else + out += safe(k) + separator + safe(val) + eol; + } + + if (opt.section && out.length) + out = '[' + safe(opt.section) + ']' + eol + out; + + for (const k of children) { + const nk = dotSplit(k).join('\\.'); + const section = (opt.section ? opt.section + '.' : '') + nk; + const { whitespace } = opt; + const child = encode(obj[k], { + section, + whitespace, + }); + if (out.length && child.length) + out += eol; + + out += child; + } + + return out +}; + +const dotSplit = str => + str.replace(/\1/g, '\u0002LITERAL\\1LITERAL\u0002') + .replace(/\\\./g, '\u0001') + .split(/\./) + .map(part => + part.replace(/\1/g, '\\.') + .replace(/\2LITERAL\\1LITERAL\2/g, '\u0001')); + +const decode = str => { + const out = Object.create(null); + let p = out; + let section = null; + // section |key = value + const re = /^\[([^\]]*)\]$|^([^=]+)(=(.*))?$/i; + const lines = str.split(/[\r\n]+/g); + + for (const line of lines) { + if (!line || line.match(/^\s*[;#]/)) + continue + const match = line.match(re); + if (!match) + continue + if (match[1] !== undefined) { + section = unsafe(match[1]); + if (section === '__proto__') { + // not allowed + // keep parsing the section, but don't attach it. + p = Object.create(null); + continue + } + p = out[section] = out[section] || Object.create(null); + continue + } + const keyRaw = unsafe(match[2]); + const isArray = keyRaw.length > 2 && keyRaw.slice(-2) === '[]'; + const key = isArray ? keyRaw.slice(0, -2) : keyRaw; + if (key === '__proto__') + continue + const valueRaw = match[3] ? unsafe(match[4]) : true; + const value = valueRaw === 'true' || + valueRaw === 'false' || + valueRaw === 'null' ? JSON.parse(valueRaw) + : valueRaw; + + // Convert keys with '[]' suffix to an array + if (isArray) { + if (!hasOwnProperty$h.call(p, key)) + p[key] = []; + else if (!Array.isArray(p[key])) + p[key] = [p[key]]; + } + + // safeguard against resetting a previously defined + // array by accidentally forgetting the brackets + if (Array.isArray(p[key])) + p[key].push(value); + else + p[key] = value; + } + + // {a:{y:1},"a.b":{x:2}} --> {a:{y:1,b:{x:2}}} + // use a filter to return the keys that have to be deleted. + const remove = []; + for (const k of Object.keys(out)) { + if (!hasOwnProperty$h.call(out, k) || + typeof out[k] !== 'object' || + Array.isArray(out[k])) + continue + + // see if the parent section is also an object. + // if so, add it to that, and mark this one for deletion + const parts = dotSplit(k); + let p = out; + const l = parts.pop(); + const nl = l.replace(/\\\./g, '.'); + for (const part of parts) { + if (part === '__proto__') + continue + if (!hasOwnProperty$h.call(p, part) || typeof p[part] !== 'object') + p[part] = Object.create(null); + p = p[part]; + } + if (p === out && nl === l) + continue + + p[nl] = out[k]; + remove.push(k); + } + for (const del of remove) + delete out[del]; + + return out +}; + +const isQuoted = val => + (val.charAt(0) === '"' && val.slice(-1) === '"') || + (val.charAt(0) === "'" && val.slice(-1) === "'"); + +const safe = val => + (typeof val !== 'string' || + val.match(/[=\r\n]/) || + val.match(/^\[/) || + (val.length > 1 && + isQuoted(val)) || + val !== val.trim()) + ? JSON.stringify(val) + : val.replace(/;/g, '\\;').replace(/#/g, '\\#'); + +const unsafe = (val, doUnesc) => { + val = (val || '').trim(); + if (isQuoted(val)) { + // remove the single quotes before calling JSON.parse + if (val.charAt(0) === "'") + val = val.substr(1, val.length - 2); + + try { + val = JSON.parse(val); + } catch (_) {} + } else { + // walk the val to find the first not-escaped ; character + let esc = false; + let unesc = ''; + for (let i = 0, l = val.length; i < l; i++) { + const c = val.charAt(i); + if (esc) { + if ('\\;#'.indexOf(c) !== -1) + unesc += c; + else + unesc += '\\' + c; + + esc = false; + } else if (';#'.indexOf(c) !== -1) + break + else if (c === '\\') + esc = true; + else + unesc += c; + } + if (esc) + unesc += '\\'; + + return unesc.trim() + } + return val +}; + +var ini = { + parse: decode, + decode, + stringify: encode, + encode, + safe, + unsafe, +}; + +(function (exports) { + const path = require$$0$b; + const os = require$$0$7; + const fs = require$$0$8; + const ini$1 = ini; + + const isWindows = process.platform === 'win32'; + + const readRc = filePath => { + try { + return ini$1.parse(fs.readFileSync(filePath, 'utf8')).prefix; + } catch {} + }; + + const getEnvNpmPrefix = () => { + // TODO: Remove the `.reduce` call. + // eslint-disable-next-line unicorn/no-array-reduce + return Object.keys(process.env).reduce((prefix, name) => { + return /^npm_config_prefix$/i.test(name) ? process.env[name] : prefix; + }, undefined); + }; + + const getGlobalNpmrc = () => { + if (isWindows && process.env.APPDATA) { + // Hardcoded contents of `c:\Program Files\nodejs\node_modules\npm\npmrc` + return path.join(process.env.APPDATA, '/npm/etc/npmrc'); + } + + // Homebrew special case: `$(brew --prefix)/lib/node_modules/npm/npmrc` + if (process.execPath.includes('/Cellar/node')) { + const homebrewPrefix = process.execPath.slice(0, process.execPath.indexOf('/Cellar/node')); + return path.join(homebrewPrefix, '/lib/node_modules/npm/npmrc'); + } + + if (process.execPath.endsWith('/bin/node')) { + const installDir = path.dirname(path.dirname(process.execPath)); + return path.join(installDir, '/etc/npmrc'); + } + }; + + const getDefaultNpmPrefix = () => { + if (isWindows) { + const {APPDATA} = process.env; + // `c:\node\node.exe` → `prefix=c:\node\` + return APPDATA ? path.join(APPDATA, 'npm') : path.dirname(process.execPath); + } + + // `/usr/local/bin/node` → `prefix=/usr/local` + return path.dirname(path.dirname(process.execPath)); + }; + + const getNpmPrefix = () => { + const envPrefix = getEnvNpmPrefix(); + if (envPrefix) { + return envPrefix; + } + + const homePrefix = readRc(path.join(os.homedir(), '.npmrc')); + if (homePrefix) { + return homePrefix; + } + + if (process.env.PREFIX) { + return process.env.PREFIX; + } + + const globalPrefix = readRc(getGlobalNpmrc()); + if (globalPrefix) { + return globalPrefix; + } + + return getDefaultNpmPrefix(); + }; + + const npmPrefix = path.resolve(getNpmPrefix()); + + const getYarnWindowsDirectory = () => { + if (isWindows && process.env.LOCALAPPDATA) { + const dir = path.join(process.env.LOCALAPPDATA, 'Yarn'); + if (fs.existsSync(dir)) { + return dir; + } + } + + return false; + }; + + const getYarnPrefix = () => { + if (process.env.PREFIX) { + return process.env.PREFIX; + } + + const windowsPrefix = getYarnWindowsDirectory(); + if (windowsPrefix) { + return windowsPrefix; + } + + const configPrefix = path.join(os.homedir(), '.config/yarn'); + if (fs.existsSync(configPrefix)) { + return configPrefix; + } + + const homePrefix = path.join(os.homedir(), '.yarn-config'); + if (fs.existsSync(homePrefix)) { + return homePrefix; + } + + // Yarn supports the npm conventions but the inverse is not true + return npmPrefix; + }; + + exports.npm = {}; + exports.npm.prefix = npmPrefix; + exports.npm.packages = path.join(npmPrefix, isWindows ? 'node_modules' : 'lib/node_modules'); + exports.npm.binaries = isWindows ? npmPrefix : path.join(npmPrefix, 'bin'); + + const yarnPrefix = path.resolve(getYarnPrefix()); + exports.yarn = {}; + exports.yarn.prefix = yarnPrefix; + exports.yarn.packages = path.join(yarnPrefix, getYarnWindowsDirectory() ? 'Data/global/node_modules' : 'global/node_modules'); + exports.yarn.binaries = path.join(exports.yarn.packages, '.bin'); +} (globalDirs$1)); + +const path$6 = require$$0$b; + +var isPathInside$1 = (childPath, parentPath) => { + const relation = path$6.relative(parentPath, childPath); + return Boolean( + relation && + relation !== '..' && + !relation.startsWith(`..${path$6.sep}`) && + relation !== path$6.resolve(childPath) + ); +}; + +const fs$8 = require$$0$8; +const globalDirs = globalDirs$1; +const isPathInside = isPathInside$1; + +var isInstalledGlobally = (() => { + try { + return ( + isPathInside(__dirname, globalDirs.yarn.packages) || + isPathInside(__dirname, fs$8.realpathSync(globalDirs.npm.packages)) + ); + } catch { + return false; + } +})(); + +var isInstalledGlobally$1 = /*@__PURE__*/getDefaultExportFromCjs(isInstalledGlobally); + +const isYarnGlobal = () => { + const __dirname = path$c.dirname(urlLib.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('rollup-output.cjs', document.baseURI).href)))); + const isWindows = process.platform === 'win32'; + const yarnPath = isWindows + ? path$c.join('Yarn', 'config', 'global') + : path$c.join('.config', 'yarn', 'global'); + return __dirname.includes(yarnPath); +}; + +function hasYarn(cwd = process$3.cwd()) { + return fs$i.existsSync(path$c.resolve(cwd, 'yarn.lock')); +} + +function ansiRegex$4({onlyFirst = false} = {}) { + const pattern = [ + '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)', + '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))' + ].join('|'); + + return new RegExp(pattern, onlyFirst ? undefined : 'g'); +} + +const regex$3 = ansiRegex$4(); + +function stripAnsi$5(string) { + if (typeof string !== 'string') { + throw new TypeError(`Expected a \`string\`, got \`${typeof string}\``); + } + + // Even though the regex is global, we don't need to reset the `.lastIndex` + // because unlike `.exec()` and `.test()`, `.replace()` does it automatically + // and doing it manually has a performance penalty. + return string.replace(regex$3, ''); +} + +var eastasianwidth = {exports: {}}; + +(function (module) { + var eaw = {}; + + { + module.exports = eaw; + } + + eaw.eastAsianWidth = function(character) { + var x = character.charCodeAt(0); + var y = (character.length == 2) ? character.charCodeAt(1) : 0; + var codePoint = x; + if ((0xD800 <= x && x <= 0xDBFF) && (0xDC00 <= y && y <= 0xDFFF)) { + x &= 0x3FF; + y &= 0x3FF; + codePoint = (x << 10) | y; + codePoint += 0x10000; + } + + if ((0x3000 == codePoint) || + (0xFF01 <= codePoint && codePoint <= 0xFF60) || + (0xFFE0 <= codePoint && codePoint <= 0xFFE6)) { + return 'F'; + } + if ((0x20A9 == codePoint) || + (0xFF61 <= codePoint && codePoint <= 0xFFBE) || + (0xFFC2 <= codePoint && codePoint <= 0xFFC7) || + (0xFFCA <= codePoint && codePoint <= 0xFFCF) || + (0xFFD2 <= codePoint && codePoint <= 0xFFD7) || + (0xFFDA <= codePoint && codePoint <= 0xFFDC) || + (0xFFE8 <= codePoint && codePoint <= 0xFFEE)) { + return 'H'; + } + if ((0x1100 <= codePoint && codePoint <= 0x115F) || + (0x11A3 <= codePoint && codePoint <= 0x11A7) || + (0x11FA <= codePoint && codePoint <= 0x11FF) || + (0x2329 <= codePoint && codePoint <= 0x232A) || + (0x2E80 <= codePoint && codePoint <= 0x2E99) || + (0x2E9B <= codePoint && codePoint <= 0x2EF3) || + (0x2F00 <= codePoint && codePoint <= 0x2FD5) || + (0x2FF0 <= codePoint && codePoint <= 0x2FFB) || + (0x3001 <= codePoint && codePoint <= 0x303E) || + (0x3041 <= codePoint && codePoint <= 0x3096) || + (0x3099 <= codePoint && codePoint <= 0x30FF) || + (0x3105 <= codePoint && codePoint <= 0x312D) || + (0x3131 <= codePoint && codePoint <= 0x318E) || + (0x3190 <= codePoint && codePoint <= 0x31BA) || + (0x31C0 <= codePoint && codePoint <= 0x31E3) || + (0x31F0 <= codePoint && codePoint <= 0x321E) || + (0x3220 <= codePoint && codePoint <= 0x3247) || + (0x3250 <= codePoint && codePoint <= 0x32FE) || + (0x3300 <= codePoint && codePoint <= 0x4DBF) || + (0x4E00 <= codePoint && codePoint <= 0xA48C) || + (0xA490 <= codePoint && codePoint <= 0xA4C6) || + (0xA960 <= codePoint && codePoint <= 0xA97C) || + (0xAC00 <= codePoint && codePoint <= 0xD7A3) || + (0xD7B0 <= codePoint && codePoint <= 0xD7C6) || + (0xD7CB <= codePoint && codePoint <= 0xD7FB) || + (0xF900 <= codePoint && codePoint <= 0xFAFF) || + (0xFE10 <= codePoint && codePoint <= 0xFE19) || + (0xFE30 <= codePoint && codePoint <= 0xFE52) || + (0xFE54 <= codePoint && codePoint <= 0xFE66) || + (0xFE68 <= codePoint && codePoint <= 0xFE6B) || + (0x1B000 <= codePoint && codePoint <= 0x1B001) || + (0x1F200 <= codePoint && codePoint <= 0x1F202) || + (0x1F210 <= codePoint && codePoint <= 0x1F23A) || + (0x1F240 <= codePoint && codePoint <= 0x1F248) || + (0x1F250 <= codePoint && codePoint <= 0x1F251) || + (0x20000 <= codePoint && codePoint <= 0x2F73F) || + (0x2B740 <= codePoint && codePoint <= 0x2FFFD) || + (0x30000 <= codePoint && codePoint <= 0x3FFFD)) { + return 'W'; + } + if ((0x0020 <= codePoint && codePoint <= 0x007E) || + (0x00A2 <= codePoint && codePoint <= 0x00A3) || + (0x00A5 <= codePoint && codePoint <= 0x00A6) || + (0x00AC == codePoint) || + (0x00AF == codePoint) || + (0x27E6 <= codePoint && codePoint <= 0x27ED) || + (0x2985 <= codePoint && codePoint <= 0x2986)) { + return 'Na'; + } + if ((0x00A1 == codePoint) || + (0x00A4 == codePoint) || + (0x00A7 <= codePoint && codePoint <= 0x00A8) || + (0x00AA == codePoint) || + (0x00AD <= codePoint && codePoint <= 0x00AE) || + (0x00B0 <= codePoint && codePoint <= 0x00B4) || + (0x00B6 <= codePoint && codePoint <= 0x00BA) || + (0x00BC <= codePoint && codePoint <= 0x00BF) || + (0x00C6 == codePoint) || + (0x00D0 == codePoint) || + (0x00D7 <= codePoint && codePoint <= 0x00D8) || + (0x00DE <= codePoint && codePoint <= 0x00E1) || + (0x00E6 == codePoint) || + (0x00E8 <= codePoint && codePoint <= 0x00EA) || + (0x00EC <= codePoint && codePoint <= 0x00ED) || + (0x00F0 == codePoint) || + (0x00F2 <= codePoint && codePoint <= 0x00F3) || + (0x00F7 <= codePoint && codePoint <= 0x00FA) || + (0x00FC == codePoint) || + (0x00FE == codePoint) || + (0x0101 == codePoint) || + (0x0111 == codePoint) || + (0x0113 == codePoint) || + (0x011B == codePoint) || + (0x0126 <= codePoint && codePoint <= 0x0127) || + (0x012B == codePoint) || + (0x0131 <= codePoint && codePoint <= 0x0133) || + (0x0138 == codePoint) || + (0x013F <= codePoint && codePoint <= 0x0142) || + (0x0144 == codePoint) || + (0x0148 <= codePoint && codePoint <= 0x014B) || + (0x014D == codePoint) || + (0x0152 <= codePoint && codePoint <= 0x0153) || + (0x0166 <= codePoint && codePoint <= 0x0167) || + (0x016B == codePoint) || + (0x01CE == codePoint) || + (0x01D0 == codePoint) || + (0x01D2 == codePoint) || + (0x01D4 == codePoint) || + (0x01D6 == codePoint) || + (0x01D8 == codePoint) || + (0x01DA == codePoint) || + (0x01DC == codePoint) || + (0x0251 == codePoint) || + (0x0261 == codePoint) || + (0x02C4 == codePoint) || + (0x02C7 == codePoint) || + (0x02C9 <= codePoint && codePoint <= 0x02CB) || + (0x02CD == codePoint) || + (0x02D0 == codePoint) || + (0x02D8 <= codePoint && codePoint <= 0x02DB) || + (0x02DD == codePoint) || + (0x02DF == codePoint) || + (0x0300 <= codePoint && codePoint <= 0x036F) || + (0x0391 <= codePoint && codePoint <= 0x03A1) || + (0x03A3 <= codePoint && codePoint <= 0x03A9) || + (0x03B1 <= codePoint && codePoint <= 0x03C1) || + (0x03C3 <= codePoint && codePoint <= 0x03C9) || + (0x0401 == codePoint) || + (0x0410 <= codePoint && codePoint <= 0x044F) || + (0x0451 == codePoint) || + (0x2010 == codePoint) || + (0x2013 <= codePoint && codePoint <= 0x2016) || + (0x2018 <= codePoint && codePoint <= 0x2019) || + (0x201C <= codePoint && codePoint <= 0x201D) || + (0x2020 <= codePoint && codePoint <= 0x2022) || + (0x2024 <= codePoint && codePoint <= 0x2027) || + (0x2030 == codePoint) || + (0x2032 <= codePoint && codePoint <= 0x2033) || + (0x2035 == codePoint) || + (0x203B == codePoint) || + (0x203E == codePoint) || + (0x2074 == codePoint) || + (0x207F == codePoint) || + (0x2081 <= codePoint && codePoint <= 0x2084) || + (0x20AC == codePoint) || + (0x2103 == codePoint) || + (0x2105 == codePoint) || + (0x2109 == codePoint) || + (0x2113 == codePoint) || + (0x2116 == codePoint) || + (0x2121 <= codePoint && codePoint <= 0x2122) || + (0x2126 == codePoint) || + (0x212B == codePoint) || + (0x2153 <= codePoint && codePoint <= 0x2154) || + (0x215B <= codePoint && codePoint <= 0x215E) || + (0x2160 <= codePoint && codePoint <= 0x216B) || + (0x2170 <= codePoint && codePoint <= 0x2179) || + (0x2189 == codePoint) || + (0x2190 <= codePoint && codePoint <= 0x2199) || + (0x21B8 <= codePoint && codePoint <= 0x21B9) || + (0x21D2 == codePoint) || + (0x21D4 == codePoint) || + (0x21E7 == codePoint) || + (0x2200 == codePoint) || + (0x2202 <= codePoint && codePoint <= 0x2203) || + (0x2207 <= codePoint && codePoint <= 0x2208) || + (0x220B == codePoint) || + (0x220F == codePoint) || + (0x2211 == codePoint) || + (0x2215 == codePoint) || + (0x221A == codePoint) || + (0x221D <= codePoint && codePoint <= 0x2220) || + (0x2223 == codePoint) || + (0x2225 == codePoint) || + (0x2227 <= codePoint && codePoint <= 0x222C) || + (0x222E == codePoint) || + (0x2234 <= codePoint && codePoint <= 0x2237) || + (0x223C <= codePoint && codePoint <= 0x223D) || + (0x2248 == codePoint) || + (0x224C == codePoint) || + (0x2252 == codePoint) || + (0x2260 <= codePoint && codePoint <= 0x2261) || + (0x2264 <= codePoint && codePoint <= 0x2267) || + (0x226A <= codePoint && codePoint <= 0x226B) || + (0x226E <= codePoint && codePoint <= 0x226F) || + (0x2282 <= codePoint && codePoint <= 0x2283) || + (0x2286 <= codePoint && codePoint <= 0x2287) || + (0x2295 == codePoint) || + (0x2299 == codePoint) || + (0x22A5 == codePoint) || + (0x22BF == codePoint) || + (0x2312 == codePoint) || + (0x2460 <= codePoint && codePoint <= 0x24E9) || + (0x24EB <= codePoint && codePoint <= 0x254B) || + (0x2550 <= codePoint && codePoint <= 0x2573) || + (0x2580 <= codePoint && codePoint <= 0x258F) || + (0x2592 <= codePoint && codePoint <= 0x2595) || + (0x25A0 <= codePoint && codePoint <= 0x25A1) || + (0x25A3 <= codePoint && codePoint <= 0x25A9) || + (0x25B2 <= codePoint && codePoint <= 0x25B3) || + (0x25B6 <= codePoint && codePoint <= 0x25B7) || + (0x25BC <= codePoint && codePoint <= 0x25BD) || + (0x25C0 <= codePoint && codePoint <= 0x25C1) || + (0x25C6 <= codePoint && codePoint <= 0x25C8) || + (0x25CB == codePoint) || + (0x25CE <= codePoint && codePoint <= 0x25D1) || + (0x25E2 <= codePoint && codePoint <= 0x25E5) || + (0x25EF == codePoint) || + (0x2605 <= codePoint && codePoint <= 0x2606) || + (0x2609 == codePoint) || + (0x260E <= codePoint && codePoint <= 0x260F) || + (0x2614 <= codePoint && codePoint <= 0x2615) || + (0x261C == codePoint) || + (0x261E == codePoint) || + (0x2640 == codePoint) || + (0x2642 == codePoint) || + (0x2660 <= codePoint && codePoint <= 0x2661) || + (0x2663 <= codePoint && codePoint <= 0x2665) || + (0x2667 <= codePoint && codePoint <= 0x266A) || + (0x266C <= codePoint && codePoint <= 0x266D) || + (0x266F == codePoint) || + (0x269E <= codePoint && codePoint <= 0x269F) || + (0x26BE <= codePoint && codePoint <= 0x26BF) || + (0x26C4 <= codePoint && codePoint <= 0x26CD) || + (0x26CF <= codePoint && codePoint <= 0x26E1) || + (0x26E3 == codePoint) || + (0x26E8 <= codePoint && codePoint <= 0x26FF) || + (0x273D == codePoint) || + (0x2757 == codePoint) || + (0x2776 <= codePoint && codePoint <= 0x277F) || + (0x2B55 <= codePoint && codePoint <= 0x2B59) || + (0x3248 <= codePoint && codePoint <= 0x324F) || + (0xE000 <= codePoint && codePoint <= 0xF8FF) || + (0xFE00 <= codePoint && codePoint <= 0xFE0F) || + (0xFFFD == codePoint) || + (0x1F100 <= codePoint && codePoint <= 0x1F10A) || + (0x1F110 <= codePoint && codePoint <= 0x1F12D) || + (0x1F130 <= codePoint && codePoint <= 0x1F169) || + (0x1F170 <= codePoint && codePoint <= 0x1F19A) || + (0xE0100 <= codePoint && codePoint <= 0xE01EF) || + (0xF0000 <= codePoint && codePoint <= 0xFFFFD) || + (0x100000 <= codePoint && codePoint <= 0x10FFFD)) { + return 'A'; + } + + return 'N'; + }; + + eaw.characterLength = function(character) { + var code = this.eastAsianWidth(character); + if (code == 'F' || code == 'W' || code == 'A') { + return 2; + } else { + return 1; + } + }; + + // Split a string considering surrogate-pairs. + function stringToArray(string) { + return string.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]|[^\uD800-\uDFFF]/g) || []; + } + + eaw.length = function(string) { + var characters = stringToArray(string); + var len = 0; + for (var i = 0; i < characters.length; i++) { + len = len + this.characterLength(characters[i]); + } + return len; + }; + + eaw.slice = function(text, start, end) { + textLen = eaw.length(text); + start = start ? start : 0; + end = end ? end : 1; + if (start < 0) { + start = textLen + start; + } + if (end < 0) { + end = textLen + end; + } + var result = ''; + var eawLen = 0; + var chars = stringToArray(text); + for (var i = 0; i < chars.length; i++) { + var char = chars[i]; + var charLen = eaw.length(char); + if (eawLen >= start - (charLen == 2 ? 1 : 0)) { + if (eawLen + charLen <= end) { + result += char; + } else { + break; + } + } + eawLen += charLen; + } + return result; + }; +} (eastasianwidth)); + +var eastasianwidthExports = eastasianwidth.exports; +var eastAsianWidth = /*@__PURE__*/getDefaultExportFromCjs(eastasianwidthExports); + +var emojiRegex$4 = function () { + // https://mths.be/emoji + return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67)\uDB40\uDC7F|(?:\uD83E\uDDD1\uD83C\uDFFF\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFC-\uDFFF])|\uD83D\uDC68(?:\uD83C\uDFFB(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|[\u2695\u2696\u2708]\uFE0F|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))?|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])\uFE0F|\u200D(?:(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D[\uDC66\uDC67])|\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC)?|(?:\uD83D\uDC69(?:\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69]))|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC69(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83E\uDDD1(?:\u200D(?:\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDE36\u200D\uD83C\uDF2B|\uD83C\uDFF3\uFE0F\u200D\u26A7|\uD83D\uDC3B\u200D\u2744|(?:(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\uD83C\uDFF4\u200D\u2620|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])\u200D[\u2640\u2642]|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u2600-\u2604\u260E\u2611\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26B0\u26B1\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0\u26F1\u26F4\u26F7\u26F8\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u3030\u303D\u3297\u3299]|\uD83C[\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]|\uD83D[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3])\uFE0F|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDE35\u200D\uD83D\uDCAB|\uD83D\uDE2E\u200D\uD83D\uDCA8|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83E\uDDD1(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83D\uDC69(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF6\uD83C\uDDE6|\uD83C\uDDF4\uD83C\uDDF2|\uD83D\uDC08\u200D\u2B1B|\u2764\uFE0F\u200D(?:\uD83D\uDD25|\uD83E\uDE79)|\uD83D\uDC41\uFE0F|\uD83C\uDFF3\uFE0F|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|[#\*0-9]\uFE0F\u20E3|\u2764\uFE0F|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|\uD83C\uDFF4|(?:[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270C\u270D]|\uD83D[\uDD74\uDD90])(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC08\uDC15\uDC3B\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE2E\uDE35\uDE36\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5]|\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD]|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0D\uDD0E\uDD10-\uDD17\uDD1D\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78\uDD7A-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCB\uDDD0\uDDE0-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6]|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26A7\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5-\uDED7\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDD77\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g; +}; + +var emojiRegex$5 = /*@__PURE__*/getDefaultExportFromCjs(emojiRegex$4); + +function stringWidth$5(string, options = {}) { + if (typeof string !== 'string' || string.length === 0) { + return 0; + } + + options = { + ambiguousIsNarrow: true, + ...options + }; + + string = stripAnsi$5(string); + + if (string.length === 0) { + return 0; + } + + string = string.replace(emojiRegex$5(), ' '); + + const ambiguousCharacterWidth = options.ambiguousIsNarrow ? 1 : 2; + let width = 0; + + for (const character of string) { + const codePoint = character.codePointAt(0); + + // Ignore control characters + if (codePoint <= 0x1F || (codePoint >= 0x7F && codePoint <= 0x9F)) { + continue; + } + + // Ignore combining characters + if (codePoint >= 0x300 && codePoint <= 0x36F) { + continue; + } + + const code = eastAsianWidth.eastAsianWidth(character); + switch (code) { + case 'F': + case 'W': + width += 2; + break; + case 'A': + width += ambiguousCharacterWidth; + break; + default: + width += 1; + } + } + + return width; +} + +function widestLine(string) { + let lineWidth = 0; + + for (const line of string.split('\n')) { + lineWidth = Math.max(lineWidth, stringWidth$5(line)); + } + + return lineWidth; +} + +var cliBoxes$2 = {exports: {}}; + +var single = { + topLeft: "┌", + top: "─", + topRight: "┐", + right: "│", + bottomRight: "┘", + bottom: "─", + bottomLeft: "└", + left: "│" +}; +var double = { + topLeft: "╔", + top: "═", + topRight: "╗", + right: "║", + bottomRight: "╝", + bottom: "═", + bottomLeft: "╚", + left: "║" +}; +var round = { + topLeft: "╭", + top: "─", + topRight: "╮", + right: "│", + bottomRight: "╯", + bottom: "─", + bottomLeft: "╰", + left: "│" +}; +var bold = { + topLeft: "┏", + top: "━", + topRight: "┓", + right: "┃", + bottomRight: "┛", + bottom: "━", + bottomLeft: "┗", + left: "┃" +}; +var singleDouble = { + topLeft: "╓", + top: "─", + topRight: "╖", + right: "║", + bottomRight: "╜", + bottom: "─", + bottomLeft: "╙", + left: "║" +}; +var doubleSingle = { + topLeft: "╒", + top: "═", + topRight: "╕", + right: "│", + bottomRight: "╛", + bottom: "═", + bottomLeft: "╘", + left: "│" +}; +var classic = { + topLeft: "+", + top: "-", + topRight: "+", + right: "|", + bottomRight: "+", + bottom: "-", + bottomLeft: "+", + left: "|" +}; +var arrow$1 = { + topLeft: "↘", + top: "↓", + topRight: "↙", + right: "←", + bottomRight: "↖", + bottom: "↑", + bottomLeft: "↗", + left: "→" +}; +var require$$0$6 = { + single: single, + double: double, + round: round, + bold: bold, + singleDouble: singleDouble, + doubleSingle: doubleSingle, + classic: classic, + arrow: arrow$1 +}; + +const cliBoxes = require$$0$6; + +cliBoxes$2.exports = cliBoxes; +// TODO: Remove this for the next major release +cliBoxes$2.exports.default = cliBoxes; + +var cliBoxesExports = cliBoxes$2.exports; +var cliBoxes$1 = /*@__PURE__*/getDefaultExportFromCjs(cliBoxesExports); + +const UPPERCASE = /[\p{Lu}]/u; +const LOWERCASE = /[\p{Ll}]/u; +const LEADING_CAPITAL = /^[\p{Lu}](?![\p{Lu}])/gu; +const IDENTIFIER = /([\p{Alpha}\p{N}_]|$)/u; +const SEPARATORS = /[_.\- ]+/; + +const LEADING_SEPARATORS = new RegExp('^' + SEPARATORS.source); +const SEPARATORS_AND_IDENTIFIER = new RegExp(SEPARATORS.source + IDENTIFIER.source, 'gu'); +const NUMBERS_AND_IDENTIFIER = new RegExp('\\d+' + IDENTIFIER.source, 'gu'); + +const preserveCamelCase = (string, toLowerCase, toUpperCase, preserveConsecutiveUppercase) => { + let isLastCharLower = false; + let isLastCharUpper = false; + let isLastLastCharUpper = false; + let isLastLastCharPreserved = false; + + for (let index = 0; index < string.length; index++) { + const character = string[index]; + isLastLastCharPreserved = index > 2 ? string[index - 3] === '-' : true; + + if (isLastCharLower && UPPERCASE.test(character)) { + string = string.slice(0, index) + '-' + string.slice(index); + isLastCharLower = false; + isLastLastCharUpper = isLastCharUpper; + isLastCharUpper = true; + index++; + } else if (isLastCharUpper && isLastLastCharUpper && LOWERCASE.test(character) && (!isLastLastCharPreserved || preserveConsecutiveUppercase)) { + string = string.slice(0, index - 1) + '-' + string.slice(index - 1); + isLastLastCharUpper = isLastCharUpper; + isLastCharUpper = false; + isLastCharLower = true; + } else { + isLastCharLower = toLowerCase(character) === character && toUpperCase(character) !== character; + isLastLastCharUpper = isLastCharUpper; + isLastCharUpper = toUpperCase(character) === character && toLowerCase(character) !== character; + } + } + + return string; +}; + +const preserveConsecutiveUppercase = (input, toLowerCase) => { + LEADING_CAPITAL.lastIndex = 0; + + return input.replace(LEADING_CAPITAL, m1 => toLowerCase(m1)); +}; + +const postProcess = (input, toUpperCase) => { + SEPARATORS_AND_IDENTIFIER.lastIndex = 0; + NUMBERS_AND_IDENTIFIER.lastIndex = 0; + + return input.replace(SEPARATORS_AND_IDENTIFIER, (_, identifier) => toUpperCase(identifier)) + .replace(NUMBERS_AND_IDENTIFIER, m => toUpperCase(m)); +}; + +function camelCase$3(input, options) { + if (!(typeof input === 'string' || Array.isArray(input))) { + throw new TypeError('Expected the input to be `string | string[]`'); + } + + options = { + pascalCase: false, + preserveConsecutiveUppercase: false, + ...options, + }; + + if (Array.isArray(input)) { + input = input.map(x => x.trim()) + .filter(x => x.length) + .join('-'); + } else { + input = input.trim(); + } + + if (input.length === 0) { + return ''; + } + + const toLowerCase = options.locale === false + ? string => string.toLowerCase() + : string => string.toLocaleLowerCase(options.locale); + + const toUpperCase = options.locale === false + ? string => string.toUpperCase() + : string => string.toLocaleUpperCase(options.locale); + + if (input.length === 1) { + if (SEPARATORS.test(input)) { + return ''; + } + + return options.pascalCase ? toUpperCase(input) : toLowerCase(input); + } + + const hasUpperCase = input !== toLowerCase(input); + + if (hasUpperCase) { + input = preserveCamelCase(input, toLowerCase, toUpperCase, options.preserveConsecutiveUppercase); + } + + input = input.replace(LEADING_SEPARATORS, ''); + input = options.preserveConsecutiveUppercase ? preserveConsecutiveUppercase(input, toLowerCase) : toLowerCase(input); + + if (options.pascalCase) { + input = toUpperCase(input.charAt(0)) + input.slice(1); + } + + return postProcess(input, toUpperCase); +} + +var stringWidth$4 = {exports: {}}; + +var ansiRegex$3 = ({onlyFirst = false} = {}) => { + const pattern = [ + '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)', + '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))' + ].join('|'); + + return new RegExp(pattern, onlyFirst ? undefined : 'g'); +}; + +const ansiRegex$2 = ansiRegex$3; + +var stripAnsi$4 = string => typeof string === 'string' ? string.replace(ansiRegex$2(), '') : string; + +var isFullwidthCodePoint$4 = {exports: {}}; + +/* eslint-disable yoda */ + +const isFullwidthCodePoint$3 = codePoint => { + if (Number.isNaN(codePoint)) { + return false; + } + + // Code points are derived from: + // http://www.unix.org/Public/UNIDATA/EastAsianWidth.txt + if ( + codePoint >= 0x1100 && ( + codePoint <= 0x115F || // Hangul Jamo + codePoint === 0x2329 || // LEFT-POINTING ANGLE BRACKET + codePoint === 0x232A || // RIGHT-POINTING ANGLE BRACKET + // CJK Radicals Supplement .. Enclosed CJK Letters and Months + (0x2E80 <= codePoint && codePoint <= 0x3247 && codePoint !== 0x303F) || + // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A + (0x3250 <= codePoint && codePoint <= 0x4DBF) || + // CJK Unified Ideographs .. Yi Radicals + (0x4E00 <= codePoint && codePoint <= 0xA4C6) || + // Hangul Jamo Extended-A + (0xA960 <= codePoint && codePoint <= 0xA97C) || + // Hangul Syllables + (0xAC00 <= codePoint && codePoint <= 0xD7A3) || + // CJK Compatibility Ideographs + (0xF900 <= codePoint && codePoint <= 0xFAFF) || + // Vertical Forms + (0xFE10 <= codePoint && codePoint <= 0xFE19) || + // CJK Compatibility Forms .. Small Form Variants + (0xFE30 <= codePoint && codePoint <= 0xFE6B) || + // Halfwidth and Fullwidth Forms + (0xFF01 <= codePoint && codePoint <= 0xFF60) || + (0xFFE0 <= codePoint && codePoint <= 0xFFE6) || + // Kana Supplement + (0x1B000 <= codePoint && codePoint <= 0x1B001) || + // Enclosed Ideographic Supplement + (0x1F200 <= codePoint && codePoint <= 0x1F251) || + // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane + (0x20000 <= codePoint && codePoint <= 0x3FFFD) + ) + ) { + return true; + } + + return false; +}; + +isFullwidthCodePoint$4.exports = isFullwidthCodePoint$3; +isFullwidthCodePoint$4.exports.default = isFullwidthCodePoint$3; + +var isFullwidthCodePointExports = isFullwidthCodePoint$4.exports; + +var emojiRegex$3 = function () { + // https://mths.be/emoji + return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83C\uDFF4\u200D\u2620)\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF4\uD83C\uDDF2|\uD83C\uDDF6\uD83C\uDDE6|[#\*0-9]\uFE0F\u20E3|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g; +}; + +const stripAnsi$3 = stripAnsi$4; +const isFullwidthCodePoint$2 = isFullwidthCodePointExports; +const emojiRegex$2 = emojiRegex$3; + +const stringWidth$3 = string => { + if (typeof string !== 'string' || string.length === 0) { + return 0; + } + + string = stripAnsi$3(string); + + if (string.length === 0) { + return 0; + } + + string = string.replace(emojiRegex$2(), ' '); + + let width = 0; + + for (let i = 0; i < string.length; i++) { + const code = string.codePointAt(i); + + // Ignore control characters + if (code <= 0x1F || (code >= 0x7F && code <= 0x9F)) { + continue; + } + + // Ignore combining characters + if (code >= 0x300 && code <= 0x36F) { + continue; + } + + // Surrogates + if (code > 0xFFFF) { + i++; + } + + width += isFullwidthCodePoint$2(code) ? 2 : 1; + } + + return width; +}; + +stringWidth$4.exports = stringWidth$3; +// TODO: remove this in the next major version +stringWidth$4.exports.default = stringWidth$3; + +var stringWidthExports$1 = stringWidth$4.exports; + +const stringWidth$2 = stringWidthExports$1; + +function ansiAlign (text, opts) { + if (!text) return text + + opts = opts || {}; + const align = opts.align || 'center'; + + // short-circuit `align: 'left'` as no-op + if (align === 'left') return text + + const split = opts.split || '\n'; + const pad = opts.pad || ' '; + const widthDiffFn = align !== 'right' ? halfDiff : fullDiff; + + let returnString = false; + if (!Array.isArray(text)) { + returnString = true; + text = String(text).split(split); + } + + let width; + let maxWidth = 0; + text = text.map(function (str) { + str = String(str); + width = stringWidth$2(str); + maxWidth = Math.max(width, maxWidth); + return { + str, + width + } + }).map(function (obj) { + return new Array(widthDiffFn(maxWidth, obj.width) + 1).join(pad) + obj.str + }); + + return returnString ? text.join(split) : text +} + +ansiAlign.left = function left (text) { + return ansiAlign(text, { align: 'left' }) +}; + +ansiAlign.center = function center (text) { + return ansiAlign(text, { align: 'center' }) +}; + +ansiAlign.right = function right (text) { + return ansiAlign(text, { align: 'right' }) +}; + +var ansiAlign_1 = ansiAlign; + +function halfDiff (maxWidth, curWidth) { + return Math.floor((maxWidth - curWidth) / 2) +} + +function fullDiff (maxWidth, curWidth) { + return maxWidth - curWidth +} + +var ansiAlign$1 = /*@__PURE__*/getDefaultExportFromCjs(ansiAlign_1); + +function ansiRegex$1({onlyFirst = false} = {}) { + const pattern = [ + '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)', + '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))' + ].join('|'); + + return new RegExp(pattern, onlyFirst ? undefined : 'g'); +} + +const regex$2 = ansiRegex$1(); + +function stripAnsi$2(string) { + if (typeof string !== 'string') { + throw new TypeError(`Expected a \`string\`, got \`${typeof string}\``); + } + + // Even though the regex is global, we don't need to reset the `.lastIndex` + // because unlike `.exec()` and `.test()`, `.replace()` does it automatically + // and doing it manually has a performance penalty. + return string.replace(regex$2, ''); +} + +const ANSI_BACKGROUND_OFFSET = 10; + +const wrapAnsi16 = (offset = 0) => code => `\u001B[${code + offset}m`; + +const wrapAnsi256 = (offset = 0) => code => `\u001B[${38 + offset};5;${code}m`; + +const wrapAnsi16m = (offset = 0) => (red, green, blue) => `\u001B[${38 + offset};2;${red};${green};${blue}m`; + +const styles$1 = { + modifier: { + reset: [0, 0], + // 21 isn't widely supported and 22 does the same thing + bold: [1, 22], + dim: [2, 22], + italic: [3, 23], + underline: [4, 24], + overline: [53, 55], + inverse: [7, 27], + hidden: [8, 28], + strikethrough: [9, 29], + }, + color: { + black: [30, 39], + red: [31, 39], + green: [32, 39], + yellow: [33, 39], + blue: [34, 39], + magenta: [35, 39], + cyan: [36, 39], + white: [37, 39], + + // Bright color + blackBright: [90, 39], + gray: [90, 39], // Alias of `blackBright` + grey: [90, 39], // Alias of `blackBright` + redBright: [91, 39], + greenBright: [92, 39], + yellowBright: [93, 39], + blueBright: [94, 39], + magentaBright: [95, 39], + cyanBright: [96, 39], + whiteBright: [97, 39], + }, + bgColor: { + bgBlack: [40, 49], + bgRed: [41, 49], + bgGreen: [42, 49], + bgYellow: [43, 49], + bgBlue: [44, 49], + bgMagenta: [45, 49], + bgCyan: [46, 49], + bgWhite: [47, 49], + + // Bright color + bgBlackBright: [100, 49], + bgGray: [100, 49], // Alias of `bgBlackBright` + bgGrey: [100, 49], // Alias of `bgBlackBright` + bgRedBright: [101, 49], + bgGreenBright: [102, 49], + bgYellowBright: [103, 49], + bgBlueBright: [104, 49], + bgMagentaBright: [105, 49], + bgCyanBright: [106, 49], + bgWhiteBright: [107, 49], + }, +}; + +Object.keys(styles$1.modifier); +const foregroundColorNames = Object.keys(styles$1.color); +const backgroundColorNames = Object.keys(styles$1.bgColor); +[...foregroundColorNames, ...backgroundColorNames]; + +function assembleStyles() { + const codes = new Map(); + + for (const [groupName, group] of Object.entries(styles$1)) { + for (const [styleName, style] of Object.entries(group)) { + styles$1[styleName] = { + open: `\u001B[${style[0]}m`, + close: `\u001B[${style[1]}m`, + }; + + group[styleName] = styles$1[styleName]; + + codes.set(style[0], style[1]); + } + + Object.defineProperty(styles$1, groupName, { + value: group, + enumerable: false, + }); + } + + Object.defineProperty(styles$1, 'codes', { + value: codes, + enumerable: false, + }); + + styles$1.color.close = '\u001B[39m'; + styles$1.bgColor.close = '\u001B[49m'; + + styles$1.color.ansi = wrapAnsi16(); + styles$1.color.ansi256 = wrapAnsi256(); + styles$1.color.ansi16m = wrapAnsi16m(); + styles$1.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET); + styles$1.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET); + styles$1.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET); + + // From https://github.com/Qix-/color-convert/blob/3f0e0d4e92e235796ccb17f6e85c72094a651f49/conversions.js + Object.defineProperties(styles$1, { + rgbToAnsi256: { + value: (red, green, blue) => { + // We use the extended greyscale palette here, with the exception of + // black and white. normal palette only has 4 greyscale shades. + if (red === green && green === blue) { + if (red < 8) { + return 16; + } + + if (red > 248) { + return 231; + } + + return Math.round(((red - 8) / 247) * 24) + 232; + } + + return 16 + + (36 * Math.round(red / 255 * 5)) + + (6 * Math.round(green / 255 * 5)) + + Math.round(blue / 255 * 5); + }, + enumerable: false, + }, + hexToRgb: { + value: hex => { + const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16)); + if (!matches) { + return [0, 0, 0]; + } + + let [colorString] = matches; + + if (colorString.length === 3) { + colorString = [...colorString].map(character => character + character).join(''); + } + + const integer = Number.parseInt(colorString, 16); + + return [ + /* eslint-disable no-bitwise */ + (integer >> 16) & 0xFF, + (integer >> 8) & 0xFF, + integer & 0xFF, + /* eslint-enable no-bitwise */ + ]; + }, + enumerable: false, + }, + hexToAnsi256: { + value: hex => styles$1.rgbToAnsi256(...styles$1.hexToRgb(hex)), + enumerable: false, + }, + ansi256ToAnsi: { + value: code => { + if (code < 8) { + return 30 + code; + } + + if (code < 16) { + return 90 + (code - 8); + } + + let red; + let green; + let blue; + + if (code >= 232) { + red = (((code - 232) * 10) + 8) / 255; + green = red; + blue = red; + } else { + code -= 16; + + const remainder = code % 36; + + red = Math.floor(code / 36) / 5; + green = Math.floor(remainder / 6) / 5; + blue = (remainder % 6) / 5; + } + + const value = Math.max(red, green, blue) * 2; + + if (value === 0) { + return 30; + } + + // eslint-disable-next-line no-bitwise + let result = 30 + ((Math.round(blue) << 2) | (Math.round(green) << 1) | Math.round(red)); + + if (value === 2) { + result += 60; + } + + return result; + }, + enumerable: false, + }, + rgbToAnsi: { + value: (red, green, blue) => styles$1.ansi256ToAnsi(styles$1.rgbToAnsi256(red, green, blue)), + enumerable: false, + }, + hexToAnsi: { + value: hex => styles$1.ansi256ToAnsi(styles$1.hexToAnsi256(hex)), + enumerable: false, + }, + }); + + return styles$1; +} + +const ansiStyles$7 = assembleStyles(); + +const ESCAPES$2 = new Set([ + '\u001B', + '\u009B', +]); + +const END_CODE = 39; +const ANSI_ESCAPE_BELL = '\u0007'; +const ANSI_CSI = '['; +const ANSI_OSC = ']'; +const ANSI_SGR_TERMINATOR = 'm'; +const ANSI_ESCAPE_LINK = `${ANSI_OSC}8;;`; + +const wrapAnsiCode = code => `${ESCAPES$2.values().next().value}${ANSI_CSI}${code}${ANSI_SGR_TERMINATOR}`; +const wrapAnsiHyperlink = uri => `${ESCAPES$2.values().next().value}${ANSI_ESCAPE_LINK}${uri}${ANSI_ESCAPE_BELL}`; + +// Calculate the length of words split on ' ', ignoring +// the extra characters added by ansi escape codes +const wordLengths = string => string.split(' ').map(character => stringWidth$5(character)); + +// Wrap a long word across multiple rows +// Ansi escape codes do not count towards length +const wrapWord$2 = (rows, word, columns) => { + const characters = [...word]; + + let isInsideEscape = false; + let isInsideLinkEscape = false; + let visible = stringWidth$5(stripAnsi$2(rows[rows.length - 1])); + + for (const [index, character] of characters.entries()) { + const characterLength = stringWidth$5(character); + + if (visible + characterLength <= columns) { + rows[rows.length - 1] += character; + } else { + rows.push(character); + visible = 0; + } + + if (ESCAPES$2.has(character)) { + isInsideEscape = true; + isInsideLinkEscape = characters.slice(index + 1).join('').startsWith(ANSI_ESCAPE_LINK); + } + + if (isInsideEscape) { + if (isInsideLinkEscape) { + if (character === ANSI_ESCAPE_BELL) { + isInsideEscape = false; + isInsideLinkEscape = false; + } + } else if (character === ANSI_SGR_TERMINATOR) { + isInsideEscape = false; + } + + continue; + } + + visible += characterLength; + + if (visible === columns && index < characters.length - 1) { + rows.push(''); + visible = 0; + } + } + + // It's possible that the last row we copy over is only + // ansi escape characters, handle this edge-case + if (!visible && rows[rows.length - 1].length > 0 && rows.length > 1) { + rows[rows.length - 2] += rows.pop(); + } +}; + +// Trims spaces from a string ignoring invisible sequences +const stringVisibleTrimSpacesRight = string => { + const words = string.split(' '); + let last = words.length; + + while (last > 0) { + if (stringWidth$5(words[last - 1]) > 0) { + break; + } + + last--; + } + + if (last === words.length) { + return string; + } + + return words.slice(0, last).join(' ') + words.slice(last).join(''); +}; + +// The wrap-ansi module can be invoked in either 'hard' or 'soft' wrap mode +// +// 'hard' will never allow a string to take up more than columns characters +// +// 'soft' allows long words to expand past the column length +const exec = (string, columns, options = {}) => { + if (options.trim !== false && string.trim() === '') { + return ''; + } + + let returnValue = ''; + let escapeCode; + let escapeUrl; + + const lengths = wordLengths(string); + let rows = ['']; + + for (const [index, word] of string.split(' ').entries()) { + if (options.trim !== false) { + rows[rows.length - 1] = rows[rows.length - 1].trimStart(); + } + + let rowLength = stringWidth$5(rows[rows.length - 1]); + + if (index !== 0) { + if (rowLength >= columns && (options.wordWrap === false || options.trim === false)) { + // If we start with a new word but the current row length equals the length of the columns, add a new row + rows.push(''); + rowLength = 0; + } + + if (rowLength > 0 || options.trim === false) { + rows[rows.length - 1] += ' '; + rowLength++; + } + } + + // In 'hard' wrap mode, the length of a line is never allowed to extend past 'columns' + if (options.hard && lengths[index] > columns) { + const remainingColumns = (columns - rowLength); + const breaksStartingThisLine = 1 + Math.floor((lengths[index] - remainingColumns - 1) / columns); + const breaksStartingNextLine = Math.floor((lengths[index] - 1) / columns); + if (breaksStartingNextLine < breaksStartingThisLine) { + rows.push(''); + } + + wrapWord$2(rows, word, columns); + continue; + } + + if (rowLength + lengths[index] > columns && rowLength > 0 && lengths[index] > 0) { + if (options.wordWrap === false && rowLength < columns) { + wrapWord$2(rows, word, columns); + continue; + } + + rows.push(''); + } + + if (rowLength + lengths[index] > columns && options.wordWrap === false) { + wrapWord$2(rows, word, columns); + continue; + } + + rows[rows.length - 1] += word; + } + + if (options.trim !== false) { + rows = rows.map(row => stringVisibleTrimSpacesRight(row)); + } + + const pre = [...rows.join('\n')]; + + for (const [index, character] of pre.entries()) { + returnValue += character; + + if (ESCAPES$2.has(character)) { + const {groups} = new RegExp(`(?:\\${ANSI_CSI}(?\\d+)m|\\${ANSI_ESCAPE_LINK}(?.*)${ANSI_ESCAPE_BELL})`).exec(pre.slice(index).join('')) || {groups: {}}; + if (groups.code !== undefined) { + const code = Number.parseFloat(groups.code); + escapeCode = code === END_CODE ? undefined : code; + } else if (groups.uri !== undefined) { + escapeUrl = groups.uri.length === 0 ? undefined : groups.uri; + } + } + + const code = ansiStyles$7.codes.get(Number(escapeCode)); + + if (pre[index + 1] === '\n') { + if (escapeUrl) { + returnValue += wrapAnsiHyperlink(''); + } + + if (escapeCode && code) { + returnValue += wrapAnsiCode(code); + } + } else if (character === '\n') { + if (escapeCode && code) { + returnValue += wrapAnsiCode(escapeCode); + } + + if (escapeUrl) { + returnValue += wrapAnsiHyperlink(escapeUrl); + } + } + } + + return returnValue; +}; + +// For each newline, invoke the method separately +function wrapAnsi$1(string, columns, options) { + return String(string) + .normalize() + .replace(/\r\n/g, '\n') + .split('\n') + .map(line => exec(line, columns, options)) + .join('\n'); +} + +const NEWLINE = '\n'; +const PAD = ' '; +const NONE = 'none'; + +const terminalColumns = () => { + const {env, stdout, stderr} = process$3; + + if (stdout?.columns) { + return stdout.columns; + } + + if (stderr?.columns) { + return stderr.columns; + } + + if (env.COLUMNS) { + return Number.parseInt(env.COLUMNS, 10); + } + + return 80; +}; + +const getObject = detail => typeof detail === 'number' ? { + top: detail, + right: detail * 3, + bottom: detail, + left: detail * 3, +} : { + top: 0, + right: 0, + bottom: 0, + left: 0, + ...detail, +}; + +const getBorderWidth = borderStyle => borderStyle === NONE ? 0 : 2; + +const getBorderChars = borderStyle => { + const sides = [ + 'topLeft', + 'topRight', + 'bottomRight', + 'bottomLeft', + 'left', + 'right', + 'top', + 'bottom', + ]; + + let characters; + + // Create empty border style + if (borderStyle === NONE) { + borderStyle = {}; + for (const side of sides) { + borderStyle[side] = ''; + } + } + + if (typeof borderStyle === 'string') { + characters = cliBoxes$1[borderStyle]; + + if (!characters) { + throw new TypeError(`Invalid border style: ${borderStyle}`); + } + } else { + // Ensure retro-compatibility + if (typeof borderStyle?.vertical === 'string') { + borderStyle.left = borderStyle.vertical; + borderStyle.right = borderStyle.vertical; + } + + // Ensure retro-compatibility + if (typeof borderStyle?.horizontal === 'string') { + borderStyle.top = borderStyle.horizontal; + borderStyle.bottom = borderStyle.horizontal; + } + + for (const side of sides) { + if (borderStyle[side] === null || typeof borderStyle[side] !== 'string') { + throw new TypeError(`Invalid border style: ${side}`); + } + } + + characters = borderStyle; + } + + return characters; +}; + +const makeTitle = (text, horizontal, alignment) => { + let title = ''; + + const textWidth = stringWidth$5(text); + + switch (alignment) { + case 'left': { + title = text + horizontal.slice(textWidth); + break; + } + + case 'right': { + title = horizontal.slice(textWidth) + text; + break; + } + + default: { + horizontal = horizontal.slice(textWidth); + + if (horizontal.length % 2 === 1) { // This is needed in case the length is odd + horizontal = horizontal.slice(Math.floor(horizontal.length / 2)); + title = horizontal.slice(1) + text + horizontal; // We reduce the left part of one character to avoid the bar to go beyond its limit + } else { + horizontal = horizontal.slice(horizontal.length / 2); + title = horizontal + text + horizontal; + } + + break; + } + } + + return title; +}; + +const makeContentText = (text, {padding, width, textAlignment, height}) => { + text = ansiAlign$1(text, {align: textAlignment}); + let lines = text.split(NEWLINE); + const textWidth = widestLine(text); + + const max = width - padding.left - padding.right; + + if (textWidth > max) { + const newLines = []; + for (const line of lines) { + const createdLines = wrapAnsi$1(line, max, {hard: true}); + const alignedLines = ansiAlign$1(createdLines, {align: textAlignment}); + const alignedLinesArray = alignedLines.split('\n'); + const longestLength = Math.max(...alignedLinesArray.map(s => stringWidth$5(s))); + + for (const alignedLine of alignedLinesArray) { + let paddedLine; + switch (textAlignment) { + case 'center': { + paddedLine = PAD.repeat((max - longestLength) / 2) + alignedLine; + break; + } + + case 'right': { + paddedLine = PAD.repeat(max - longestLength) + alignedLine; + break; + } + + default: { + paddedLine = alignedLine; + break; + } + } + + newLines.push(paddedLine); + } + } + + lines = newLines; + } + + if (textAlignment === 'center' && textWidth < max) { + lines = lines.map(line => PAD.repeat((max - textWidth) / 2) + line); + } else if (textAlignment === 'right' && textWidth < max) { + lines = lines.map(line => PAD.repeat(max - textWidth) + line); + } + + const paddingLeft = PAD.repeat(padding.left); + const paddingRight = PAD.repeat(padding.right); + + lines = lines.map(line => paddingLeft + line + paddingRight); + + lines = lines.map(line => { + if (width - stringWidth$5(line) > 0) { + switch (textAlignment) { + case 'center': { + return line + PAD.repeat(width - stringWidth$5(line)); + } + + case 'right': { + return line + PAD.repeat(width - stringWidth$5(line)); + } + + default: { + return line + PAD.repeat(width - stringWidth$5(line)); + } + } + } + + return line; + }); + + if (padding.top > 0) { + lines = [...Array.from({length: padding.top}).fill(PAD.repeat(width)), ...lines]; + } + + if (padding.bottom > 0) { + lines = [...lines, ...Array.from({length: padding.bottom}).fill(PAD.repeat(width))]; + } + + if (height && lines.length > height) { + lines = lines.slice(0, height); + } else if (height && lines.length < height) { + lines = [...lines, ...Array.from({length: height - lines.length}).fill(PAD.repeat(width))]; + } + + return lines.join(NEWLINE); +}; + +const boxContent = (content, contentWidth, options) => { + const colorizeBorder = border => { + const newBorder = options.borderColor ? getColorFn(options.borderColor)(border) : border; + return options.dimBorder ? chalk$5.dim(newBorder) : newBorder; + }; + + const colorizeContent = content => options.backgroundColor ? getBGColorFn(options.backgroundColor)(content) : content; + + const chars = getBorderChars(options.borderStyle); + const columns = terminalColumns(); + let marginLeft = PAD.repeat(options.margin.left); + + if (options.float === 'center') { + const marginWidth = Math.max((columns - contentWidth - getBorderWidth(options.borderStyle)) / 2, 0); + marginLeft = PAD.repeat(marginWidth); + } else if (options.float === 'right') { + const marginWidth = Math.max(columns - contentWidth - options.margin.right - getBorderWidth(options.borderStyle), 0); + marginLeft = PAD.repeat(marginWidth); + } + + let result = ''; + + if (options.margin.top) { + result += NEWLINE.repeat(options.margin.top); + } + + if (options.borderStyle !== NONE || options.title) { + result += colorizeBorder(marginLeft + chars.topLeft + (options.title ? makeTitle(options.title, chars.top.repeat(contentWidth), options.titleAlignment) : chars.top.repeat(contentWidth)) + chars.topRight) + NEWLINE; + } + + const lines = content.split(NEWLINE); + + result += lines.map(line => marginLeft + colorizeBorder(chars.left) + colorizeContent(line) + colorizeBorder(chars.right)).join(NEWLINE); + + if (options.borderStyle !== NONE) { + result += NEWLINE + colorizeBorder(marginLeft + chars.bottomLeft + chars.bottom.repeat(contentWidth) + chars.bottomRight); + } + + if (options.margin.bottom) { + result += NEWLINE.repeat(options.margin.bottom); + } + + return result; +}; + +const sanitizeOptions = options => { + // If fullscreen is enabled, max-out unspecified width/height + if (options.fullscreen && process$3?.stdout) { + let newDimensions = [process$3.stdout.columns, process$3.stdout.rows]; + + if (typeof options.fullscreen === 'function') { + newDimensions = options.fullscreen(...newDimensions); + } + + if (!options.width) { + options.width = newDimensions[0]; + } + + if (!options.height) { + options.height = newDimensions[1]; + } + } + + // If width is provided, make sure it's not below 1 + if (options.width) { + options.width = Math.max(1, options.width - getBorderWidth(options.borderStyle)); + } + + // If height is provided, make sure it's not below 1 + if (options.height) { + options.height = Math.max(1, options.height - getBorderWidth(options.borderStyle)); + } + + return options; +}; + +const formatTitle = (title, borderStyle) => borderStyle === NONE ? title : ` ${title} `; + +const determineDimensions = (text, options) => { + options = sanitizeOptions(options); + const widthOverride = options.width !== undefined; + const columns = terminalColumns(); + const borderWidth = getBorderWidth(options.borderStyle); + const maxWidth = columns - options.margin.left - options.margin.right - borderWidth; + + const widest = widestLine(wrapAnsi$1(text, columns - borderWidth, {hard: true, trim: false})) + options.padding.left + options.padding.right; + + // If title and width are provided, title adheres to fixed width + if (options.title && widthOverride) { + options.title = options.title.slice(0, Math.max(0, options.width - 2)); + if (options.title) { + options.title = formatTitle(options.title, options.borderStyle); + } + } else if (options.title) { + options.title = options.title.slice(0, Math.max(0, maxWidth - 2)); + + // Recheck if title isn't empty now + if (options.title) { + options.title = formatTitle(options.title, options.borderStyle); + // If the title is larger than content, box adheres to title width + if (stringWidth$5(options.title) > widest) { + options.width = stringWidth$5(options.title); + } + } + } + + // If fixed width is provided, use it or content width as reference + options.width = options.width ? options.width : widest; + + if (!widthOverride) { + if ((options.margin.left && options.margin.right) && options.width > maxWidth) { + // Let's assume we have margins: left = 3, right = 5, in total = 8 + const spaceForMargins = columns - options.width - borderWidth; + // Let's assume we have space = 4 + const multiplier = spaceForMargins / (options.margin.left + options.margin.right); + // Here: multiplier = 4/8 = 0.5 + options.margin.left = Math.max(0, Math.floor(options.margin.left * multiplier)); + options.margin.right = Math.max(0, Math.floor(options.margin.right * multiplier)); + // Left: 3 * 0.5 = 1.5 -> 1 + // Right: 6 * 0.5 = 3 + } + + // Re-cap width considering the margins after shrinking + options.width = Math.min(options.width, columns - borderWidth - options.margin.left - options.margin.right); + } + + // Prevent padding overflow + if (options.width - (options.padding.left + options.padding.right) <= 0) { + options.padding.left = 0; + options.padding.right = 0; + } + + if (options.height && options.height - (options.padding.top + options.padding.bottom) <= 0) { + options.padding.top = 0; + options.padding.bottom = 0; + } + + return options; +}; + +const isHex = color => color.match(/^#(?:[0-f]{3}){1,2}$/i); +const isColorValid = color => typeof color === 'string' && (chalk$5[color] ?? isHex(color)); +const getColorFn = color => isHex(color) ? chalk$5.hex(color) : chalk$5[color]; +const getBGColorFn = color => isHex(color) ? chalk$5.bgHex(color) : chalk$5[camelCase$3(['bg', color])]; + +function boxen(text, options) { + options = { + padding: 0, + borderStyle: 'single', + dimBorder: false, + textAlignment: 'left', + float: 'left', + titleAlignment: 'left', + ...options, + }; + + // This option is deprecated + if (options.align) { + options.textAlignment = options.align; + } + + if (options.borderColor && !isColorValid(options.borderColor)) { + throw new Error(`${options.borderColor} is not a valid borderColor`); + } + + if (options.backgroundColor && !isColorValid(options.backgroundColor)) { + throw new Error(`${options.backgroundColor} is not a valid backgroundColor`); + } + + options.padding = getObject(options.padding); + options.margin = getObject(options.margin); + + options = determineDimensions(text, options); + + text = makeContentText(text, options); + + return boxContent(text, options.width, options); +} + +var ciInfo = {}; + +var require$$0$5 = [ + { + name: "Appcircle", + constant: "APPCIRCLE", + env: "AC_APPCIRCLE" + }, + { + name: "AppVeyor", + constant: "APPVEYOR", + env: "APPVEYOR", + pr: "APPVEYOR_PULL_REQUEST_NUMBER" + }, + { + name: "AWS CodeBuild", + constant: "CODEBUILD", + env: "CODEBUILD_BUILD_ARN" + }, + { + name: "Azure Pipelines", + constant: "AZURE_PIPELINES", + env: "SYSTEM_TEAMFOUNDATIONCOLLECTIONURI", + pr: "SYSTEM_PULLREQUEST_PULLREQUESTID" + }, + { + name: "Bamboo", + constant: "BAMBOO", + env: "bamboo_planKey" + }, + { + name: "Bitbucket Pipelines", + constant: "BITBUCKET", + env: "BITBUCKET_COMMIT", + pr: "BITBUCKET_PR_ID" + }, + { + name: "Bitrise", + constant: "BITRISE", + env: "BITRISE_IO", + pr: "BITRISE_PULL_REQUEST" + }, + { + name: "Buddy", + constant: "BUDDY", + env: "BUDDY_WORKSPACE_ID", + pr: "BUDDY_EXECUTION_PULL_REQUEST_ID" + }, + { + name: "Buildkite", + constant: "BUILDKITE", + env: "BUILDKITE", + pr: { + env: "BUILDKITE_PULL_REQUEST", + ne: "false" + } + }, + { + name: "CircleCI", + constant: "CIRCLE", + env: "CIRCLECI", + pr: "CIRCLE_PULL_REQUEST" + }, + { + name: "Cirrus CI", + constant: "CIRRUS", + env: "CIRRUS_CI", + pr: "CIRRUS_PR" + }, + { + name: "Codefresh", + constant: "CODEFRESH", + env: "CF_BUILD_ID", + pr: { + any: [ + "CF_PULL_REQUEST_NUMBER", + "CF_PULL_REQUEST_ID" + ] + } + }, + { + name: "Codemagic", + constant: "CODEMAGIC", + env: "CM_BUILD_ID", + pr: "CM_PULL_REQUEST" + }, + { + name: "Codeship", + constant: "CODESHIP", + env: { + CI_NAME: "codeship" + } + }, + { + name: "Drone", + constant: "DRONE", + env: "DRONE", + pr: { + DRONE_BUILD_EVENT: "pull_request" + } + }, + { + name: "dsari", + constant: "DSARI", + env: "DSARI" + }, + { + name: "Expo Application Services", + constant: "EAS", + env: "EAS_BUILD" + }, + { + name: "Gerrit", + constant: "GERRIT", + env: "GERRIT_PROJECT" + }, + { + name: "GitHub Actions", + constant: "GITHUB_ACTIONS", + env: "GITHUB_ACTIONS", + pr: { + GITHUB_EVENT_NAME: "pull_request" + } + }, + { + name: "GitLab CI", + constant: "GITLAB", + env: "GITLAB_CI", + pr: "CI_MERGE_REQUEST_ID" + }, + { + name: "GoCD", + constant: "GOCD", + env: "GO_PIPELINE_LABEL" + }, + { + name: "Google Cloud Build", + constant: "GOOGLE_CLOUD_BUILD", + env: "BUILDER_OUTPUT" + }, + { + name: "Harness CI", + constant: "HARNESS", + env: "HARNESS_BUILD_ID" + }, + { + name: "Heroku", + constant: "HEROKU", + env: { + env: "NODE", + includes: "/app/.heroku/node/bin/node" + } + }, + { + name: "Hudson", + constant: "HUDSON", + env: "HUDSON_URL" + }, + { + name: "Jenkins", + constant: "JENKINS", + env: [ + "JENKINS_URL", + "BUILD_ID" + ], + pr: { + any: [ + "ghprbPullId", + "CHANGE_ID" + ] + } + }, + { + name: "LayerCI", + constant: "LAYERCI", + env: "LAYERCI", + pr: "LAYERCI_PULL_REQUEST" + }, + { + name: "Magnum CI", + constant: "MAGNUM", + env: "MAGNUM" + }, + { + name: "Netlify CI", + constant: "NETLIFY", + env: "NETLIFY", + pr: { + env: "PULL_REQUEST", + ne: "false" + } + }, + { + name: "Nevercode", + constant: "NEVERCODE", + env: "NEVERCODE", + pr: { + env: "NEVERCODE_PULL_REQUEST", + ne: "false" + } + }, + { + name: "ReleaseHub", + constant: "RELEASEHUB", + env: "RELEASE_BUILD_ID" + }, + { + name: "Render", + constant: "RENDER", + env: "RENDER", + pr: { + IS_PULL_REQUEST: "true" + } + }, + { + name: "Sail CI", + constant: "SAIL", + env: "SAILCI", + pr: "SAIL_PULL_REQUEST_NUMBER" + }, + { + name: "Screwdriver", + constant: "SCREWDRIVER", + env: "SCREWDRIVER", + pr: { + env: "SD_PULL_REQUEST", + ne: "false" + } + }, + { + name: "Semaphore", + constant: "SEMAPHORE", + env: "SEMAPHORE", + pr: "PULL_REQUEST_NUMBER" + }, + { + name: "Shippable", + constant: "SHIPPABLE", + env: "SHIPPABLE", + pr: { + IS_PULL_REQUEST: "true" + } + }, + { + name: "Solano CI", + constant: "SOLANO", + env: "TDDIUM", + pr: "TDDIUM_PR_ID" + }, + { + name: "Sourcehut", + constant: "SOURCEHUT", + env: { + CI_NAME: "sourcehut" + } + }, + { + name: "Strider CD", + constant: "STRIDER", + env: "STRIDER" + }, + { + name: "TaskCluster", + constant: "TASKCLUSTER", + env: [ + "TASK_ID", + "RUN_ID" + ] + }, + { + name: "TeamCity", + constant: "TEAMCITY", + env: "TEAMCITY_VERSION" + }, + { + name: "Travis CI", + constant: "TRAVIS", + env: "TRAVIS", + pr: { + env: "TRAVIS_PULL_REQUEST", + ne: "false" + } + }, + { + name: "Vercel", + constant: "VERCEL", + env: { + any: [ + "NOW_BUILDER", + "VERCEL" + ] + } + }, + { + name: "Visual Studio App Center", + constant: "APPCENTER", + env: "APPCENTER_BUILD_ID" + }, + { + name: "Woodpecker", + constant: "WOODPECKER", + env: { + CI: "woodpecker" + }, + pr: { + CI_BUILD_EVENT: "pull_request" + } + }, + { + name: "Xcode Cloud", + constant: "XCODE_CLOUD", + env: "CI_XCODE_PROJECT", + pr: "CI_PULL_REQUEST_NUMBER" + }, + { + name: "Xcode Server", + constant: "XCODE_SERVER", + env: "XCS" + } +]; + +(function (exports) { + + const vendors = require$$0$5; + + const env = process.env; + + // Used for testing only + Object.defineProperty(exports, '_vendors', { + value: vendors.map(function (v) { + return v.constant + }) + }); + + exports.name = null; + exports.isPR = null; + + vendors.forEach(function (vendor) { + const envs = Array.isArray(vendor.env) ? vendor.env : [vendor.env]; + const isCI = envs.every(function (obj) { + return checkEnv(obj) + }); + + exports[vendor.constant] = isCI; + + if (!isCI) { + return + } + + exports.name = vendor.name; + + switch (typeof vendor.pr) { + case 'string': + // "pr": "CIRRUS_PR" + exports.isPR = !!env[vendor.pr]; + break + case 'object': + if ('env' in vendor.pr) { + // "pr": { "env": "BUILDKITE_PULL_REQUEST", "ne": "false" } + exports.isPR = vendor.pr.env in env && env[vendor.pr.env] !== vendor.pr.ne; + } else if ('any' in vendor.pr) { + // "pr": { "any": ["ghprbPullId", "CHANGE_ID"] } + exports.isPR = vendor.pr.any.some(function (key) { + return !!env[key] + }); + } else { + // "pr": { "DRONE_BUILD_EVENT": "pull_request" } + exports.isPR = checkEnv(vendor.pr); + } + break + default: + // PR detection not supported for this vendor + exports.isPR = null; + } + }); + + exports.isCI = !!( + env.CI !== 'false' && // Bypass all checks if CI env is explicitly set to 'false' + (env.BUILD_ID || // Jenkins, Cloudbees + env.BUILD_NUMBER || // Jenkins, TeamCity + env.CI || // Travis CI, CircleCI, Cirrus CI, Gitlab CI, Appveyor, CodeShip, dsari + env.CI_APP_ID || // Appflow + env.CI_BUILD_ID || // Appflow + env.CI_BUILD_NUMBER || // Appflow + env.CI_NAME || // Codeship and others + env.CONTINUOUS_INTEGRATION || // Travis CI, Cirrus CI + env.RUN_ID || // TaskCluster, dsari + exports.name || + false) + ); + + function checkEnv (obj) { + // "env": "CIRRUS" + if (typeof obj === 'string') return !!env[obj] + + // "env": { "env": "NODE", "includes": "/app/.heroku/node/bin/node" } + if ('env' in obj) { + // Currently there are no other types, uncomment when there are + // if ('includes' in obj) { + return env[obj.env] && env[obj.env].includes(obj.includes) + // } + } + if ('any' in obj) { + return obj.any.some(function (k) { + return !!env[k] + }) + } + return Object.keys(obj).every(function (k) { + return env[k] === obj[k] + }) + } +} (ciInfo)); + +var ci = /*@__PURE__*/getDefaultExportFromCjs(ciInfo); + +var isCi = ciInfo.isCI; + +var isCi$1 = /*@__PURE__*/getDefaultExportFromCjs(isCi); + +const _htmlEscape = string => string + .replace(/&/g, '&') + .replace(/"/g, '"') + .replace(/'/g, ''') + .replace(//g, '>'); + +function htmlEscape(strings, ...values) { + if (typeof strings === 'string') { + return _htmlEscape(strings); + } + + let output = strings[0]; + for (const [index, value] of values.entries()) { + output = output + _htmlEscape(String(value)) + strings[index + 1]; + } + + return output; +} + +class MissingValueError extends Error { + constructor(key) { + super(`Missing a value for ${key ? `the placeholder: ${key}` : 'a placeholder'}`, key); + this.name = 'MissingValueError'; + this.key = key; + } +} + +function pupa(template, data, {ignoreMissing = false, transform = ({value}) => value} = {}) { + if (typeof template !== 'string') { + throw new TypeError(`Expected a \`string\` in the first argument, got \`${typeof template}\``); + } + + if (typeof data !== 'object') { + throw new TypeError(`Expected an \`object\` or \`Array\` in the second argument, got \`${typeof data}\``); + } + + const replace = (placeholder, key) => { + let value = data; + for (const property of key.split('.')) { + value = value ? value[property] : undefined; + } + + const transformedValue = transform({value, key}); + if (transformedValue === undefined) { + if (ignoreMissing) { + return placeholder; + } + + throw new MissingValueError(key); + } + + return String(transformedValue); + }; + + const composeHtmlEscape = replacer => (...args) => htmlEscape(replacer(...args)); + + // The regex tries to match either a number inside `{{ }}` or a valid JS identifier or key path. + const doubleBraceRegex = /{{(\d+|[a-z$_][\w\-$]*?(?:\.[\w\-$]*?)*?)}}/gi; + + if (doubleBraceRegex.test(template)) { + template = template.replace(doubleBraceRegex, composeHtmlEscape(replace)); + } + + const braceRegex = /{(\d+|[a-z$_][\w\-$]*?(?:\.[\w\-$]*?)*?)}/gi; + + return template.replace(braceRegex, replace); +} + +const __dirname$2 = path$c.dirname(urlLib.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('rollup-output.cjs', document.baseURI).href)))); + +const ONE_DAY = 1000 * 60 * 60 * 24; + +class UpdateNotifier { + // Public + config; + update; + + // Semi-private (used for tests) + _packageName; + _shouldNotifyInNpmScript; + + #options; + #packageVersion; + #updateCheckInterval; + #isDisabled; + + constructor(options = {}) { + this.#options = options; + options.pkg = options.pkg || {}; + options.distTag = options.distTag || 'latest'; + + // Reduce pkg to the essential keys. with fallback to deprecated options + // TODO: Remove deprecated options at some point far into the future + options.pkg = { + name: options.pkg.name || options.packageName, + version: options.pkg.version || options.packageVersion, + }; + + if (!options.pkg.name || !options.pkg.version) { + throw new Error('pkg.name and pkg.version required'); + } + + this._packageName = options.pkg.name; + this.#packageVersion = options.pkg.version; + this.#updateCheckInterval = typeof options.updateCheckInterval === 'number' ? options.updateCheckInterval : ONE_DAY; + this.#isDisabled = 'NO_UPDATE_NOTIFIER' in process$3.env + || process$3.env.NODE_ENV === 'test' + || process$3.argv.includes('--no-update-notifier') + || isCi$1; + this._shouldNotifyInNpmScript = options.shouldNotifyInNpmScript; + + if (!this.#isDisabled) { + try { + this.config = new Configstore(`update-notifier-${this._packageName}`, { + optOut: false, + // Init with the current time so the first check is only + // after the set interval, so not to bother users right away + lastUpdateCheck: Date.now(), + }); + } catch { + // Expecting error code EACCES or EPERM + const message + = chalk$5.yellow(node_util.format(' %s update check failed ', options.pkg.name)) + + node_util.format('\n Try running with %s or get access ', chalk$5.cyan('sudo')) + + '\n to the local update config store via \n' + + chalk$5.cyan(node_util.format(' sudo chown -R $USER:$(id -gn $USER) %s ', xdgConfig)); + + process$3.on('exit', () => { + console.error(boxen(message, {textAlignment: 'center'})); + }); + } + } + } + + check() { + if ( + !this.config + || this.config.get('optOut') + || this.#isDisabled + ) { + return; + } + + this.update = this.config.get('update'); + + if (this.update) { + // Use the real latest version instead of the cached one + this.update.current = this.#packageVersion; + + // Clear cached information + this.config.delete('update'); + } + + // Only check for updates on a set interval + if (Date.now() - this.config.get('lastUpdateCheck') < this.#updateCheckInterval) { + return; + } + + // Spawn a detached process, passing the options as an environment property + childProcess$1.spawn(process$3.execPath, [path$c.join(__dirname$2, 'check.js'), JSON.stringify(this.#options)], { + detached: true, + stdio: 'ignore', + }).unref(); + } + + async fetchInfo() { + const {distTag} = this.#options; + const latest = await latestVersion(this._packageName, {version: distTag}); + + return { + latest, + current: this.#packageVersion, + type: semverDiff(this.#packageVersion, latest) || distTag, + name: this._packageName, + }; + } + + notify(options) { + const suppressForNpm = !this._shouldNotifyInNpmScript && isNpmOrYarn; + if (!process$3.stdout.isTTY || suppressForNpm || !this.update || !semver$1.gt(this.update.latest, this.update.current)) { + return this; + } + + options = { + isGlobal: isInstalledGlobally$1, + isYarnGlobal: isYarnGlobal(), + ...options, + }; + + let installCommand; + if (options.isYarnGlobal) { + installCommand = `yarn global add ${this._packageName}`; + } else if (options.isGlobal) { + installCommand = `npm i -g ${this._packageName}`; + } else if (hasYarn()) { + installCommand = `yarn add ${this._packageName}`; + } else { + installCommand = `npm i ${this._packageName}`; + } + + const defaultTemplate = 'Update available ' + + chalk$5.dim('{currentVersion}') + + chalk$5.reset(' → ') + + chalk$5.green('{latestVersion}') + + ' \nRun ' + chalk$5.cyan('{updateCommand}') + ' to update'; + + const template = options.message || defaultTemplate; + + options.boxenOptions = options.boxenOptions || { + padding: 1, + margin: 1, + textAlignment: 'center', + borderColor: 'yellow', + borderStyle: 'round', + }; + + const message = boxen( + pupa(template, { + packageName: this._packageName, + currentVersion: this.update.current, + latestVersion: this.update.latest, + updateCommand: installCommand, + }), + options.boxenOptions, + ); + + if (options.defer === false) { + console.error(message); + } else { + process$3.on('exit', () => { + console.error(message); + }); + + process$3.on('SIGINT', () => { + console.error(''); + process$3.exit(); + }); + } + + return this; + } +} + +function updateNotifier(options) { + const updateNotifier = new UpdateNotifier(options); + updateNotifier.check(); + return updateNotifier; +} + +var name$1 = "rdme"; +var version$2 = "8.7.0-next.2"; +var description$4 = "ReadMe's official CLI and GitHub Action."; +var license$1 = "MIT"; +var author$1 = "ReadMe (https://readme.com)"; +var engines$3 = { + node: ">=14" +}; +var bin$1 = { + rdme: "bin/rdme.js" +}; +var keywords$1 = [ + "api", + "apidoc", + "apis", + "documentation", + "microservice", + "oai", + "oas", + "openapi", + "openapi document", + "openapi initiative", + "openapi spec", + "openapi specification", + "postman", + "readme", + "swagger" +]; +var repository$1 = { + type: "git", + url: "https://github.com/readmeio/rdme.git" +}; +var bugs$1 = { + url: "https://github.com/readmeio/rdme/issues" +}; +var type$h = "module"; +var dependencies$3 = { + "@actions/core": "^1.6.0", + chalk: "^5.3.0", + "ci-info": "^3.6.1", + "command-line-args": "^5.2.0", + "command-line-usage": "^7.0.1", + configstore: "^6.0.0", + debug: "^4.3.3", + editor: "^1.0.0", + "formdata-node": "^5.0.1", + "gray-matter": "^4.0.1", + ignore: "^5.2.0", + "mime-types": "^2.1.35", + "node-fetch": "^3.3.2", + oas: "^21.1.1", + "oas-normalize": "^10.1.0", + open: "^9.1.0", + ora: "^6.3.1", + "parse-link-header": "^2.0.0", + pluralize: "^8.0.0", + prompts: "^2.4.2", + semver: "^7.5.3", + "simple-git": "^3.19.1", + "string-argv": "^0.3.1", + table: "^6.8.1", + "tmp-promise": "^3.0.2", + "update-notifier": "^6.0.2", + validator: "^13.7.0" +}; +var devDependencies = { + "@commitlint/cli": "^17.6.6", + "@commitlint/config-conventional": "^17.6.6", + "@readme/better-ajv-errors": "^1.5.0", + "@readme/eslint-config": "^13.0.0", + "@readme/oas-examples": "^5.10.0", + "@rollup/plugin-commonjs": "^25.0.4", + "@rollup/plugin-json": "^6.0.0", + "@rollup/plugin-node-resolve": "^15.2.1", + "@rollup/plugin-replace": "^5.0.2", + "@types/command-line-args": "^5.2.0", + "@types/command-line-usage": "^5.0.2", + "@types/configstore": "^6.0.0", + "@types/debug": "^4.1.7", + "@types/js-yaml": "^4.0.5", + "@types/mime-types": "^2.1.1", + "@types/parse-link-header": "^2.0.0", + "@types/pluralize": "^0.0.30", + "@types/prompts": "^2.4.2", + "@types/semver": "^7.3.12", + "@types/validator": "^13.7.6", + "@vitest/coverage-v8": "^0.34.1", + "@vitest/expect": "^0.34.3", + ajv: "^8.11.0", + alex: "^11.0.0", + eslint: "^8.47.0", + "headers-polyfill": "^4.0.1", + husky: "^8.0.0", + "js-yaml": "^4.1.0", + knip: "^2.24.0", + msw: "^1.2.3", + nock: "^13.2.7", + "openapi-types": "^12.1.3", + pkg: "^5.8.1", + prettier: "^3.0.2", + rollup: "^3.29.1", + "ts-node": "^10.9.1", + "type-fest": "^4.3.1", + typescript: "^5.1.6", + vitest: "^0.34.1" +}; +var scripts$1 = { + build: "tsc", + "build:exe": "npm run build && rollup -c && pkg dist/rollup-output.cjs --target host --output exe/rdme", + debug: "ts-node src/cli.ts", + lint: "alex . && knip && npm run lint:ts && npm run prettier && npm run schemas:check", + "lint:ts": "eslint . --ext .js,.ts", + prebuild: "rm -rf dist/", + prepack: "npm run build", + prepare: "husky install", + pretest: "npm run build", + prettier: "prettier --check .", + "schemas:check": "./bin/json-schema-store.js", + "schemas:write": "./bin/json-schema-store.js --update", + test: "npm run test:multi && npm run test:single", + "test:multi": "vitest run --coverage", + "test:single": "vitest run --coverage --config vitest.single-threaded.config.ts" +}; +var commitlint = { + "extends": [ + "@commitlint/config-conventional" + ], + rules: { + "body-max-line-length": [ + 0, + "always", + "Infinity" + ], + "footer-max-line-length": [ + 0, + "always", + "Infinity" + ], + "scope-case": [ + 2, + "never", + "upper-case" + ] + } +}; +var prettier = "@readme/eslint-config/prettier"; +var pkg = { + name: name$1, + version: version$2, + description: description$4, + license: license$1, + author: author$1, + engines: engines$3, + bin: bin$1, + keywords: keywords$1, + repository: repository$1, + bugs: bugs$1, + type: type$h, + dependencies: dependencies$3, + devDependencies: devDependencies, + scripts: scripts$1, + commitlint: commitlint, + prettier: prettier +}; + +/** + * Wrapper function that returns the name of the current CI environment + * (or "n/a" if it's not available). + * + * Full list of vendors available here: + * https://github.com/watson/ci-info#supported-ci-tools + */ +function ciName() { + return ci.name || 'n/a'; +} +/** + * Small env check to determine if we're running our testbed + */ +function isTest() { + return process.env.NODE_ENV === 'rdme-test'; +} +/** + * Small env check to determine if the current command is being run + * via an npm (or yarn) script. + * + * The reason we have this weird conditional logic is because we run our tests via + * an npm script and we don't want false positives when running tests. + * + * @see {@link https://docs.npmjs.com/cli/v8/using-npm/scripts#current-lifecycle-event} + * @see {@link https://docs.npmjs.com/cli/v6/using-npm/scripts#current-lifecycle-event} + * @see {@link https://yarnpkg.com/advanced/lifecycle-scripts} + */ +function isNpmScript() { + /* istanbul ignore next */ + return (!!process.env.npm_lifecycle_event && !isTest()) || !!process.env.TEST_RDME_NPM_SCRIPT; +} +/** + * Small check to ensure we're in a safe CI environment. + * + * The reason we have this weird conditional logic is because we run our tests in + * a CI environment and we don't want false positives when running tests. + */ +function isCI() { + /* istanbul ignore next */ + return (ci.isCI && !isTest()) || !!process.env.TEST_RDME_CI; +} +/** + * Small env check to determine if we're in a GitHub Actions environment. + * + * @see {@link https://docs.github.com/en/actions/learn-github-actions/environment-variables#default-environment-variables} + */ +function isGHA() { + return isCI() && ci.GITHUB_ACTIONS; +} + +/** + * lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright jQuery Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ + +/** Used as references for various `Number` constants. */ +var INFINITY$4 = 1 / 0; + +/** `Object#toString` result references. */ +var symbolTag$4 = '[object Symbol]'; + +/** Used to match words composed of alphanumeric characters. */ +var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g; + +/** Used to match Latin Unicode letters (excluding mathematical operators). */ +var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g; + +/** Used to compose unicode character classes. */ +var rsAstralRange = '\\ud800-\\udfff', + rsComboMarksRange = '\\u0300-\\u036f\\ufe20-\\ufe23', + rsComboSymbolsRange = '\\u20d0-\\u20f0', + rsDingbatRange = '\\u2700-\\u27bf', + rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff', + rsMathOpRange = '\\xac\\xb1\\xd7\\xf7', + rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf', + rsPunctuationRange = '\\u2000-\\u206f', + rsSpaceRange = ' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000', + rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde', + rsVarRange = '\\ufe0e\\ufe0f', + rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange; + +/** Used to compose unicode capture groups. */ +var rsApos = "['\u2019]", + rsAstral = '[' + rsAstralRange + ']', + rsBreak = '[' + rsBreakRange + ']', + rsCombo = '[' + rsComboMarksRange + rsComboSymbolsRange + ']', + rsDigits = '\\d+', + rsDingbat = '[' + rsDingbatRange + ']', + rsLower = '[' + rsLowerRange + ']', + rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']', + rsFitz = '\\ud83c[\\udffb-\\udfff]', + rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', + rsNonAstral = '[^' + rsAstralRange + ']', + rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', + rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', + rsUpper = '[' + rsUpperRange + ']', + rsZWJ = '\\u200d'; + +/** Used to compose unicode regexes. */ +var rsLowerMisc = '(?:' + rsLower + '|' + rsMisc + ')', + rsUpperMisc = '(?:' + rsUpper + '|' + rsMisc + ')', + rsOptLowerContr = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?', + rsOptUpperContr = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?', + reOptMod = rsModifier + '?', + rsOptVar = '[' + rsVarRange + ']?', + rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', + rsSeq = rsOptVar + reOptMod + rsOptJoin, + rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq, + rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; + +/** Used to match apostrophes. */ +var reApos = RegExp(rsApos, 'g'); + +/** + * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and + * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols). + */ +var reComboMark = RegExp(rsCombo, 'g'); + +/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ +var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); + +/** Used to match complex or compound words. */ +var reUnicodeWord = RegExp([ + rsUpper + '?' + rsLower + '+' + rsOptLowerContr + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')', + rsUpperMisc + '+' + rsOptUpperContr + '(?=' + [rsBreak, rsUpper + rsLowerMisc, '$'].join('|') + ')', + rsUpper + '?' + rsLowerMisc + '+' + rsOptLowerContr, + rsUpper + '+' + rsOptUpperContr, + rsDigits, + rsEmoji +].join('|'), 'g'); + +/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ +var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboMarksRange + rsComboSymbolsRange + rsVarRange + ']'); + +/** Used to detect strings that need a more robust regexp to match words. */ +var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/; + +/** Used to map Latin Unicode letters to basic Latin letters. */ +var deburredLetters = { + // Latin-1 Supplement block. + '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A', + '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a', + '\xc7': 'C', '\xe7': 'c', + '\xd0': 'D', '\xf0': 'd', + '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E', + '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e', + '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I', + '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i', + '\xd1': 'N', '\xf1': 'n', + '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O', + '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o', + '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U', + '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u', + '\xdd': 'Y', '\xfd': 'y', '\xff': 'y', + '\xc6': 'Ae', '\xe6': 'ae', + '\xde': 'Th', '\xfe': 'th', + '\xdf': 'ss', + // Latin Extended-A block. + '\u0100': 'A', '\u0102': 'A', '\u0104': 'A', + '\u0101': 'a', '\u0103': 'a', '\u0105': 'a', + '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C', + '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c', + '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd', + '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E', + '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e', + '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G', + '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g', + '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h', + '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I', + '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i', + '\u0134': 'J', '\u0135': 'j', + '\u0136': 'K', '\u0137': 'k', '\u0138': 'k', + '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L', + '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l', + '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N', + '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n', + '\u014c': 'O', '\u014e': 'O', '\u0150': 'O', + '\u014d': 'o', '\u014f': 'o', '\u0151': 'o', + '\u0154': 'R', '\u0156': 'R', '\u0158': 'R', + '\u0155': 'r', '\u0157': 'r', '\u0159': 'r', + '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S', + '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's', + '\u0162': 'T', '\u0164': 'T', '\u0166': 'T', + '\u0163': 't', '\u0165': 't', '\u0167': 't', + '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U', + '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u', + '\u0174': 'W', '\u0175': 'w', + '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y', + '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z', + '\u017a': 'z', '\u017c': 'z', '\u017e': 'z', + '\u0132': 'IJ', '\u0133': 'ij', + '\u0152': 'Oe', '\u0153': 'oe', + '\u0149': "'n", '\u017f': 'ss' +}; + +/** Detect free variable `global` from Node.js. */ +var freeGlobal$2 = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal; + +/** Detect free variable `self`. */ +var freeSelf$1 = typeof self == 'object' && self && self.Object === Object && self; + +/** Used as a reference to the global object. */ +var root$9 = freeGlobal$2 || freeSelf$1 || Function('return this')(); + +/** + * A specialized version of `_.reduce` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @param {boolean} [initAccum] Specify using the first element of `array` as + * the initial value. + * @returns {*} Returns the accumulated value. + */ +function arrayReduce(array, iteratee, accumulator, initAccum) { + var index = -1, + length = array ? array.length : 0; + + if (initAccum && length) { + accumulator = array[++index]; + } + while (++index < length) { + accumulator = iteratee(accumulator, array[index], index, array); + } + return accumulator; +} + +/** + * Converts an ASCII `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ +function asciiToArray(string) { + return string.split(''); +} + +/** + * Splits an ASCII `string` into an array of its words. + * + * @private + * @param {string} The string to inspect. + * @returns {Array} Returns the words of `string`. + */ +function asciiWords(string) { + return string.match(reAsciiWord) || []; +} + +/** + * The base implementation of `_.propertyOf` without support for deep paths. + * + * @private + * @param {Object} object The object to query. + * @returns {Function} Returns the new accessor function. + */ +function basePropertyOf(object) { + return function(key) { + return object == null ? undefined : object[key]; + }; +} + +/** + * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A + * letters to basic Latin letters. + * + * @private + * @param {string} letter The matched letter to deburr. + * @returns {string} Returns the deburred letter. + */ +var deburrLetter = basePropertyOf(deburredLetters); + +/** + * Checks if `string` contains Unicode symbols. + * + * @private + * @param {string} string The string to inspect. + * @returns {boolean} Returns `true` if a symbol is found, else `false`. + */ +function hasUnicode(string) { + return reHasUnicode.test(string); +} + +/** + * Checks if `string` contains a word composed of Unicode symbols. + * + * @private + * @param {string} string The string to inspect. + * @returns {boolean} Returns `true` if a word is found, else `false`. + */ +function hasUnicodeWord(string) { + return reHasUnicodeWord.test(string); +} + +/** + * Converts `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ +function stringToArray(string) { + return hasUnicode(string) + ? unicodeToArray(string) + : asciiToArray(string); +} + +/** + * Converts a Unicode `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ +function unicodeToArray(string) { + return string.match(reUnicode) || []; +} + +/** + * Splits a Unicode `string` into an array of its words. + * + * @private + * @param {string} The string to inspect. + * @returns {Array} Returns the words of `string`. + */ +function unicodeWords(string) { + return string.match(reUnicodeWord) || []; +} + +/** Used for built-in method references. */ +var objectProto$i = Object.prototype; + +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString$4 = objectProto$i.toString; + +/** Built-in value references. */ +var Symbol$8 = root$9.Symbol; + +/** Used to convert symbols to primitives and strings. */ +var symbolProto$3 = Symbol$8 ? Symbol$8.prototype : undefined, + symbolToString$1 = symbolProto$3 ? symbolProto$3.toString : undefined; + +/** + * The base implementation of `_.slice` without an iteratee call guard. + * + * @private + * @param {Array} array The array to slice. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the slice of `array`. + */ +function baseSlice(array, start, end) { + var index = -1, + length = array.length; + + if (start < 0) { + start = -start > length ? 0 : (length + start); + } + end = end > length ? length : end; + if (end < 0) { + end += length; + } + length = start > end ? 0 : ((end - start) >>> 0); + start >>>= 0; + + var result = Array(length); + while (++index < length) { + result[index] = array[index + start]; + } + return result; +} + +/** + * The base implementation of `_.toString` which doesn't convert nullish + * values to empty strings. + * + * @private + * @param {*} value The value to process. + * @returns {string} Returns the string. + */ +function baseToString$2(value) { + // Exit early for strings to avoid a performance hit in some environments. + if (typeof value == 'string') { + return value; + } + if (isSymbol$6(value)) { + return symbolToString$1 ? symbolToString$1.call(value) : ''; + } + var result = (value + ''); + return (result == '0' && (1 / value) == -INFINITY$4) ? '-0' : result; +} + +/** + * Casts `array` to a slice if it's needed. + * + * @private + * @param {Array} array The array to inspect. + * @param {number} start The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the cast slice. + */ +function castSlice(array, start, end) { + var length = array.length; + end = end === undefined ? length : end; + return (!start && end >= length) ? array : baseSlice(array, start, end); +} + +/** + * Creates a function like `_.lowerFirst`. + * + * @private + * @param {string} methodName The name of the `String` case method to use. + * @returns {Function} Returns the new case function. + */ +function createCaseFirst(methodName) { + return function(string) { + string = toString$3(string); + + var strSymbols = hasUnicode(string) + ? stringToArray(string) + : undefined; + + var chr = strSymbols + ? strSymbols[0] + : string.charAt(0); + + var trailing = strSymbols + ? castSlice(strSymbols, 1).join('') + : string.slice(1); + + return chr[methodName]() + trailing; + }; +} + +/** + * Creates a function like `_.camelCase`. + * + * @private + * @param {Function} callback The function to combine each word. + * @returns {Function} Returns the new compounder function. + */ +function createCompounder(callback) { + return function(string) { + return arrayReduce(words(deburr(string).replace(reApos, '')), callback, ''); + }; +} + +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike$c(value) { + return !!value && typeof value == 'object'; +} + +/** + * Checks if `value` is classified as a `Symbol` primitive or object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. + * @example + * + * _.isSymbol(Symbol.iterator); + * // => true + * + * _.isSymbol('abc'); + * // => false + */ +function isSymbol$6(value) { + return typeof value == 'symbol' || + (isObjectLike$c(value) && objectToString$4.call(value) == symbolTag$4); +} + +/** + * Converts `value` to a string. An empty string is returned for `null` + * and `undefined` values. The sign of `-0` is preserved. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to process. + * @returns {string} Returns the string. + * @example + * + * _.toString(null); + * // => '' + * + * _.toString(-0); + * // => '-0' + * + * _.toString([1, 2, 3]); + * // => '1,2,3' + */ +function toString$3(value) { + return value == null ? '' : baseToString$2(value); +} + +/** + * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the camel cased string. + * @example + * + * _.camelCase('Foo Bar'); + * // => 'fooBar' + * + * _.camelCase('--foo-bar--'); + * // => 'fooBar' + * + * _.camelCase('__FOO_BAR__'); + * // => 'fooBar' + */ +var camelCase$2 = createCompounder(function(result, word, index) { + word = word.toLowerCase(); + return result + (index ? capitalize(word) : word); +}); + +/** + * Converts the first character of `string` to upper case and the remaining + * to lower case. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to capitalize. + * @returns {string} Returns the capitalized string. + * @example + * + * _.capitalize('FRED'); + * // => 'Fred' + */ +function capitalize(string) { + return upperFirst(toString$3(string).toLowerCase()); +} + +/** + * Deburrs `string` by converting + * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table) + * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A) + * letters to basic Latin letters and removing + * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to deburr. + * @returns {string} Returns the deburred string. + * @example + * + * _.deburr('déjà vu'); + * // => 'deja vu' + */ +function deburr(string) { + string = toString$3(string); + return string && string.replace(reLatin, deburrLetter).replace(reComboMark, ''); +} + +/** + * Converts the first character of `string` to upper case. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the converted string. + * @example + * + * _.upperFirst('fred'); + * // => 'Fred' + * + * _.upperFirst('FRED'); + * // => 'FRED' + */ +var upperFirst = createCaseFirst('toUpperCase'); + +/** + * Splits `string` into an array of its words. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to inspect. + * @param {RegExp|string} [pattern] The pattern to match words. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the words of `string`. + * @example + * + * _.words('fred, barney, & pebbles'); + * // => ['fred', 'barney', 'pebbles'] + * + * _.words('fred, barney, & pebbles', /[^, ]+/g); + * // => ['fred', 'barney', '&', 'pebbles'] + */ +function words(string, pattern, guard) { + string = toString$3(string); + pattern = guard ? undefined : pattern; + + if (pattern === undefined) { + return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string); + } + return string.match(pattern) || []; +} + +var lodash_camelcase = camelCase$2; + +function _interopDefault$1 (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } + +var camelCase$1 = _interopDefault$1(lodash_camelcase); + +/** + * Takes any input and guarantees an array back. + * + * - Converts array-like objects (e.g. `arguments`, `Set`) to a real array. + * - Converts `undefined` to an empty array. + * - Converts any another other, singular value (including `null`, objects and iterables other than `Set`) into an array containing that value. + * - Ignores input which is already an array. + * + * @module array-back + * @example + * > const arrayify = require('array-back') + * + * > arrayify(undefined) + * [] + * + * > arrayify(null) + * [ null ] + * + * > arrayify(0) + * [ 0 ] + * + * > arrayify([ 1, 2 ]) + * [ 1, 2 ] + * + * > arrayify(new Set([ 1, 2 ])) + * [ 1, 2 ] + * + * > function f(){ return arrayify(arguments); } + * > f(1,2,3) + * [ 1, 2, 3 ] + */ + +function isObject$o (input) { + return typeof input === 'object' && input !== null +} + +function isArrayLike$d (input) { + return isObject$o(input) && typeof input.length === 'number' +} + +/** + * @param {*} - The input value to convert to an array + * @returns {Array} + * @alias module:array-back + */ +function arrayify$2 (input) { + if (Array.isArray(input)) { + return input + } + + if (input === undefined) { + return [] + } + + if (isArrayLike$d(input) || input instanceof Set) { + return Array.from(input) + } + + return [ input ] +} + +/** + * Takes any input and guarantees an array back. + * + * - converts array-like objects (e.g. `arguments`) to a real array + * - converts `undefined` to an empty array + * - converts any another other, singular value (including `null`) into an array containing that value + * - ignores input which is already an array + * + * @module array-back + * @example + * > const arrayify = require('array-back') + * + * > arrayify(undefined) + * [] + * + * > arrayify(null) + * [ null ] + * + * > arrayify(0) + * [ 0 ] + * + * > arrayify([ 1, 2 ]) + * [ 1, 2 ] + * + * > function f(){ return arrayify(arguments); } + * > f(1,2,3) + * [ 1, 2, 3 ] + */ + +function isObject$1$1 (input) { + return typeof input === 'object' && input !== null +} + +function isArrayLike$1$1 (input) { + return isObject$1$1(input) && typeof input.length === 'number' +} + +/** + * @param {*} - the input value to convert to an array + * @returns {Array} + * @alias module:array-back + */ +function arrayify$1$1 (input) { + if (Array.isArray(input)) { + return input + } else { + if (input === undefined) { + return [] + } else if (isArrayLike$1$1(input)) { + return Array.prototype.slice.call(input) + } else { + return [ input ] + } + } +} + +/** + * Find and either replace or remove items in an array. + * + * @module find-replace + * @example + * > const findReplace = require('find-replace') + * > const numbers = [ 1, 2, 3] + * + * > findReplace(numbers, n => n === 2, 'two') + * [ 1, 'two', 3 ] + * + * > findReplace(numbers, n => n === 2, [ 'two', 'zwei' ]) + * [ 1, [ 'two', 'zwei' ], 3 ] + * + * > findReplace(numbers, n => n === 2, 'two', 'zwei') + * [ 1, 'two', 'zwei', 3 ] + * + * > findReplace(numbers, n => n === 2) // no replacement, so remove + * [ 1, 3 ] + */ + +/** + * @param {array} - The input array + * @param {testFn} - A predicate function which, if returning `true` causes the current item to be operated on. + * @param [replaceWith] {...any} - If specified, found values will be replaced with these values, else removed. + * @returns {array} + * @alias module:find-replace + */ +function findReplace (array, testFn) { + const found = []; + const replaceWiths = arrayify$1$1(arguments); + replaceWiths.splice(0, 2); + + arrayify$1$1(array).forEach((value, index) => { + let expanded = []; + replaceWiths.forEach(replaceWith => { + if (typeof replaceWith === 'function') { + expanded = expanded.concat(replaceWith(value)); + } else { + expanded.push(replaceWith); + } + }); + + if (testFn(value)) { + found.push({ + index: index, + replaceWithValue: expanded + }); + } + }); + + found.reverse().forEach(item => { + const spliceArgs = [ item.index, 1 ].concat(item.replaceWithValue); + array.splice.apply(array, spliceArgs); + }); + + return array +} + +/** + * Some useful tools for working with `process.argv`. + * + * @module argv-tools + * @typicalName argvTools + * @example + * const argvTools = require('argv-tools') + */ + +/** + * Regular expressions for matching option formats. + * @static + */ +const re$2 = { + short: /^-([^\d-])$/, + long: /^--(\S+)/, + combinedShort: /^-[^\d-]{2,}$/, + optEquals: /^(--\S+?)=(.*)/ +}; + +/** + * Array subclass encapsulating common operations on `process.argv`. + * @static + */ +class ArgvArray extends Array { + /** + * Clears the array has loads the supplied input. + * @param {string[]} argv - The argv list to load. Defaults to `process.argv`. + */ + load (argv) { + this.clear(); + if (argv && argv !== process.argv) { + argv = arrayify$2(argv); + } else { + /* if no argv supplied, assume we are parsing process.argv */ + argv = process.argv.slice(0); + const deleteCount = process.execArgv.some(isExecArg) ? 1 : 2; + argv.splice(0, deleteCount); + } + argv.forEach(arg => this.push(String(arg))); + } + + /** + * Clear the array. + */ + clear () { + this.length = 0; + } + + /** + * expand ``--option=value` style args. + */ + expandOptionEqualsNotation () { + if (this.some(arg => re$2.optEquals.test(arg))) { + const expandedArgs = []; + this.forEach(arg => { + const matches = arg.match(re$2.optEquals); + if (matches) { + expandedArgs.push(matches[1], matches[2]); + } else { + expandedArgs.push(arg); + } + }); + this.clear(); + this.load(expandedArgs); + } + } + + /** + * expand getopt-style combinedShort options. + */ + expandGetoptNotation () { + if (this.hasCombinedShortOptions()) { + findReplace(this, re$2.combinedShort, expandCombinedShortArg); + } + } + + /** + * Returns true if the array contains combined short options (e.g. `-ab`). + * @returns {boolean} + */ + hasCombinedShortOptions () { + return this.some(arg => re$2.combinedShort.test(arg)) + } + + static from (argv) { + const result = new this(); + result.load(argv); + return result + } +} + +/** + * Expand a combined short option. + * @param {string} - the string to expand, e.g. `-ab` + * @returns {string[]} + * @static + */ +function expandCombinedShortArg (arg) { + /* remove initial hypen */ + arg = arg.slice(1); + return arg.split('').map(letter => '-' + letter) +} + +/** + * Returns true if the supplied arg matches `--option=value` notation. + * @param {string} - the arg to test, e.g. `--one=something` + * @returns {boolean} + * @static + */ +function isOptionEqualsNotation (arg) { + return re$2.optEquals.test(arg) +} + +/** + * Returns true if the supplied arg is in either long (`--one`) or short (`-o`) format. + * @param {string} - the arg to test, e.g. `--one` + * @returns {boolean} + * @static + */ +function isOption (arg) { + return (re$2.short.test(arg) || re$2.long.test(arg)) && !re$2.optEquals.test(arg) +} + +/** + * Returns true if the supplied arg is in long (`--one`) format. + * @param {string} - the arg to test, e.g. `--one` + * @returns {boolean} + * @static + */ +function isLongOption (arg) { + return re$2.long.test(arg) && !isOptionEqualsNotation(arg) +} + +/** + * Returns the name from a long, short or `--options=value` arg. + * @param {string} - the arg to inspect, e.g. `--one` + * @returns {string} + * @static + */ +function getOptionName (arg) { + if (re$2.short.test(arg)) { + return arg.match(re$2.short)[1] + } else if (isLongOption(arg)) { + return arg.match(re$2.long)[1] + } else if (isOptionEqualsNotation(arg)) { + return arg.match(re$2.optEquals)[1].replace(/^--/, '') + } else { + return null + } +} + +function isValue$4 (arg) { + return !(isOption(arg) || re$2.combinedShort.test(arg) || re$2.optEquals.test(arg)) +} + +function isExecArg (arg) { + return ['--eval', '-e'].indexOf(arg) > -1 || arg.startsWith('--eval=') +} + +/** + * For type-checking Javascript values. + * @module typical + * @typicalname t + * @example + * const t = require('typical') + */ + +/** + * Returns true if input is a number + * @param {*} - the input to test + * @returns {boolean} + * @static + * @example + * > t.isNumber(0) + * true + * > t.isNumber(1) + * true + * > t.isNumber(1.1) + * true + * > t.isNumber(0xff) + * true + * > t.isNumber(0644) + * true + * > t.isNumber(6.2e5) + * true + * > t.isNumber(NaN) + * false + * > t.isNumber(Infinity) + * false + */ +function isNumber$4 (n) { + return !isNaN(parseFloat(n)) && isFinite(n) +} + +/** + * A plain object is a simple object literal, it is not an instance of a class. Returns true if the input `typeof` is `object` and directly decends from `Object`. + * + * @param {*} - the input to test + * @returns {boolean} + * @static + * @example + * > t.isPlainObject({ something: 'one' }) + * true + * > t.isPlainObject(new Date()) + * false + * > t.isPlainObject([ 0, 1 ]) + * false + * > t.isPlainObject(/test/) + * false + * > t.isPlainObject(1) + * false + * > t.isPlainObject('one') + * false + * > t.isPlainObject(null) + * false + * > t.isPlainObject((function * () {})()) + * false + * > t.isPlainObject(function * () {}) + * false + */ +function isPlainObject$8 (input) { + return input !== null && typeof input === 'object' && input.constructor === Object +} + +/** + * An array-like value has all the properties of an array, but is not an array instance. Examples in the `arguments` object. Returns true if the input value is an object, not null and has a `length` property with a numeric value. + * + * @param {*} - the input to test + * @returns {boolean} + * @static + * @example + * function sum(x, y){ + * console.log(t.isArrayLike(arguments)) + * // prints `true` + * } + */ +function isArrayLike$2$1 (input) { + return isObject$2$1(input) && typeof input.length === 'number' +} + +/** + * returns true if the typeof input is `'object'`, but not null! + * @param {*} - the input to test + * @returns {boolean} + * @static + */ +function isObject$2$1 (input) { + return typeof input === 'object' && input !== null +} + +/** + * Returns true if the input value is defined + * @param {*} - the input to test + * @returns {boolean} + * @static + */ +function isDefined$3 (input) { + return typeof input !== 'undefined' +} + +/** + * Returns true if the input value is a string + * @param {*} - the input to test + * @returns {boolean} + * @static + */ +function isString$4 (input) { + return typeof input === 'string' +} + +/** + * Returns true if the input value is a boolean + * @param {*} - the input to test + * @returns {boolean} + * @static + */ +function isBoolean$5 (input) { + return typeof input === 'boolean' +} + +/** + * Returns true if the input value is a function + * @param {*} - the input to test + * @returns {boolean} + * @static + */ +function isFunction$d (input) { + return typeof input === 'function' +} + +/** + * Returns true if the input value is an es2015 `class`. + * @param {*} - the input to test + * @returns {boolean} + * @static + */ +function isClass$2 (input) { + if (isFunction$d(input)) { + return /^class /.test(Function.prototype.toString.call(input)) + } else { + return false + } +} + +/** + * Returns true if the input is a string, number, symbol, boolean, null or undefined value. + * @param {*} - the input to test + * @returns {boolean} + * @static + */ +function isPrimitive$3 (input) { + if (input === null) return true + switch (typeof input) { + case 'string': + case 'number': + case 'symbol': + case 'undefined': + case 'boolean': + return true + default: + return false + } +} + +/** + * Returns true if the input is a Promise. + * @param {*} - the input to test + * @returns {boolean} + * @static + */ +function isPromise$3 (input) { + if (input) { + const isPromise = isDefined$3(Promise) && input instanceof Promise; + const isThenable = input.then && typeof input.then === 'function'; + return !!(isPromise || isThenable) + } else { + return false + } +} + +/** + * Returns true if the input is an iterable (`Map`, `Set`, `Array`, Generator etc.). + * @param {*} - the input to test + * @returns {boolean} + * @static + * @example + * > t.isIterable('string') + * true + * > t.isIterable(new Map()) + * true + * > t.isIterable([]) + * true + * > t.isIterable((function * () {})()) + * true + * > t.isIterable(Promise.resolve()) + * false + * > t.isIterable(Promise) + * false + * > t.isIterable(true) + * false + * > t.isIterable({}) + * false + * > t.isIterable(0) + * false + * > t.isIterable(1.1) + * false + * > t.isIterable(NaN) + * false + * > t.isIterable(Infinity) + * false + * > t.isIterable(function () {}) + * false + * > t.isIterable(Date) + * false + * > t.isIterable() + * false + * > t.isIterable({ then: function () {} }) + * false + */ +function isIterable$2 (input) { + if (input === null || !isDefined$3(input)) { + return false + } else { + return ( + typeof input[Symbol.iterator] === 'function' || + typeof input[Symbol.asyncIterator] === 'function' + ) + } +} + +var t$4 = { + isNumber: isNumber$4, + isString: isString$4, + isBoolean: isBoolean$5, + isPlainObject: isPlainObject$8, + isArrayLike: isArrayLike$2$1, + isObject: isObject$2$1, + isDefined: isDefined$3, + isFunction: isFunction$d, + isClass: isClass$2, + isPrimitive: isPrimitive$3, + isPromise: isPromise$3, + isIterable: isIterable$2 +}; + +/** + * @module option-definition + */ + +/** + * Describes a command-line option. Additionally, if generating a usage guide with [command-line-usage](https://github.com/75lb/command-line-usage) you could optionally add `description` and `typeLabel` properties to each definition. + * + * @alias module:option-definition + * @typicalname option + */ +class OptionDefinition { + constructor (definition) { + /** + * The only required definition property is `name`, so the simplest working example is + * ```js + * const optionDefinitions = [ + * { name: 'file' }, + * { name: 'depth' } + * ] + * ``` + * + * Where a `type` property is not specified it will default to `String`. + * + * | # | argv input | commandLineArgs() output | + * | --- | -------------------- | ------------ | + * | 1 | `--file` | `{ file: null }` | + * | 2 | `--file lib.js` | `{ file: 'lib.js' }` | + * | 3 | `--depth 2` | `{ depth: '2' }` | + * + * Unicode option names and aliases are valid, for example: + * ```js + * const optionDefinitions = [ + * { name: 'один' }, + * { name: '两' }, + * { name: 'три', alias: 'т' } + * ] + * ``` + * @type {string} + */ + this.name = definition.name; + + /** + * The `type` value is a setter function (you receive the output from this), enabling you to be specific about the type and value received. + * + * The most common values used are `String` (the default), `Number` and `Boolean` but you can use a custom function, for example: + * + * ```js + * const fs = require('fs') + * + * class FileDetails { + * constructor (filename) { + * this.filename = filename + * this.exists = fs.existsSync(filename) + * } + * } + * + * const cli = commandLineArgs([ + * { name: 'file', type: filename => new FileDetails(filename) }, + * { name: 'depth', type: Number } + * ]) + * ``` + * + * | # | argv input | commandLineArgs() output | + * | --- | ----------------- | ------------ | + * | 1 | `--file asdf.txt` | `{ file: { filename: 'asdf.txt', exists: false } }` | + * + * The `--depth` option expects a `Number`. If no value was set, you will receive `null`. + * + * | # | argv input | commandLineArgs() output | + * | --- | ----------------- | ------------ | + * | 2 | `--depth` | `{ depth: null }` | + * | 3 | `--depth 2` | `{ depth: 2 }` | + * + * @type {function} + * @default String + */ + this.type = definition.type || String; + + /** + * getopt-style short option names. Can be any single character (unicode included) except a digit or hyphen. + * + * ```js + * const optionDefinitions = [ + * { name: 'hot', alias: 'h', type: Boolean }, + * { name: 'discount', alias: 'd', type: Boolean }, + * { name: 'courses', alias: 'c' , type: Number } + * ] + * ``` + * + * | # | argv input | commandLineArgs() output | + * | --- | ------------ | ------------ | + * | 1 | `-hcd` | `{ hot: true, courses: null, discount: true }` | + * | 2 | `-hdc 3` | `{ hot: true, discount: true, courses: 3 }` | + * + * @type {string} + */ + this.alias = definition.alias; + + /** + * Set this flag if the option takes a list of values. You will receive an array of values, each passed through the `type` function (if specified). + * + * ```js + * const optionDefinitions = [ + * { name: 'files', type: String, multiple: true } + * ] + * ``` + * + * Note, examples 1 and 3 below demonstrate "greedy" parsing which can be disabled by using `lazyMultiple`. + * + * | # | argv input | commandLineArgs() output | + * | --- | ------------ | ------------ | + * | 1 | `--files one.js two.js` | `{ files: [ 'one.js', 'two.js' ] }` | + * | 2 | `--files one.js --files two.js` | `{ files: [ 'one.js', 'two.js' ] }` | + * | 3 | `--files *` | `{ files: [ 'one.js', 'two.js' ] }` | + * + * @type {boolean} + */ + this.multiple = definition.multiple; + + /** + * Identical to `multiple` but with greedy parsing disabled. + * + * ```js + * const optionDefinitions = [ + * { name: 'files', lazyMultiple: true }, + * { name: 'verbose', alias: 'v', type: Boolean, lazyMultiple: true } + * ] + * ``` + * + * | # | argv input | commandLineArgs() output | + * | --- | ------------ | ------------ | + * | 1 | `--files one.js --files two.js` | `{ files: [ 'one.js', 'two.js' ] }` | + * | 2 | `-vvv` | `{ verbose: [ true, true, true ] }` | + * + * @type {boolean} + */ + this.lazyMultiple = definition.lazyMultiple; + + /** + * Any values unaccounted for by an option definition will be set on the `defaultOption`. This flag is typically set on the most commonly-used option to make for more concise usage (i.e. `$ example *.js` instead of `$ example --files *.js`). + * + * ```js + * const optionDefinitions = [ + * { name: 'files', multiple: true, defaultOption: true } + * ] + * ``` + * + * | # | argv input | commandLineArgs() output | + * | --- | ------------ | ------------ | + * | 1 | `--files one.js two.js` | `{ files: [ 'one.js', 'two.js' ] }` | + * | 2 | `one.js two.js` | `{ files: [ 'one.js', 'two.js' ] }` | + * | 3 | `*` | `{ files: [ 'one.js', 'two.js' ] }` | + * + * @type {boolean} + */ + this.defaultOption = definition.defaultOption; + + /** + * An initial value for the option. + * + * ```js + * const optionDefinitions = [ + * { name: 'files', multiple: true, defaultValue: [ 'one.js' ] }, + * { name: 'max', type: Number, defaultValue: 3 } + * ] + * ``` + * + * | # | argv input | commandLineArgs() output | + * | --- | ------------ | ------------ | + * | 1 | | `{ files: [ 'one.js' ], max: 3 }` | + * | 2 | `--files two.js` | `{ files: [ 'two.js' ], max: 3 }` | + * | 3 | `--max 4` | `{ files: [ 'one.js' ], max: 4 }` | + * + * @type {*} + */ + this.defaultValue = definition.defaultValue; + + /** + * When your app has a large amount of options it makes sense to organise them in groups. + * + * There are two automatic groups: `_all` (contains all options) and `_none` (contains options without a `group` specified in their definition). + * + * ```js + * const optionDefinitions = [ + * { name: 'verbose', group: 'standard' }, + * { name: 'help', group: [ 'standard', 'main' ] }, + * { name: 'compress', group: [ 'server', 'main' ] }, + * { name: 'static', group: 'server' }, + * { name: 'debug' } + * ] + * ``` + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
#Command LinecommandLineArgs() output
1--verbose

+    *{
+    *  _all: { verbose: true },
+    *  standard: { verbose: true }
+    *}
+    *
2--debug

+    *{
+    *  _all: { debug: true },
+    *  _none: { debug: true }
+    *}
+    *
3--verbose --debug --compress

+    *{
+    *  _all: {
+    *    verbose: true,
+    *    debug: true,
+    *    compress: true
+    *  },
+    *  standard: { verbose: true },
+    *  server: { compress: true },
+    *  main: { compress: true },
+    *  _none: { debug: true }
+    *}
+    *
4--compress

+    *{
+    *  _all: { compress: true },
+    *  server: { compress: true },
+    *  main: { compress: true }
+    *}
+    *
+ * + * @type {string|string[]} + */ + this.group = definition.group; + + /* pick up any remaining properties */ + for (const prop in definition) { + if (!this[prop]) this[prop] = definition[prop]; + } + } + + isBoolean () { + return this.type === Boolean || (t$4.isFunction(this.type) && this.type.name === 'Boolean') + } + + isMultiple () { + return this.multiple || this.lazyMultiple + } + + static create (def) { + const result = new this(def); + return result + } +} + +/** + * @module option-definitions + */ + +/** + * @alias module:option-definitions + */ +class Definitions extends Array { + /** + * validate option definitions + * @param {boolean} [caseInsensitive=false] - whether arguments will be parsed in a case insensitive manner + * @returns {string} + */ + validate (caseInsensitive) { + const someHaveNoName = this.some(def => !def.name); + if (someHaveNoName) { + halt( + 'INVALID_DEFINITIONS', + 'Invalid option definitions: the `name` property is required on each definition' + ); + } + + const someDontHaveFunctionType = this.some(def => def.type && typeof def.type !== 'function'); + if (someDontHaveFunctionType) { + halt( + 'INVALID_DEFINITIONS', + 'Invalid option definitions: the `type` property must be a setter fuction (default: `Boolean`)' + ); + } + + let invalidOption; + + const numericAlias = this.some(def => { + invalidOption = def; + return t$4.isDefined(def.alias) && t$4.isNumber(def.alias) + }); + if (numericAlias) { + halt( + 'INVALID_DEFINITIONS', + 'Invalid option definition: to avoid ambiguity an alias cannot be numeric [--' + invalidOption.name + ' alias is -' + invalidOption.alias + ']' + ); + } + + const multiCharacterAlias = this.some(def => { + invalidOption = def; + return t$4.isDefined(def.alias) && def.alias.length !== 1 + }); + if (multiCharacterAlias) { + halt( + 'INVALID_DEFINITIONS', + 'Invalid option definition: an alias must be a single character' + ); + } + + const hypenAlias = this.some(def => { + invalidOption = def; + return def.alias === '-' + }); + if (hypenAlias) { + halt( + 'INVALID_DEFINITIONS', + 'Invalid option definition: an alias cannot be "-"' + ); + } + + const duplicateName = hasDuplicates$1(this.map(def => caseInsensitive ? def.name.toLowerCase() : def.name)); + if (duplicateName) { + halt( + 'INVALID_DEFINITIONS', + 'Two or more option definitions have the same name' + ); + } + + const duplicateAlias = hasDuplicates$1(this.map(def => caseInsensitive && t$4.isDefined(def.alias) ? def.alias.toLowerCase() : def.alias)); + if (duplicateAlias) { + halt( + 'INVALID_DEFINITIONS', + 'Two or more option definitions have the same alias' + ); + } + + const duplicateDefaultOption = this.filter(def => def.defaultOption === true).length > 1; + if (duplicateDefaultOption) { + halt( + 'INVALID_DEFINITIONS', + 'Only one option definition can be the defaultOption' + ); + } + + const defaultBoolean = this.some(def => { + invalidOption = def; + return def.isBoolean() && def.defaultOption + }); + if (defaultBoolean) { + halt( + 'INVALID_DEFINITIONS', + `A boolean option ["${invalidOption.name}"] can not also be the defaultOption.` + ); + } + } + + /** + * Get definition by option arg (e.g. `--one` or `-o`) + * @param {string} [arg] the argument name to get the definition for + * @param {boolean} [caseInsensitive] whether to use case insensitive comparisons when finding the appropriate definition + * @returns {Definition} + */ + get (arg, caseInsensitive) { + if (isOption(arg)) { + if (re$2.short.test(arg)) { + const shortOptionName = getOptionName(arg); + if (caseInsensitive) { + const lowercaseShortOptionName = shortOptionName.toLowerCase(); + return this.find(def => t$4.isDefined(def.alias) && def.alias.toLowerCase() === lowercaseShortOptionName) + } else { + return this.find(def => def.alias === shortOptionName) + } + } else { + const optionName = getOptionName(arg); + if (caseInsensitive) { + const lowercaseOptionName = optionName.toLowerCase(); + return this.find(def => def.name.toLowerCase() === lowercaseOptionName) + } else { + return this.find(def => def.name === optionName) + } + } + } else { + return this.find(def => def.name === arg) + } + } + + getDefault () { + return this.find(def => def.defaultOption === true) + } + + isGrouped () { + return this.some(def => def.group) + } + + whereGrouped () { + return this.filter(containsValidGroup) + } + + whereNotGrouped () { + return this.filter(def => !containsValidGroup(def)) + } + + whereDefaultValueSet () { + return this.filter(def => t$4.isDefined(def.defaultValue)) + } + + static from (definitions, caseInsensitive) { + if (definitions instanceof this) return definitions + const result = super.from(arrayify$2(definitions), def => OptionDefinition.create(def)); + result.validate(caseInsensitive); + return result + } +} + +function halt (name, message) { + const err = new Error(message); + err.name = name; + throw err +} + +function containsValidGroup (def) { + return arrayify$2(def.group).some(group => group) +} + +function hasDuplicates$1 (array) { + const items = {}; + for (let i = 0; i < array.length; i++) { + const value = array[i]; + if (items[value]) { + return true + } else { + if (t$4.isDefined(value)) items[value] = true; + } + } +} + +/** + * @module argv-parser + */ + +/** + * @alias module:argv-parser + */ +class ArgvParser { + /** + * @param {OptionDefinitions} - Definitions array + * @param {object} [options] - Options + * @param {string[]} [options.argv] - Overrides `process.argv` + * @param {boolean} [options.stopAtFirstUnknown] - + * @param {boolean} [options.caseInsensitive] - Arguments will be parsed in a case insensitive manner. Defaults to false. + */ + constructor (definitions, options) { + this.options = Object.assign({}, options); + /** + * Option Definitions + */ + this.definitions = Definitions.from(definitions, this.options.caseInsensitive); + + /** + * Argv + */ + this.argv = ArgvArray.from(this.options.argv); + if (this.argv.hasCombinedShortOptions()) { + findReplace(this.argv, re$2.combinedShort.test.bind(re$2.combinedShort), arg => { + arg = arg.slice(1); + return arg.split('').map(letter => ({ origArg: `-${arg}`, arg: '-' + letter })) + }); + } + } + + /** + * Yields one `{ event, name, value, arg, def }` argInfo object for each arg in `process.argv` (or `options.argv`). + */ + * [Symbol.iterator] () { + const definitions = this.definitions; + + let def; + let value; + let name; + let event; + let singularDefaultSet = false; + let unknownFound = false; + let origArg; + + for (let arg of this.argv) { + if (t$4.isPlainObject(arg)) { + origArg = arg.origArg; + arg = arg.arg; + } + + if (unknownFound && this.options.stopAtFirstUnknown) { + yield { event: 'unknown_value', arg, name: '_unknown', value: undefined }; + continue + } + + /* handle long or short option */ + if (isOption(arg)) { + def = definitions.get(arg, this.options.caseInsensitive); + value = undefined; + if (def) { + value = def.isBoolean() ? true : null; + event = 'set'; + } else { + event = 'unknown_option'; + } + + /* handle --option-value notation */ + } else if (isOptionEqualsNotation(arg)) { + const matches = arg.match(re$2.optEquals); + def = definitions.get(matches[1], this.options.caseInsensitive); + if (def) { + if (def.isBoolean()) { + yield { event: 'unknown_value', arg, name: '_unknown', value, def }; + event = 'set'; + value = true; + } else { + event = 'set'; + value = matches[2]; + } + } else { + event = 'unknown_option'; + } + + /* handle value */ + } else if (isValue$4(arg)) { + if (def) { + value = arg; + event = 'set'; + } else { + /* get the defaultOption */ + def = this.definitions.getDefault(); + if (def && !singularDefaultSet) { + value = arg; + event = 'set'; + } else { + event = 'unknown_value'; + def = undefined; + } + } + } + + name = def ? def.name : '_unknown'; + const argInfo = { event, arg, name, value, def }; + if (origArg) { + argInfo.subArg = arg; + argInfo.arg = origArg; + } + yield argInfo; + + /* unknownFound logic */ + if (name === '_unknown') unknownFound = true; + + /* singularDefaultSet logic */ + if (def && def.defaultOption && !def.isMultiple() && event === 'set') singularDefaultSet = true; + + /* reset values once consumed and yielded */ + if (def && def.isBoolean()) def = undefined; + /* reset the def if it's a singular which has been set */ + if (def && !def.multiple && t$4.isDefined(value) && value !== null) { + def = undefined; + } + value = undefined; + event = undefined; + name = undefined; + origArg = undefined; + } + } +} + +const _value$1 = new WeakMap(); + +/** + * Encapsulates behaviour (defined by an OptionDefinition) when setting values + */ +class Option { + constructor (definition) { + this.definition = new OptionDefinition(definition); + this.state = null; /* set or default */ + this.resetToDefault(); + } + + get () { + return _value$1.get(this) + } + + set (val) { + this._set(val, 'set'); + } + + _set (val, state) { + const def = this.definition; + if (def.isMultiple()) { + /* don't add null or undefined to a multiple */ + if (val !== null && val !== undefined) { + const arr = this.get(); + if (this.state === 'default') arr.length = 0; + arr.push(def.type(val)); + this.state = state; + } + } else { + /* throw if already set on a singlar defaultOption */ + if (!def.isMultiple() && this.state === 'set') { + const err = new Error(`Singular option already set [${this.definition.name}=${this.get()}]`); + err.name = 'ALREADY_SET'; + err.value = val; + err.optionName = def.name; + throw err + } else if (val === null || val === undefined) { + _value$1.set(this, val); + // /* required to make 'partial: defaultOption with value equal to defaultValue 2' pass */ + // if (!(def.defaultOption && !def.isMultiple())) { + // this.state = state + // } + } else { + _value$1.set(this, def.type(val)); + this.state = state; + } + } + } + + resetToDefault () { + if (t$4.isDefined(this.definition.defaultValue)) { + if (this.definition.isMultiple()) { + _value$1.set(this, arrayify$2(this.definition.defaultValue).slice()); + } else { + _value$1.set(this, this.definition.defaultValue); + } + } else { + if (this.definition.isMultiple()) { + _value$1.set(this, []); + } else { + _value$1.set(this, null); + } + } + this.state = 'default'; + } + + static create (definition) { + definition = new OptionDefinition(definition); + if (definition.isBoolean()) { + return FlagOption.create(definition) + } else { + return new this(definition) + } + } +} + +class FlagOption extends Option { + set (val) { + super.set(true); + } + + static create (def) { + return new this(def) + } +} + +/** + * A map of { DefinitionNameString: Option }. By default, an Output has an `_unknown` property and any options with defaultValues. + */ +class Output extends Map { + constructor (definitions) { + super(); + /** + * @type {OptionDefinitions} + */ + this.definitions = Definitions.from(definitions); + + /* by default, an Output has an `_unknown` property and any options with defaultValues */ + this.set('_unknown', Option.create({ name: '_unknown', multiple: true })); + for (const def of this.definitions.whereDefaultValueSet()) { + this.set(def.name, Option.create(def)); + } + } + + toObject (options) { + options = options || {}; + const output = {}; + for (const item of this) { + const name = options.camelCase && item[0] !== '_unknown' ? camelCase$1(item[0]) : item[0]; + const option = item[1]; + if (name === '_unknown' && !option.get().length) continue + output[name] = option.get(); + } + + if (options.skipUnknown) delete output._unknown; + return output + } +} + +class GroupedOutput extends Output { + toObject (options) { + const superOutputNoCamel = super.toObject({ skipUnknown: options.skipUnknown }); + const superOutput = super.toObject(options); + const unknown = superOutput._unknown; + delete superOutput._unknown; + const grouped = { + _all: superOutput + }; + if (unknown && unknown.length) grouped._unknown = unknown; + + this.definitions.whereGrouped().forEach(def => { + const name = options.camelCase ? camelCase$1(def.name) : def.name; + const outputValue = superOutputNoCamel[def.name]; + for (const groupName of arrayify$2(def.group)) { + grouped[groupName] = grouped[groupName] || {}; + if (t$4.isDefined(outputValue)) { + grouped[groupName][name] = outputValue; + } + } + }); + + this.definitions.whereNotGrouped().forEach(def => { + const name = options.camelCase ? camelCase$1(def.name) : def.name; + const outputValue = superOutputNoCamel[def.name]; + if (t$4.isDefined(outputValue)) { + if (!grouped._none) grouped._none = {}; + grouped._none[name] = outputValue; + } + }); + return grouped + } +} + +/** + * @module command-line-args + */ + +/** + * Returns an object containing all option values set on the command line. By default it parses the global [`process.argv`](https://nodejs.org/api/process.html#process_process_argv) array. + * + * Parsing is strict by default - an exception is thrown if the user sets a singular option more than once or sets an unknown value or option (one without a valid [definition](https://github.com/75lb/command-line-args/blob/master/doc/option-definition.md)). To be more permissive, enabling [partial](https://github.com/75lb/command-line-args/wiki/Partial-mode-example) or [stopAtFirstUnknown](https://github.com/75lb/command-line-args/wiki/stopAtFirstUnknown) modes will return known options in the usual manner while collecting unknown arguments in a separate `_unknown` property. + * + * @param {Array} - An array of [OptionDefinition](https://github.com/75lb/command-line-args/blob/master/doc/option-definition.md) objects + * @param {object} [options] - Options. + * @param {string[]} [options.argv] - An array of strings which, if present will be parsed instead of `process.argv`. + * @param {boolean} [options.partial] - If `true`, an array of unknown arguments is returned in the `_unknown` property of the output. + * @param {boolean} [options.stopAtFirstUnknown] - If `true`, parsing will stop at the first unknown argument and the remaining arguments returned in `_unknown`. When set, `partial: true` is also implied. + * @param {boolean} [options.camelCase] - If `true`, options with hypenated names (e.g. `move-to`) will be returned in camel-case (e.g. `moveTo`). + * @param {boolean} [options.caseInsensitive] - If `true`, the case of each option name or alias parsed is insignificant. In other words, both `--Verbose` and `--verbose`, `-V` and `-v` would be equivalent. Defaults to false. + * @returns {object} + * @throws `UNKNOWN_OPTION` If `options.partial` is false and the user set an undefined option. The `err.optionName` property contains the arg that specified an unknown option, e.g. `--one`. + * @throws `UNKNOWN_VALUE` If `options.partial` is false and the user set a value unaccounted for by an option definition. The `err.value` property contains the unknown value, e.g. `5`. + * @throws `ALREADY_SET` If a user sets a singular, non-multiple option more than once. The `err.optionName` property contains the option name that has already been set, e.g. `one`. + * @throws `INVALID_DEFINITIONS` + * - If an option definition is missing the required `name` property + * - If an option definition has a `type` value that's not a function + * - If an alias is numeric, a hyphen or a length other than 1 + * - If an option definition name was used more than once + * - If an option definition alias was used more than once + * - If more than one option definition has `defaultOption: true` + * - If a `Boolean` option is also set as the `defaultOption`. + * @alias module:command-line-args + */ +function commandLineArgs (optionDefinitions, options) { + options = options || {}; + if (options.stopAtFirstUnknown) options.partial = true; + optionDefinitions = Definitions.from(optionDefinitions, options.caseInsensitive); + + const parser = new ArgvParser(optionDefinitions, { + argv: options.argv, + stopAtFirstUnknown: options.stopAtFirstUnknown, + caseInsensitive: options.caseInsensitive + }); + + const OutputClass = optionDefinitions.isGrouped() ? GroupedOutput : Output; + const output = new OutputClass(optionDefinitions); + + /* Iterate the parser setting each known value to the output. Optionally, throw on unknowns. */ + for (const argInfo of parser) { + const arg = argInfo.subArg || argInfo.arg; + if (!options.partial) { + if (argInfo.event === 'unknown_value') { + const err = new Error(`Unknown value: ${arg}`); + err.name = 'UNKNOWN_VALUE'; + err.value = arg; + throw err + } else if (argInfo.event === 'unknown_option') { + const err = new Error(`Unknown option: ${arg}`); + err.name = 'UNKNOWN_OPTION'; + err.optionName = arg; + throw err + } + } + + let option; + if (output.has(argInfo.name)) { + option = output.get(argInfo.name); + } else { + option = Option.create(argInfo.def); + output.set(argInfo.name, option); + } + + if (argInfo.name === '_unknown') { + option.set(arg); + } else { + option.set(argInfo.value); + } + } + + return output.toObject({ skipUnknown: !options.partial, camelCase: options.camelCase }) +} + +var dist$5 = commandLineArgs; + +var cliArgs = /*@__PURE__*/getDefaultExportFromCjs(dist$5); + +function parseArgsStringToArgv(value, env, file) { + // ([^\s'"]([^\s'"]*(['"])([^\3]*?)\3)+[^\s'"]*) Matches nested quotes until the first space outside of quotes + // [^\s'"]+ or Match if not a space ' or " + // (['"])([^\5]*?)\5 or Match "quoted text" without quotes + // `\3` and `\5` are a backreference to the quote style (' or ") captured + var myRegexp = /([^\s'"]([^\s'"]*(['"])([^\3]*?)\3)+[^\s'"]*)|[^\s'"]+|(['"])([^\5]*?)\5/gi; + var myString = value; + var myArray = []; + if (env) { + myArray.push(env); + } + if (file) { + myArray.push(file); + } + var match; + do { + // Each call to exec returns the next regex match as an array + match = myRegexp.exec(myString); + if (match !== null) { + // Index 1 in the array is the captured group if it exists + // Index 0 is the matched text, which we use if no captured group exists + myArray.push(firstString(match[1], match[6], match[0])); + } + } while (match !== null); + return myArray; +} +// Accepts any number of arguments, and returns the first one that is a string +// (even an empty string) +function firstString() { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + for (var i = 0; i < args.length; i++) { + var arg = args[i]; + if (typeof arg === "string") { + return arg; + } + } +} + +/** + * 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_es2018 = {exports: {}}; + +/** + * web-streams-polyfill v3.2.1 + */ + +var hasRequiredPonyfill_es2018; + +function requirePonyfill_es2018 () { + if (hasRequiredPonyfill_es2018) return ponyfill_es2018.exports; + 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_es2018.exports)); + return ponyfill_es2018.exports; +} + +/* 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$3 = _Blob; +var Blob$4 = Blob$3; + +const _File = class File extends Blob$4 { + #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$4 && + /^(File)$/.test(object[Symbol.toStringTag]) + } +}; + +/** @type {typeof globalThis.File} */// @ts-ignore +const File$1 = _File; + +/*! formdata-polyfill. MIT License. Jimmy Wärting */ + + +var {toStringTag:t$3,iterator:i$4,hasInstance:h$1}=Symbol, +r$1=Math.random, +m$1='append,set,get,getAll,delete,keys,values,entries,forEach,constructor'.split(','), +f$2=(a,b,c)=>(a+='',/^(Blob|File)$/.test(b && b[t$3])?[(c=c!==void 0?c+'':b[t$3]=='File'?b.name:'blob',a),b.name!==c||b[t$3]=='blob'?new File$1([b],c,b):b]:[a,b+'']), +e$1=(c,f)=>(f?c:c.replace(/\r?\n|\r/g,'\r\n')).replace(/\n/g,'%0A').replace(/\r/g,'%0D').replace(/"/g,'%22'), +x$1=(n, a, e)=>{if(a.lengthtypeof o[m]!='function')} +append(...a){x$1('append',arguments,2);this.#d.push(f$2(...a));} +delete(a){x$1('delete',arguments,1);a+='';this.#d=this.#d.filter(([b])=>b!==a);} +get(a){x$1('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$1('has',arguments,1);a+='';return this.#d.some(b=>b[0]===a)} +forEach(a,b){x$1('forEach',arguments,1);for(var [c,d]of this)a.call(b,d,c,this);} +set(...a){x$1('set',arguments,2);var b=[],c=!0;a=f$2(...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$4){ +var b=`${r$1()}${r$1()}`.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$1(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$2 = 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$2 = 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$4.pipeline); +const INTERNALS$6 = Symbol('Body internals'); + +/** + * Body mixin + * + * Ref: https://fetch.spec.whatwg.org/#body + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +let Body$2 = 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$2(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$4) ; else if (body instanceof FormData$1) { + // 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$4.Readable.from(body); + } else if (isBlob$2(body)) { + stream = Stream$4.Readable.from(body.stream()); + } + + this[INTERNALS$6] = { + body, + stream, + boundary, + disturbed: false, + error: null + }; + this.size = size; + + if (body instanceof Stream$4) { + body.on('error', error_ => { + const error = error_ instanceof FetchBaseError ? + error_ : + new FetchError$2(`Invalid response body while trying to fetch ${this.url}: ${error_.message}`, 'system', error_); + this[INTERNALS$6].error = error; + }); + } + } + + get body() { + return this[INTERNALS$6].stream; + } + + get bodyUsed() { + return this[INTERNALS$6].disturbed; + } + + /** + * Decode response as ArrayBuffer + * + * @return Promise + */ + async arrayBuffer() { + const {buffer, byteOffset, byteLength} = await consumeBody$2(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$1(); + 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 multipartParser; }); + 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$6].body && this[INTERNALS$6].body.type) || ''; + const buf = await this.arrayBuffer(); + + return new Blob$4([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$2(this); + return new TextDecoder().decode(buffer); + } + + /** + * Decode response as buffer (non-spec api) + * + * @return Promise + */ + buffer() { + return consumeBody$2(this); + } +}; + +Body$2.prototype.buffer = node_util.deprecate(Body$2.prototype.buffer, 'Please use \'response.arrayBuffer()\' instead of \'response.buffer()\'', 'node-fetch#buffer'); + +// In browsers, all properties are enumerable. +Object.defineProperties(Body$2.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$2(data) { + if (data[INTERNALS$6].disturbed) { + throw new TypeError(`body used already for: ${data.url}`); + } + + data[INTERNALS$6].disturbed = true; + + if (data[INTERNALS$6].error) { + throw data[INTERNALS$6].error; + } + + const {body} = data; + + // Body is null + if (body === null) { + return node_buffer.Buffer.alloc(0); + } + + /* c8 ignore next 3 */ + if (!(body instanceof Stream$4)) { + 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$2(`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$2(`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$2(`Could not create Buffer from response body for ${data.url}: ${error.message}`, 'system', error); + } + } else { + throw new FetchError$2(`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$8 = (instance, highWaterMark) => { + let p1; + let p2; + let {body} = instance[INTERNALS$6]; + + // 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$4) && (typeof body.getBoundary !== 'function')) { + // Tee instance body + p1 = new Stream$4.PassThrough({highWaterMark}); + p2 = new Stream$4.PassThrough({highWaterMark}); + body.pipe(p1); + body.pipe(p2); + // Set instance body to teed body and return the other teed body + instance[INTERNALS$6].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$2 = (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$2(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$1) { + return `multipart/form-data; boundary=${request[INTERNALS$6].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$4) { + 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$1 = request => { + const {body} = request[INTERNALS$6]; + + // Body is null or undefined + if (body === null) { + return 0; + } + + // Body is Blob + if (isBlob$2(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$1 = 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$a.validateHeaderName === 'function' ? + http$a.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$a.validateHeaderValue === 'function' ? + http$a.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. + * + */ +let Headers$2 = 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$2.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$2( + 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$5 = 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 + */ +let Response$2 = class Response extends Body$2 { + 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$2(options.headers); + + if (body !== null && !headers.has('Content-Type')) { + const contentType = extractContentType$2(body, this); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + this[INTERNALS$5] = { + type: 'default', + url: options.url, + status, + statusText: options.statusText || '', + headers, + counter: options.counter, + highWaterMark: options.highWaterMark + }; + } + + get type() { + return this[INTERNALS$5].type; + } + + get url() { + return this[INTERNALS$5].url || ''; + } + + get status() { + return this[INTERNALS$5].status; + } + + /** + * Convenience property representing if the request ended normally + */ + get ok() { + return this[INTERNALS$5].status >= 200 && this[INTERNALS$5].status < 300; + } + + get redirected() { + return this[INTERNALS$5].counter > 0; + } + + get statusText() { + return this[INTERNALS$5].statusText; + } + + get headers() { + return this[INTERNALS$5].headers; + } + + get highWaterMark() { + return this[INTERNALS$5].highWaterMark; + } + + /** + * Clone this response + * + * @return Response + */ + clone() { + return new Response(clone$8(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$5].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$2(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$2.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 = 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$4 = Symbol('Request internals'); + +/** + * Check if `obj` is an instance of Request. + * + * @param {*} object + * @return {boolean} + */ +const isRequest$2 = object => { + return ( + typeof object === 'object' && + typeof object[INTERNALS$4] === '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 + */ +let Request$2 = class Request extends Body$2 { + 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$2(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$2(init) && 'data' in init) { + doBadDataWarn(); + } + + // eslint-disable-next-line no-eq-null, eqeqeq + if ((init.body != null || (isRequest$2(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$2(input) && input.body !== null ? + clone$8(input) : + null); + + super(inputBody, { + size: init.size || input.size || 0 + }); + + const headers = new Headers$2(init.headers || input.headers || {}); + + if (inputBody !== null && !headers.has('Content-Type')) { + const contentType = extractContentType$2(inputBody, this); + if (contentType) { + headers.set('Content-Type', contentType); + } + } + + let signal = isRequest$2(input) ? + input.signal : + null; + if ('signal' in init) { + signal = init.signal; + } + + // eslint-disable-next-line no-eq-null, eqeqeq + if (signal != null && !isAbortSignal$2(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$4] = { + 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$4].method; + } + + /** @returns {string} */ + get url() { + return urlLib.format(this[INTERNALS$4].parsedURL); + } + + /** @returns {Headers} */ + get headers() { + return this[INTERNALS$4].headers; + } + + get redirect() { + return this[INTERNALS$4].redirect; + } + + /** @returns {AbortSignal} */ + get signal() { + return this[INTERNALS$4].signal; + } + + // https://fetch.spec.whatwg.org/#dom-request-referrer + get referrer() { + if (this[INTERNALS$4].referrer === 'no-referrer') { + return ''; + } + + if (this[INTERNALS$4].referrer === 'client') { + return 'about:client'; + } + + if (this[INTERNALS$4].referrer) { + return this[INTERNALS$4].referrer.toString(); + } + + return undefined; + } + + get referrerPolicy() { + return this[INTERNALS$4].referrerPolicy; + } + + set referrerPolicy(referrerPolicy) { + this[INTERNALS$4].referrerPolicy = validateReferrerPolicy(referrerPolicy); + } + + /** + * Clone this request + * + * @return Request + */ + clone() { + return new Request(this); + } + + get [Symbol.toStringTag]() { + return 'Request'; + } +}; + +Object.defineProperties(Request$2.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$1 = request => { + const {parsedURL} = request[INTERNALS$4]; + const headers = new Headers$2(request[INTERNALS$4].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$1(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$4].referrer = determineRequestsReferrer(request); + } else { + request[INTERNALS$4].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$4].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); + } + + // 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$2 = 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$4(url, options_) { + return new Promise((resolve, reject) => { + // Build request object + const request = new Request$2(url, options_); + const {parsedURL, options} = getNodeRequestOptions$1(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$2(data, {headers: {'Content-Type': data.typeFull}}); + resolve(response); + return; + } + + // Wrap http.request into fetch + const send = (parsedURL.protocol === 'https:' ? https$8 : http$a).request; + const {signal} = request; + let response = null; + + const abort = () => { + const error = new AbortError$2('The operation was aborted.'); + reject(error); + if (request.body && request.body instanceof Stream$4.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$2(`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$2(`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$2(`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$2(`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$2(request.headers), + follow: request.follow, + counter: request.counter + 1, + agent: request.agent, + compress: request.compress, + method: request.method, + body: clone$8(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$4.Readable) { + reject(new FetchError$2('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$4(new Request$2(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$4.pipeline(response_, new Stream$4.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$2(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$2.Z_SYNC_FLUSH, + finishFlush: zlib$2.Z_SYNC_FLUSH + }; + + // For gzip + if (codings === 'gzip' || codings === 'x-gzip') { + body = Stream$4.pipeline(body, zlib$2.createGunzip(zlibOptions), error => { + if (error) { + reject(error); + } + }); + response = new Response$2(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$4.pipeline(response_, new Stream$4.PassThrough(), error => { + if (error) { + reject(error); + } + }); + raw.once('data', chunk => { + // See http://stackoverflow.com/questions/37519828 + if ((chunk[0] & 0x0F) === 0x08) { + body = Stream$4.pipeline(body, zlib$2.createInflate(), error => { + if (error) { + reject(error); + } + }); + } else { + body = Stream$4.pipeline(body, zlib$2.createInflateRaw(), error => { + if (error) { + reject(error); + } + }); + } + + response = new Response$2(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$2(body, responseOptions); + resolve(response); + } + }); + return; + } + + // For br + if (codings === 'br') { + body = Stream$4.pipeline(body, zlib$2.createBrotliDecompress(), error => { + if (error) { + reject(error); + } + }); + response = new Response$2(body, responseOptions); + resolve(response); + return; + } + + // Otherwise, use response as-is + response = new Response$2(body, responseOptions); + resolve(response); + }); + + // eslint-disable-next-line promise/prefer-await-to-then + writeToStream$1(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); + }); + }); +} + +const configstore = new Configstore( +/** + * The `VITEST_POOL_ID` and `VITEST_WORKER_ID` are used here to ensure that our `configstore` + * tests don't clash with one another. + * + * @see {@link https://vitest.dev/guide/migration.html#:~:text=Vitest%20counterparts.-,Envs,-Just%20like%20Jest} + */ +`${pkg.name}-${process.env.NODE_ENV || 'production'}${process.env.VITEST_POOL_ID || ''}${process.env.VITEST_WORKER_ID || ''}`); + +/** + * Retrieves stored user data values from env variables or configstore, + * with env variables taking precedent + */ +function getCurrentConfig() { + const apiKey = process.env.RDME_API_KEY || configstore.get('apiKey'); + const email = process.env.RDME_EMAIL || configstore.get('email'); + const project = process.env.RDME_PROJECT || configstore.get('project'); + return { apiKey, email, project }; +} + +var src$7 = {exports: {}}; + +var browser = {exports: {}}; + +/** + * Helpers. + */ + +var ms; +var hasRequiredMs; + +function requireMs () { + if (hasRequiredMs) return ms; + hasRequiredMs = 1; + var s = 1000; + var m = s * 60; + var h = m * 60; + var d = h * 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 + */ + + ms = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(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(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; + 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) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return Math.round(ms / d) + 'd'; + } + if (msAbs >= h) { + return Math.round(ms / h) + 'h'; + } + if (msAbs >= m) { + return Math.round(ms / m) + '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) { + return plural(ms, msAbs, h, 'hour'); + } + if (msAbs >= m) { + return plural(ms, msAbs, m, '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' : ''); + } + return ms; +} + +var common$i; +var hasRequiredCommon$1; + +function requireCommon$1 () { + if (hasRequiredCommon$1) return common$i; + hasRequiredCommon$1 = 1; + /** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + */ + + function setup(env) { + createDebug.debug = createDebug; + createDebug.default = createDebug; + createDebug.coerce = coerce; + createDebug.disable = disable; + createDebug.enable = enable; + createDebug.enabled = enabled; + createDebug.humanize = requireMs(); + createDebug.destroy = destroy; + + Object.keys(env).forEach(key => { + createDebug[key] = env[key]; + }); + + /** + * The currently active debug mode names, and names to skip. + */ + + createDebug.names = []; + createDebug.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". + */ + createDebug.formatters = {}; + + /** + * Selects a color for a debug namespace + * @param {String} namespace The namespace string for the debug instance to be colored + * @return {Number|String} An ANSI color code for the given namespace + * @api private + */ + function selectColor(namespace) { + let hash = 0; + + for (let i = 0; i < namespace.length; i++) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } + + return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; + } + createDebug.selectColor = selectColor; + + /** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + function createDebug(namespace) { + let prevTime; + let enableOverride = null; + let namespacesCache; + let enabledCache; + + function debug(...args) { + // Disabled? + if (!debug.enabled) { + return; + } + + const self = debug; + + // Set `diff` timestamp + const curr = Number(new Date()); + const ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; + + args[0] = createDebug.coerce(args[0]); + + if (typeof args[0] !== 'string') { + // Anything else let's inspect with %O + args.unshift('%O'); + } + + // Apply any `formatters` transformations + let index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { + // If we encounter an escaped % then don't increase the array index + if (match === '%%') { + return '%'; + } + index++; + const formatter = createDebug.formatters[format]; + if (typeof formatter === 'function') { + const 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.) + createDebug.formatArgs.call(self, args); + + const logFn = self.log || createDebug.log; + logFn.apply(self, args); + } + + debug.namespace = namespace; + debug.useColors = createDebug.useColors(); + debug.color = createDebug.selectColor(namespace); + debug.extend = extend; + debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. + + Object.defineProperty(debug, 'enabled', { + enumerable: true, + configurable: false, + get: () => { + if (enableOverride !== null) { + return enableOverride; + } + if (namespacesCache !== createDebug.namespaces) { + namespacesCache = createDebug.namespaces; + enabledCache = createDebug.enabled(namespace); + } + + return enabledCache; + }, + set: v => { + enableOverride = v; + } + }); + + // Env-specific initialization logic for debug instances + if (typeof createDebug.init === 'function') { + createDebug.init(debug); + } + + return debug; + } + + function extend(namespace, delimiter) { + const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); + newDebug.log = this.log; + return newDebug; + } + + /** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ + function enable(namespaces) { + createDebug.save(namespaces); + createDebug.namespaces = namespaces; + + createDebug.names = []; + createDebug.skips = []; + + let i; + const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + const len = split.length; + + for (i = 0; i < len; i++) { + if (!split[i]) { + // ignore empty strings + continue; + } + + namespaces = split[i].replace(/\*/g, '.*?'); + + if (namespaces[0] === '-') { + createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$')); + } else { + createDebug.names.push(new RegExp('^' + namespaces + '$')); + } + } + } + + /** + * Disable debug output. + * + * @return {String} namespaces + * @api public + */ + function disable() { + const namespaces = [ + ...createDebug.names.map(toNamespace), + ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) + ].join(','); + createDebug.enable(''); + return namespaces; + } + + /** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + function enabled(name) { + if (name[name.length - 1] === '*') { + return true; + } + + let i; + let len; + + for (i = 0, len = createDebug.skips.length; i < len; i++) { + if (createDebug.skips[i].test(name)) { + return false; + } + } + + for (i = 0, len = createDebug.names.length; i < len; i++) { + if (createDebug.names[i].test(name)) { + return true; + } + } + + return false; + } + + /** + * Convert regexp to namespace + * + * @param {RegExp} regxep + * @return {String} namespace + * @api private + */ + function toNamespace(regexp) { + return regexp.toString() + .substring(2, regexp.toString().length - 2) + .replace(/\.\*\?$/, '*'); + } + + /** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + function coerce(val) { + if (val instanceof Error) { + return val.stack || val.message; + } + return val; + } + + /** + * XXX DO NOT USE. This is a temporary stub function. + * XXX It WILL be removed in the next major release. + */ + function destroy() { + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } + + createDebug.enable(createDebug.load()); + + return createDebug; + } + + common$i = setup; + return common$i; +} + +/* eslint-env browser */ + +var hasRequiredBrowser; + +function requireBrowser () { + if (hasRequiredBrowser) return browser.exports; + hasRequiredBrowser = 1; + (function (module, exports) { + /** + * This is the web browser implementation of `debug()`. + */ + + exports.formatArgs = formatArgs; + exports.save = save; + exports.load = load; + exports.useColors = useColors; + exports.storage = localstorage(); + exports.destroy = (() => { + let warned = false; + + return () => { + if (!warned) { + warned = true; + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } + }; + })(); + + /** + * Colors. + */ + + exports.colors = [ + '#0000CC', + '#0000FF', + '#0033CC', + '#0033FF', + '#0066CC', + '#0066FF', + '#0099CC', + '#0099FF', + '#00CC00', + '#00CC33', + '#00CC66', + '#00CC99', + '#00CCCC', + '#00CCFF', + '#3300CC', + '#3300FF', + '#3333CC', + '#3333FF', + '#3366CC', + '#3366FF', + '#3399CC', + '#3399FF', + '#33CC00', + '#33CC33', + '#33CC66', + '#33CC99', + '#33CCCC', + '#33CCFF', + '#6600CC', + '#6600FF', + '#6633CC', + '#6633FF', + '#66CC00', + '#66CC33', + '#9900CC', + '#9900FF', + '#9933CC', + '#9933FF', + '#99CC00', + '#99CC33', + '#CC0000', + '#CC0033', + '#CC0066', + '#CC0099', + '#CC00CC', + '#CC00FF', + '#CC3300', + '#CC3333', + '#CC3366', + '#CC3399', + '#CC33CC', + '#CC33FF', + '#CC6600', + '#CC6633', + '#CC9900', + '#CC9933', + '#CCCC00', + '#CCCC33', + '#FF0000', + '#FF0033', + '#FF0066', + '#FF0099', + '#FF00CC', + '#FF00FF', + '#FF3300', + '#FF3333', + '#FF3366', + '#FF3399', + '#FF33CC', + '#FF33FF', + '#FF6600', + '#FF6633', + '#FF9900', + '#FF9933', + '#FFCC00', + '#FFCC33' + ]; + + /** + * 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 + */ + + // eslint-disable-next-line complexity + 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' || window.process.__nwjs)) { + return true; + } + + // Internet Explorer and Edge do not support colors. + if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; + } + + // 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+)/)); + } + + /** + * Colorize log arguments if enabled. + * + * @api public + */ + + function formatArgs(args) { + args[0] = (this.useColors ? '%c' : '') + + this.namespace + + (this.useColors ? ' %c' : ' ') + + args[0] + + (this.useColors ? '%c ' : ' ') + + '+' + module.exports.humanize(this.diff); + + if (!this.useColors) { + return; + } + + const 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 + let index = 0; + let lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, match => { + if (match === '%%') { + return; + } + index++; + if (match === '%c') { + // We only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); + + args.splice(lastC, 0, c); + } + + /** + * Invokes `console.debug()` when available. + * No-op when `console.debug` is not a "function". + * If `console.debug` is not available, falls back + * to `console.log`. + * + * @api public + */ + exports.log = console.debug || console.log || (() => {}); + + /** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + function save(namespaces) { + try { + if (namespaces) { + exports.storage.setItem('debug', namespaces); + } else { + exports.storage.removeItem('debug'); + } + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } + } + + /** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + function load() { + let r; + try { + r = exports.storage.getItem('debug'); + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } + + // 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; + } + + /** + * 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 { + // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context + // The Browser also has localStorage in the global context. + return localStorage; + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } + } + + module.exports = requireCommon$1()(exports); + + const {formatters} = module.exports; + + /** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ + + formatters.j = function (v) { + try { + return JSON.stringify(v); + } catch (error) { + return '[UnexpectedJSONParseError]: ' + error.message; + } + }; + } (browser, browser.exports)); + return browser.exports; +} + +var node$1 = {exports: {}}; + +var hasFlag$2; +var hasRequiredHasFlag$2; + +function requireHasFlag$2 () { + if (hasRequiredHasFlag$2) return hasFlag$2; + hasRequiredHasFlag$2 = 1; + + hasFlag$2 = (flag, argv = process.argv) => { + const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); + const position = argv.indexOf(prefix + flag); + const terminatorPosition = argv.indexOf('--'); + return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); + }; + return hasFlag$2; +} + +var supportsColor_1$2; +var hasRequiredSupportsColor$2; + +function requireSupportsColor$2 () { + if (hasRequiredSupportsColor$2) return supportsColor_1$2; + hasRequiredSupportsColor$2 = 1; + const os = require$$0$7; + const tty = require$$1$5; + const hasFlag = requireHasFlag$2(); + + const {env} = process; + + let forceColor; + if (hasFlag('no-color') || + hasFlag('no-colors') || + hasFlag('color=false') || + hasFlag('color=never')) { + forceColor = 0; + } else if (hasFlag('color') || + hasFlag('colors') || + hasFlag('color=true') || + hasFlag('color=always')) { + forceColor = 1; + } + + if ('FORCE_COLOR' in env) { + if (env.FORCE_COLOR === 'true') { + forceColor = 1; + } else if (env.FORCE_COLOR === 'false') { + forceColor = 0; + } else { + forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3); + } + } + + function translateLevel(level) { + if (level === 0) { + return false; + } + + return { + level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3 + }; + } + + function supportsColor(haveStream, streamIsTTY) { + if (forceColor === 0) { + return 0; + } + + if (hasFlag('color=16m') || + hasFlag('color=full') || + hasFlag('color=truecolor')) { + return 3; + } + + if (hasFlag('color=256')) { + return 2; + } + + if (haveStream && !streamIsTTY && forceColor === undefined) { + return 0; + } + + const min = forceColor || 0; + + if (env.TERM === 'dumb') { + return min; + } + + if (process.platform === 'win32') { + // Windows 10 build 10586 is the first Windows release that supports 256 colors. + // Windows 10 build 14931 is the first release that supports 16m/TrueColor. + const osRelease = os.release().split('.'); + if ( + Number(osRelease[0]) >= 10 && + Number(osRelease[2]) >= 10586 + ) { + return Number(osRelease[2]) >= 14931 ? 3 : 2; + } + + return 1; + } + + if ('CI' in env) { + if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env) || env.CI_NAME === 'codeship') { + return 1; + } + + return min; + } + + if ('TEAMCITY_VERSION' in env) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; + } + + if (env.COLORTERM === 'truecolor') { + return 3; + } + + if ('TERM_PROGRAM' in env) { + const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); + + switch (env.TERM_PROGRAM) { + case 'iTerm.app': + return version >= 3 ? 3 : 2; + case 'Apple_Terminal': + return 2; + // No default + } + } + + if (/-256(color)?$/i.test(env.TERM)) { + return 2; + } + + if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { + return 1; + } + + if ('COLORTERM' in env) { + return 1; + } + + return min; + } + + function getSupportLevel(stream) { + const level = supportsColor(stream, stream && stream.isTTY); + return translateLevel(level); + } + + supportsColor_1$2 = { + supportsColor: getSupportLevel, + stdout: translateLevel(supportsColor(true, tty.isatty(1))), + stderr: translateLevel(supportsColor(true, tty.isatty(2))) + }; + return supportsColor_1$2; +} + +/** + * Module dependencies. + */ + +var hasRequiredNode$1; + +function requireNode$1 () { + if (hasRequiredNode$1) return node$1.exports; + hasRequiredNode$1 = 1; + (function (module, exports) { + const tty = require$$1$5; + const util = require$$0$9; + + /** + * This is the Node.js implementation of `debug()`. + */ + + exports.init = init; + exports.log = log; + exports.formatArgs = formatArgs; + exports.save = save; + exports.load = load; + exports.useColors = useColors; + exports.destroy = util.deprecate( + () => {}, + 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' + ); + + /** + * Colors. + */ + + exports.colors = [6, 2, 3, 4, 5, 1]; + + try { + // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) + // eslint-disable-next-line import/no-extraneous-dependencies + const supportsColor = requireSupportsColor$2(); + + if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { + exports.colors = [ + 20, + 21, + 26, + 27, + 32, + 33, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 56, + 57, + 62, + 63, + 68, + 69, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 92, + 93, + 98, + 99, + 112, + 113, + 128, + 129, + 134, + 135, + 148, + 149, + 160, + 161, + 162, + 163, + 164, + 165, + 166, + 167, + 168, + 169, + 170, + 171, + 172, + 173, + 178, + 179, + 184, + 185, + 196, + 197, + 198, + 199, + 200, + 201, + 202, + 203, + 204, + 205, + 206, + 207, + 208, + 209, + 214, + 215, + 220, + 221 + ]; + } + } catch (error) { + // Swallow - we only care if `supports-color` is available; it doesn't have to be. + } + + /** + * 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(key => { + return /^debug_/i.test(key); + }).reduce((obj, key) => { + // Camel-case + const prop = key + .substring(6) + .toLowerCase() + .replace(/_([a-z])/g, (_, k) => { + return k.toUpperCase(); + }); + + // Coerce string value into JS value + let 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; + }, {}); + + /** + * Is stdout a TTY? Colored output is enabled when `true`. + */ + + function useColors() { + return 'colors' in exports.inspectOpts ? + Boolean(exports.inspectOpts.colors) : + tty.isatty(process.stderr.fd); + } + + /** + * Adds ANSI color escape codes if enabled. + * + * @api public + */ + + function formatArgs(args) { + const {namespace: name, useColors} = this; + + if (useColors) { + const c = this.color; + const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); + const prefix = ` ${colorCode};1m${name} \u001B[0m`; + + args[0] = prefix + args[0].split('\n').join('\n' + prefix); + args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); + } else { + args[0] = getDate() + name + ' ' + args[0]; + } + } + + function getDate() { + if (exports.inspectOpts.hideDate) { + return ''; + } + return new Date().toISOString() + ' '; + } + + /** + * Invokes `util.format()` with the specified arguments and writes to stderr. + */ + + function log(...args) { + return process.stderr.write(util.format(...args) + '\n'); + } + + /** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + function save(namespaces) { + if (namespaces) { + process.env.DEBUG = namespaces; + } else { + // 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; + } + } + + /** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + + function load() { + return process.env.DEBUG; + } + + /** + * 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 = {}; + + const keys = Object.keys(exports.inspectOpts); + for (let i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } + } + + module.exports = requireCommon$1()(exports); + + const {formatters} = module.exports; + + /** + * Map %o to `util.inspect()`, all on a single line. + */ + + formatters.o = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts) + .split('\n') + .map(str => str.trim()) + .join(' '); + }; + + /** + * Map %O to `util.inspect()`, allowing multiple lines if needed. + */ + + formatters.O = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); + }; + } (node$1, node$1.exports)); + return node$1.exports; +} + +/** + * Detect Electron renderer / nwjs process, which is node, but we should + * treat as a browser. + */ + +if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { + src$7.exports = requireBrowser(); +} else { + src$7.exports = requireNode$1(); +} + +var srcExports = src$7.exports; +var debug$1 = /*@__PURE__*/getDefaultExportFromCjs(srcExports); + +const config = { + cli: pkg.name, + host: 'https://dash.readme.com', + hub: 'https://{project}.readme.io', // this is only used for the `open` command +}; + +const debugPackage = debug$1(config.cli); +/** + * Wrapper for debug statements. + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function debug(input) { + /* istanbul ignore next */ + if (isGHA() && !isTest()) { + if (typeof input === 'object') { + coreExports.debug(`rdme: ${JSON.stringify(input)}`); + } + else { + coreExports.debug(`rdme: ${input}`); + } + } + return debugPackage(input); +} +/** + * Wrapper for error statements. + */ +function error$n(input) { + /* istanbul ignore next */ + if (isGHA() && !isTest()) + return coreExports.error(input); + // eslint-disable-next-line no-console + return console.error(chalk$5.red(input)); +} +/** + * Wrapper for info/notice statements. + + */ +function info(input, opts = { + /** whether or not to prefix * the statement with this emoji: ℹ️ */ + includeEmojiPrefix: true, +}) { + /* istanbul ignore next */ + if (isGHA() && !isTest()) + return coreExports.notice(input); + /* istanbul ignore next */ + if (!opts.includeEmojiPrefix) + return console.info(input); // eslint-disable-line no-console + // eslint-disable-next-line no-console + return console.info(`ℹ️ ${input}`); +} +function oraOptions() { + // Disables spinner in tests so it doesn't pollute test output + const opts = { isSilent: isTest() }; + // Cleans up ora output so it prints nicely alongside debug logs + /* istanbul ignore next */ + if (debugPackage.enabled) + opts.isEnabled = false; + return opts; +} +/** + * Wrapper for warn statements. + * @param prefix Text that precedes the warning. + * This is *not* used in the GitHub Actions-formatted warning. + */ +function warn$1(input, prefix = 'Warning!') { + /* istanbul ignore next */ + if (isGHA() && !isTest()) + return coreExports.warning(input); + // eslint-disable-next-line no-console + return console.warn(chalk$5.yellow(`⚠️ ${prefix} ${input}`)); +} + +var isEmail$1 = {exports: {}}; + +var assertString = {exports: {}}; + +(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, assertString.exports)); + +var assertStringExports = assertString.exports; + +var isByteLength = {exports: {}}; + +(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = isByteLength; + + var _assertString = _interopRequireDefault(assertStringExports); + + 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, isByteLength.exports)); + +var isByteLengthExports = isByteLength.exports; + +var isFQDN = {exports: {}}; + +var merge$4 = {exports: {}}; + +(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$4, merge$4.exports)); + +var mergeExports = merge$4.exports; + +(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = isFQDN; + + var _assertString = _interopRequireDefault(assertStringExports); + + var _merge = _interopRequireDefault(mergeExports); + + 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, isFQDN.exports)); + +var isFQDNExports = isFQDN.exports; + +var isIP = {exports: {}}; + +(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = isIP; + + var _assertString = _interopRequireDefault(assertStringExports); + + 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, isIP.exports)); + +var isIPExports = isIP.exports; + +(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = isEmail; + + var _assertString = _interopRequireDefault(assertStringExports); + + var _isByteLength = _interopRequireDefault(isByteLengthExports); + + var _isFQDN = _interopRequireDefault(isFQDNExports); + + var _isIP = _interopRequireDefault(isIPExports); + + var _merge = _interopRequireDefault(mergeExports); + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + var default_email_options = { + allow_display_name: false, + allow_underscores: 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, + allow_underscores: options.allow_underscores + })) { + 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$1, isEmail$1.exports)); + +var isEmailExports = isEmail$1.exports; +var isEmail = /*@__PURE__*/getDefaultExportFromCjs(isEmailExports); + +var prompts$3 = {}; + +var kleur; +var hasRequiredKleur; + +function requireKleur () { + if (hasRequiredKleur) return kleur; + hasRequiredKleur = 1; + + const { FORCE_COLOR, NODE_DISABLE_COLORS, TERM } = process.env; + + const $ = { + enabled: !NODE_DISABLE_COLORS && TERM !== 'dumb' && FORCE_COLOR !== '0', + + // modifiers + reset: init(0, 0), + bold: init(1, 22), + dim: init(2, 22), + italic: init(3, 23), + underline: init(4, 24), + inverse: init(7, 27), + hidden: init(8, 28), + strikethrough: init(9, 29), + + // colors + black: init(30, 39), + red: init(31, 39), + green: init(32, 39), + yellow: init(33, 39), + blue: init(34, 39), + magenta: init(35, 39), + cyan: init(36, 39), + white: init(37, 39), + gray: init(90, 39), + grey: init(90, 39), + + // background colors + bgBlack: init(40, 49), + bgRed: init(41, 49), + bgGreen: init(42, 49), + bgYellow: init(43, 49), + bgBlue: init(44, 49), + bgMagenta: init(45, 49), + bgCyan: init(46, 49), + bgWhite: init(47, 49) + }; + + function run(arr, str) { + let i=0, tmp, beg='', end=''; + for (; i < arr.length; i++) { + tmp = arr[i]; + beg += tmp.open; + end += tmp.close; + if (str.includes(tmp.close)) { + str = str.replace(tmp.rgx, tmp.close + tmp.open); + } + } + return beg + str + end; + } + + function chain(has, keys) { + let ctx = { has, keys }; + + ctx.reset = $.reset.bind(ctx); + ctx.bold = $.bold.bind(ctx); + ctx.dim = $.dim.bind(ctx); + ctx.italic = $.italic.bind(ctx); + ctx.underline = $.underline.bind(ctx); + ctx.inverse = $.inverse.bind(ctx); + ctx.hidden = $.hidden.bind(ctx); + ctx.strikethrough = $.strikethrough.bind(ctx); + + ctx.black = $.black.bind(ctx); + ctx.red = $.red.bind(ctx); + ctx.green = $.green.bind(ctx); + ctx.yellow = $.yellow.bind(ctx); + ctx.blue = $.blue.bind(ctx); + ctx.magenta = $.magenta.bind(ctx); + ctx.cyan = $.cyan.bind(ctx); + ctx.white = $.white.bind(ctx); + ctx.gray = $.gray.bind(ctx); + ctx.grey = $.grey.bind(ctx); + + ctx.bgBlack = $.bgBlack.bind(ctx); + ctx.bgRed = $.bgRed.bind(ctx); + ctx.bgGreen = $.bgGreen.bind(ctx); + ctx.bgYellow = $.bgYellow.bind(ctx); + ctx.bgBlue = $.bgBlue.bind(ctx); + ctx.bgMagenta = $.bgMagenta.bind(ctx); + ctx.bgCyan = $.bgCyan.bind(ctx); + ctx.bgWhite = $.bgWhite.bind(ctx); + + return ctx; + } + + function init(open, close) { + let blk = { + open: `\x1b[${open}m`, + close: `\x1b[${close}m`, + rgx: new RegExp(`\\x1b\\[${close}m`, 'g') + }; + return function (txt) { + if (this !== void 0 && this.has !== void 0) { + this.has.includes(open) || (this.has.push(open),this.keys.push(blk)); + return txt === void 0 ? this : $.enabled ? run(this.keys, txt+'') : txt+''; + } + return txt === void 0 ? chain([open], [blk]) : $.enabled ? run([blk], txt+'') : txt+''; + }; + } + + kleur = $; + return kleur; +} + +var action$1; +var hasRequiredAction$1; + +function requireAction$1 () { + if (hasRequiredAction$1) return action$1; + hasRequiredAction$1 = 1; + + action$1 = (key, isSelect) => { + if (key.meta && key.name !== 'escape') return; + + if (key.ctrl) { + if (key.name === 'a') return 'first'; + if (key.name === 'c') return 'abort'; + if (key.name === 'd') return 'abort'; + if (key.name === 'e') return 'last'; + if (key.name === 'g') return 'reset'; + } + + if (isSelect) { + if (key.name === 'j') return 'down'; + if (key.name === 'k') return 'up'; + } + + if (key.name === 'return') return 'submit'; + if (key.name === 'enter') return 'submit'; // ctrl + J + + if (key.name === 'backspace') return 'delete'; + if (key.name === 'delete') return 'deleteForward'; + if (key.name === 'abort') return 'abort'; + if (key.name === 'escape') return 'exit'; + if (key.name === 'tab') return 'next'; + if (key.name === 'pagedown') return 'nextPage'; + if (key.name === 'pageup') return 'prevPage'; // TODO create home() in prompt types (e.g. TextPrompt) + + if (key.name === 'home') return 'home'; // TODO create end() in prompt types (e.g. TextPrompt) + + if (key.name === 'end') return 'end'; + if (key.name === 'up') return 'up'; + if (key.name === 'down') return 'down'; + if (key.name === 'right') return 'right'; + if (key.name === 'left') return 'left'; + return false; + }; + return action$1; +} + +var strip$1; +var hasRequiredStrip$1; + +function requireStrip$1 () { + if (hasRequiredStrip$1) return strip$1; + hasRequiredStrip$1 = 1; + + strip$1 = str => { + const pattern = ['[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)', '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PRZcf-ntqry=><~]))'].join('|'); + const RGX = new RegExp(pattern, 'g'); + return typeof str === 'string' ? str.replace(RGX, '') : str; + }; + return strip$1; +} + +var src$6; +var hasRequiredSrc; + +function requireSrc () { + if (hasRequiredSrc) return src$6; + hasRequiredSrc = 1; + + const ESC = '\x1B'; + const CSI = `${ESC}[`; + const beep = '\u0007'; + + const cursor = { + to(x, y) { + if (!y) return `${CSI}${x + 1}G`; + return `${CSI}${y + 1};${x + 1}H`; + }, + move(x, y) { + let ret = ''; + + if (x < 0) ret += `${CSI}${-x}D`; + else if (x > 0) ret += `${CSI}${x}C`; + + if (y < 0) ret += `${CSI}${-y}A`; + else if (y > 0) ret += `${CSI}${y}B`; + + return ret; + }, + up: (count = 1) => `${CSI}${count}A`, + down: (count = 1) => `${CSI}${count}B`, + forward: (count = 1) => `${CSI}${count}C`, + backward: (count = 1) => `${CSI}${count}D`, + nextLine: (count = 1) => `${CSI}E`.repeat(count), + prevLine: (count = 1) => `${CSI}F`.repeat(count), + left: `${CSI}G`, + hide: `${CSI}?25l`, + show: `${CSI}?25h`, + save: `${ESC}7`, + restore: `${ESC}8` + }; + + const scroll = { + up: (count = 1) => `${CSI}S`.repeat(count), + down: (count = 1) => `${CSI}T`.repeat(count) + }; + + const erase = { + screen: `${CSI}2J`, + up: (count = 1) => `${CSI}1J`.repeat(count), + down: (count = 1) => `${CSI}J`.repeat(count), + line: `${CSI}2K`, + lineEnd: `${CSI}K`, + lineStart: `${CSI}1K`, + lines(count) { + let clear = ''; + for (let i = 0; i < count; i++) + clear += this.line + (i < count - 1 ? cursor.up() : ''); + if (count) + clear += cursor.left; + return clear; + } + }; + + src$6 = { cursor, scroll, erase, beep }; + return src$6; +} + +var clear$1; +var hasRequiredClear$1; + +function requireClear$1 () { + if (hasRequiredClear$1) return clear$1; + hasRequiredClear$1 = 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; } + + const strip = requireStrip$1(); + + const _require = requireSrc(), + erase = _require.erase, + cursor = _require.cursor; + + const width = str => [...strip(str)].length; + /** + * @param {string} prompt + * @param {number} perLine + */ + + + clear$1 = function (prompt, perLine) { + if (!perLine) return erase.line + cursor.to(0); + let rows = 0; + const lines = prompt.split(/\r?\n/); + + var _iterator = _createForOfIteratorHelper(lines), + _step; + + try { + for (_iterator.s(); !(_step = _iterator.n()).done;) { + let line = _step.value; + rows += 1 + Math.floor(Math.max(width(line) - 1, 0) / perLine); + } + } catch (err) { + _iterator.e(err); + } finally { + _iterator.f(); + } + + return erase.lines(rows); + }; + return clear$1; +} + +var figures_1$1; +var hasRequiredFigures$1; + +function requireFigures$1 () { + if (hasRequiredFigures$1) return figures_1$1; + hasRequiredFigures$1 = 1; + + const main = { + arrowUp: '↑', + arrowDown: '↓', + arrowLeft: '←', + arrowRight: '→', + radioOn: '◉', + radioOff: '◯', + tick: '✔', + cross: '✖', + ellipsis: '…', + pointerSmall: '›', + line: '─', + pointer: '❯' + }; + const win = { + arrowUp: main.arrowUp, + arrowDown: main.arrowDown, + arrowLeft: main.arrowLeft, + arrowRight: main.arrowRight, + radioOn: '(*)', + radioOff: '( )', + tick: '√', + cross: '×', + ellipsis: '...', + pointerSmall: '»', + line: '─', + pointer: '>' + }; + const figures = process.platform === 'win32' ? win : main; + figures_1$1 = figures; + return figures_1$1; +} + +var style$1; +var hasRequiredStyle$1; + +function requireStyle$1 () { + if (hasRequiredStyle$1) return style$1; + hasRequiredStyle$1 = 1; + + const c = requireKleur(); + + const figures = requireFigures$1(); // rendering user input. + + + const styles = Object.freeze({ + password: { + scale: 1, + render: input => '*'.repeat(input.length) + }, + emoji: { + scale: 2, + render: input => '😃'.repeat(input.length) + }, + invisible: { + scale: 0, + render: input => '' + }, + default: { + scale: 1, + render: input => `${input}` + } + }); + + const render = type => styles[type] || styles.default; // icon to signalize a prompt. + + + const symbols = Object.freeze({ + aborted: c.red(figures.cross), + done: c.green(figures.tick), + exited: c.yellow(figures.cross), + default: c.cyan('?') + }); + + const symbol = (done, aborted, exited) => aborted ? symbols.aborted : exited ? symbols.exited : done ? symbols.done : symbols.default; // between the question and the user's input. + + + const delimiter = completing => c.gray(completing ? figures.ellipsis : figures.pointerSmall); + + const item = (expandable, expanded) => c.gray(expandable ? expanded ? figures.pointerSmall : '+' : figures.line); + + style$1 = { + styles, + render, + symbols, + symbol, + delimiter, + item + }; + return style$1; +} + +var lines$1; +var hasRequiredLines$1; + +function requireLines$1 () { + if (hasRequiredLines$1) return lines$1; + hasRequiredLines$1 = 1; + + const strip = requireStrip$1(); + /** + * @param {string} msg + * @param {number} perLine + */ + + + lines$1 = function (msg, perLine) { + let lines = String(strip(msg) || '').split(/\r?\n/); + if (!perLine) return lines.length; + return lines.map(l => Math.ceil(l.length / perLine)).reduce((a, b) => a + b); + }; + return lines$1; +} + +var wrap$1; +var hasRequiredWrap$1; + +function requireWrap$1 () { + if (hasRequiredWrap$1) return wrap$1; + hasRequiredWrap$1 = 1; + /** + * @param {string} msg The message to wrap + * @param {object} opts + * @param {number|string} [opts.margin] Left margin + * @param {number} opts.width Maximum characters per line including the margin + */ + + wrap$1 = (msg, opts = {}) => { + const tab = Number.isSafeInteger(parseInt(opts.margin)) ? new Array(parseInt(opts.margin)).fill(' ').join('') : opts.margin || ''; + const width = opts.width; + return (msg || '').split(/\r?\n/g).map(line => line.split(/\s+/g).reduce((arr, w) => { + if (w.length + tab.length >= width || arr[arr.length - 1].length + w.length + 1 < width) arr[arr.length - 1] += ` ${w}`;else arr.push(`${tab}${w}`); + return arr; + }, [tab]).join('\n')).join('\n'); + }; + return wrap$1; +} + +var entriesToDisplay$1; +var hasRequiredEntriesToDisplay$1; + +function requireEntriesToDisplay$1 () { + if (hasRequiredEntriesToDisplay$1) return entriesToDisplay$1; + hasRequiredEntriesToDisplay$1 = 1; + /** + * Determine what entries should be displayed on the screen, based on the + * currently selected index and the maximum visible. Used in list-based + * prompts like `select` and `multiselect`. + * + * @param {number} cursor the currently selected entry + * @param {number} total the total entries available to display + * @param {number} [maxVisible] the number of entries that can be displayed + */ + + entriesToDisplay$1 = (cursor, total, maxVisible) => { + maxVisible = maxVisible || total; + let startIndex = Math.min(total - maxVisible, cursor - Math.floor(maxVisible / 2)); + if (startIndex < 0) startIndex = 0; + let endIndex = Math.min(startIndex + maxVisible, total); + return { + startIndex, + endIndex + }; + }; + return entriesToDisplay$1; +} + +var util$b; +var hasRequiredUtil$2; + +function requireUtil$2 () { + if (hasRequiredUtil$2) return util$b; + hasRequiredUtil$2 = 1; + + util$b = { + action: requireAction$1(), + clear: requireClear$1(), + style: requireStyle$1(), + strip: requireStrip$1(), + figures: requireFigures$1(), + lines: requireLines$1(), + wrap: requireWrap$1(), + entriesToDisplay: requireEntriesToDisplay$1() + }; + return util$b; +} + +var prompt$1; +var hasRequiredPrompt$1; + +function requirePrompt$1 () { + if (hasRequiredPrompt$1) return prompt$1; + hasRequiredPrompt$1 = 1; + + const readline = require$$0$g; + + const _require = requireUtil$2(), + action = _require.action; + + const EventEmitter = require$$2$3; + + const _require2 = requireSrc(), + beep = _require2.beep, + cursor = _require2.cursor; + + const color = requireKleur(); + /** + * Base prompt skeleton + * @param {Stream} [opts.stdin] The Readable stream to listen to + * @param {Stream} [opts.stdout] The Writable stream to write readline data to + */ + + + class Prompt extends EventEmitter { + constructor(opts = {}) { + super(); + this.firstRender = true; + this.in = opts.stdin || process.stdin; + this.out = opts.stdout || process.stdout; + + this.onRender = (opts.onRender || (() => void 0)).bind(this); + + const rl = readline.createInterface({ + input: this.in, + escapeCodeTimeout: 50 + }); + readline.emitKeypressEvents(this.in, rl); + if (this.in.isTTY) this.in.setRawMode(true); + const isSelect = ['SelectPrompt', 'MultiselectPrompt'].indexOf(this.constructor.name) > -1; + + const keypress = (str, key) => { + let a = action(key, isSelect); + + if (a === false) { + this._ && this._(str, key); + } else if (typeof this[a] === 'function') { + this[a](key); + } else { + this.bell(); + } + }; + + this.close = () => { + this.out.write(cursor.show); + this.in.removeListener('keypress', keypress); + if (this.in.isTTY) this.in.setRawMode(false); + rl.close(); + this.emit(this.aborted ? 'abort' : this.exited ? 'exit' : 'submit', this.value); + this.closed = true; + }; + + this.in.on('keypress', keypress); + } + + fire() { + this.emit('state', { + value: this.value, + aborted: !!this.aborted, + exited: !!this.exited + }); + } + + bell() { + this.out.write(beep); + } + + render() { + this.onRender(color); + if (this.firstRender) this.firstRender = false; + } + + } + + prompt$1 = Prompt; + return prompt$1; +} + +var text$2; +var hasRequiredText$1; + +function requireText$1 () { + if (hasRequiredText$1) return text$2; + hasRequiredText$1 = 1; + + function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } + + function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } + + const color = requireKleur(); + + const Prompt = requirePrompt$1(); + + const _require = requireSrc(), + erase = _require.erase, + cursor = _require.cursor; + + const _require2 = requireUtil$2(), + style = _require2.style, + clear = _require2.clear, + lines = _require2.lines, + figures = _require2.figures; + /** + * TextPrompt Base Element + * @param {Object} opts Options + * @param {String} opts.message Message + * @param {String} [opts.style='default'] Render style + * @param {String} [opts.initial] Default value + * @param {Function} [opts.validate] Validate function + * @param {Stream} [opts.stdin] The Readable stream to listen to + * @param {Stream} [opts.stdout] The Writable stream to write readline data to + * @param {String} [opts.error] The invalid error label + */ + + + class TextPrompt extends Prompt { + constructor(opts = {}) { + super(opts); + this.transform = style.render(opts.style); + this.scale = this.transform.scale; + this.msg = opts.message; + this.initial = opts.initial || ``; + + this.validator = opts.validate || (() => true); + + this.value = ``; + this.errorMsg = opts.error || `Please Enter A Valid Value`; + this.cursor = Number(!!this.initial); + this.cursorOffset = 0; + this.clear = clear(``, this.out.columns); + this.render(); + } + + set value(v) { + if (!v && this.initial) { + this.placeholder = true; + this.rendered = color.gray(this.transform.render(this.initial)); + } else { + this.placeholder = false; + this.rendered = this.transform.render(v); + } + + this._value = v; + this.fire(); + } + + get value() { + return this._value; + } + + reset() { + this.value = ``; + this.cursor = Number(!!this.initial); + this.cursorOffset = 0; + this.fire(); + this.render(); + } + + exit() { + this.abort(); + } + + abort() { + this.value = this.value || this.initial; + this.done = this.aborted = true; + this.error = false; + this.red = false; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + + validate() { + var _this = this; + + return _asyncToGenerator(function* () { + let valid = yield _this.validator(_this.value); + + if (typeof valid === `string`) { + _this.errorMsg = valid; + valid = false; + } + + _this.error = !valid; + })(); + } + + submit() { + var _this2 = this; + + return _asyncToGenerator(function* () { + _this2.value = _this2.value || _this2.initial; + _this2.cursorOffset = 0; + _this2.cursor = _this2.rendered.length; + yield _this2.validate(); + + if (_this2.error) { + _this2.red = true; + + _this2.fire(); + + _this2.render(); + + return; + } + + _this2.done = true; + _this2.aborted = false; + + _this2.fire(); + + _this2.render(); + + _this2.out.write('\n'); + + _this2.close(); + })(); + } + + next() { + if (!this.placeholder) return this.bell(); + this.value = this.initial; + this.cursor = this.rendered.length; + this.fire(); + this.render(); + } + + moveCursor(n) { + if (this.placeholder) return; + this.cursor = this.cursor + n; + this.cursorOffset += n; + } + + _(c, key) { + let s1 = this.value.slice(0, this.cursor); + let s2 = this.value.slice(this.cursor); + this.value = `${s1}${c}${s2}`; + this.red = false; + this.cursor = this.placeholder ? 0 : s1.length + 1; + this.render(); + } + + delete() { + if (this.isCursorAtStart()) return this.bell(); + let s1 = this.value.slice(0, this.cursor - 1); + let s2 = this.value.slice(this.cursor); + this.value = `${s1}${s2}`; + this.red = false; + + if (this.isCursorAtStart()) { + this.cursorOffset = 0; + } else { + this.cursorOffset++; + this.moveCursor(-1); + } + + this.render(); + } + + deleteForward() { + if (this.cursor * this.scale >= this.rendered.length || this.placeholder) return this.bell(); + let s1 = this.value.slice(0, this.cursor); + let s2 = this.value.slice(this.cursor + 1); + this.value = `${s1}${s2}`; + this.red = false; + + if (this.isCursorAtEnd()) { + this.cursorOffset = 0; + } else { + this.cursorOffset++; + } + + this.render(); + } + + first() { + this.cursor = 0; + this.render(); + } + + last() { + this.cursor = this.value.length; + this.render(); + } + + left() { + if (this.cursor <= 0 || this.placeholder) return this.bell(); + this.moveCursor(-1); + this.render(); + } + + right() { + if (this.cursor * this.scale >= this.rendered.length || this.placeholder) return this.bell(); + this.moveCursor(1); + this.render(); + } + + isCursorAtStart() { + return this.cursor === 0 || this.placeholder && this.cursor === 1; + } + + isCursorAtEnd() { + return this.cursor === this.rendered.length || this.placeholder && this.cursor === this.rendered.length + 1; + } + + render() { + if (this.closed) return; + + if (!this.firstRender) { + if (this.outputError) this.out.write(cursor.down(lines(this.outputError, this.out.columns) - 1) + clear(this.outputError, this.out.columns)); + this.out.write(clear(this.outputText, this.out.columns)); + } + + super.render(); + this.outputError = ''; + this.outputText = [style.symbol(this.done, this.aborted), color.bold(this.msg), style.delimiter(this.done), this.red ? color.red(this.rendered) : this.rendered].join(` `); + + if (this.error) { + this.outputError += this.errorMsg.split(`\n`).reduce((a, l, i) => a + `\n${i ? ' ' : figures.pointerSmall} ${color.red().italic(l)}`, ``); + } + + this.out.write(erase.line + cursor.to(0) + this.outputText + cursor.save + this.outputError + cursor.restore + cursor.move(this.cursorOffset, 0)); + } + + } + + text$2 = TextPrompt; + return text$2; +} + +var select$1; +var hasRequiredSelect$1; + +function requireSelect$1 () { + if (hasRequiredSelect$1) return select$1; + hasRequiredSelect$1 = 1; + + const color = requireKleur(); + + const Prompt = requirePrompt$1(); + + const _require = requireUtil$2(), + style = _require.style, + clear = _require.clear, + figures = _require.figures, + wrap = _require.wrap, + entriesToDisplay = _require.entriesToDisplay; + + const _require2 = requireSrc(), + cursor = _require2.cursor; + /** + * SelectPrompt Base Element + * @param {Object} opts Options + * @param {String} opts.message Message + * @param {Array} opts.choices Array of choice objects + * @param {String} [opts.hint] Hint to display + * @param {Number} [opts.initial] Index of default value + * @param {Stream} [opts.stdin] The Readable stream to listen to + * @param {Stream} [opts.stdout] The Writable stream to write readline data to + * @param {Number} [opts.optionsPerPage=10] Max options to display at once + */ + + + class SelectPrompt extends Prompt { + constructor(opts = {}) { + super(opts); + this.msg = opts.message; + this.hint = opts.hint || '- Use arrow-keys. Return to submit.'; + this.warn = opts.warn || '- This option is disabled'; + this.cursor = opts.initial || 0; + this.choices = opts.choices.map((ch, idx) => { + if (typeof ch === 'string') ch = { + title: ch, + value: idx + }; + return { + title: ch && (ch.title || ch.value || ch), + value: ch && (ch.value === undefined ? idx : ch.value), + description: ch && ch.description, + selected: ch && ch.selected, + disabled: ch && ch.disabled + }; + }); + this.optionsPerPage = opts.optionsPerPage || 10; + this.value = (this.choices[this.cursor] || {}).value; + this.clear = clear('', this.out.columns); + this.render(); + } + + moveCursor(n) { + this.cursor = n; + this.value = this.choices[n].value; + this.fire(); + } + + reset() { + this.moveCursor(0); + this.fire(); + this.render(); + } + + exit() { + this.abort(); + } + + abort() { + this.done = this.aborted = true; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + + submit() { + if (!this.selection.disabled) { + this.done = true; + this.aborted = false; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } else this.bell(); + } + + first() { + this.moveCursor(0); + this.render(); + } + + last() { + this.moveCursor(this.choices.length - 1); + this.render(); + } + + up() { + if (this.cursor === 0) { + this.moveCursor(this.choices.length - 1); + } else { + this.moveCursor(this.cursor - 1); + } + + this.render(); + } + + down() { + if (this.cursor === this.choices.length - 1) { + this.moveCursor(0); + } else { + this.moveCursor(this.cursor + 1); + } + + this.render(); + } + + next() { + this.moveCursor((this.cursor + 1) % this.choices.length); + this.render(); + } + + _(c, key) { + if (c === ' ') return this.submit(); + } + + get selection() { + return this.choices[this.cursor]; + } + + render() { + if (this.closed) return; + if (this.firstRender) this.out.write(cursor.hide);else this.out.write(clear(this.outputText, this.out.columns)); + super.render(); + + let _entriesToDisplay = entriesToDisplay(this.cursor, this.choices.length, this.optionsPerPage), + startIndex = _entriesToDisplay.startIndex, + endIndex = _entriesToDisplay.endIndex; // Print prompt + + + this.outputText = [style.symbol(this.done, this.aborted), color.bold(this.msg), style.delimiter(false), this.done ? this.selection.title : this.selection.disabled ? color.yellow(this.warn) : color.gray(this.hint)].join(' '); // Print choices + + if (!this.done) { + this.outputText += '\n'; + + for (let i = startIndex; i < endIndex; i++) { + let title, + prefix, + desc = '', + v = this.choices[i]; // Determine whether to display "more choices" indicators + + if (i === startIndex && startIndex > 0) { + prefix = figures.arrowUp; + } else if (i === endIndex - 1 && endIndex < this.choices.length) { + prefix = figures.arrowDown; + } else { + prefix = ' '; + } + + if (v.disabled) { + title = this.cursor === i ? color.gray().underline(v.title) : color.strikethrough().gray(v.title); + prefix = (this.cursor === i ? color.bold().gray(figures.pointer) + ' ' : ' ') + prefix; + } else { + title = this.cursor === i ? color.cyan().underline(v.title) : v.title; + prefix = (this.cursor === i ? color.cyan(figures.pointer) + ' ' : ' ') + prefix; + + if (v.description && this.cursor === i) { + desc = ` - ${v.description}`; + + if (prefix.length + title.length + desc.length >= this.out.columns || v.description.split(/\r?\n/).length > 1) { + desc = '\n' + wrap(v.description, { + margin: 3, + width: this.out.columns + }); + } + } + } + + this.outputText += `${prefix} ${title}${color.gray(desc)}\n`; + } + } + + this.out.write(this.outputText); + } + + } + + select$1 = SelectPrompt; + return select$1; +} + +var toggle$2; +var hasRequiredToggle$1; + +function requireToggle$1 () { + if (hasRequiredToggle$1) return toggle$2; + hasRequiredToggle$1 = 1; + + const color = requireKleur(); + + const Prompt = requirePrompt$1(); + + const _require = requireUtil$2(), + style = _require.style, + clear = _require.clear; + + const _require2 = requireSrc(), + cursor = _require2.cursor, + erase = _require2.erase; + /** + * TogglePrompt Base Element + * @param {Object} opts Options + * @param {String} opts.message Message + * @param {Boolean} [opts.initial=false] Default value + * @param {String} [opts.active='no'] Active label + * @param {String} [opts.inactive='off'] Inactive label + * @param {Stream} [opts.stdin] The Readable stream to listen to + * @param {Stream} [opts.stdout] The Writable stream to write readline data to + */ + + + class TogglePrompt extends Prompt { + constructor(opts = {}) { + super(opts); + this.msg = opts.message; + this.value = !!opts.initial; + this.active = opts.active || 'on'; + this.inactive = opts.inactive || 'off'; + this.initialValue = this.value; + this.render(); + } + + reset() { + this.value = this.initialValue; + this.fire(); + this.render(); + } + + exit() { + this.abort(); + } + + abort() { + this.done = this.aborted = true; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + + submit() { + this.done = true; + this.aborted = false; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + + deactivate() { + if (this.value === false) return this.bell(); + this.value = false; + this.render(); + } + + activate() { + if (this.value === true) return this.bell(); + this.value = true; + this.render(); + } + + delete() { + this.deactivate(); + } + + left() { + this.deactivate(); + } + + right() { + this.activate(); + } + + down() { + this.deactivate(); + } + + up() { + this.activate(); + } + + next() { + this.value = !this.value; + this.fire(); + this.render(); + } + + _(c, key) { + if (c === ' ') { + this.value = !this.value; + } else if (c === '1') { + this.value = true; + } else if (c === '0') { + this.value = false; + } else return this.bell(); + + this.render(); + } + + render() { + if (this.closed) return; + if (this.firstRender) this.out.write(cursor.hide);else this.out.write(clear(this.outputText, this.out.columns)); + super.render(); + this.outputText = [style.symbol(this.done, this.aborted), color.bold(this.msg), style.delimiter(this.done), this.value ? this.inactive : color.cyan().underline(this.inactive), color.gray('/'), this.value ? color.cyan().underline(this.active) : this.active].join(' '); + this.out.write(erase.line + cursor.to(0) + this.outputText); + } + + } + + toggle$2 = TogglePrompt; + return toggle$2; +} + +var datepart$1; +var hasRequiredDatepart$1; + +function requireDatepart$1 () { + if (hasRequiredDatepart$1) return datepart$1; + hasRequiredDatepart$1 = 1; + + class DatePart { + constructor({ + token, + date, + parts, + locales + }) { + this.token = token; + this.date = date || new Date(); + this.parts = parts || [this]; + this.locales = locales || {}; + } + + up() {} + + down() {} + + next() { + const currentIdx = this.parts.indexOf(this); + return this.parts.find((part, idx) => idx > currentIdx && part instanceof DatePart); + } + + setTo(val) {} + + prev() { + let parts = [].concat(this.parts).reverse(); + const currentIdx = parts.indexOf(this); + return parts.find((part, idx) => idx > currentIdx && part instanceof DatePart); + } + + toString() { + return String(this.date); + } + + } + + datepart$1 = DatePart; + return datepart$1; +} + +var meridiem$1; +var hasRequiredMeridiem$1; + +function requireMeridiem$1 () { + if (hasRequiredMeridiem$1) return meridiem$1; + hasRequiredMeridiem$1 = 1; + + const DatePart = requireDatepart$1(); + + class Meridiem extends DatePart { + constructor(opts = {}) { + super(opts); + } + + up() { + this.date.setHours((this.date.getHours() + 12) % 24); + } + + down() { + this.up(); + } + + toString() { + let meridiem = this.date.getHours() > 12 ? 'pm' : 'am'; + return /\A/.test(this.token) ? meridiem.toUpperCase() : meridiem; + } + + } + + meridiem$1 = Meridiem; + return meridiem$1; +} + +var day$1; +var hasRequiredDay$1; + +function requireDay$1 () { + if (hasRequiredDay$1) return day$1; + hasRequiredDay$1 = 1; + + const DatePart = requireDatepart$1(); + + const pos = n => { + n = n % 10; + return n === 1 ? 'st' : n === 2 ? 'nd' : n === 3 ? 'rd' : 'th'; + }; + + class Day extends DatePart { + constructor(opts = {}) { + super(opts); + } + + up() { + this.date.setDate(this.date.getDate() + 1); + } + + down() { + this.date.setDate(this.date.getDate() - 1); + } + + setTo(val) { + this.date.setDate(parseInt(val.substr(-2))); + } + + toString() { + let date = this.date.getDate(); + let day = this.date.getDay(); + return this.token === 'DD' ? String(date).padStart(2, '0') : this.token === 'Do' ? date + pos(date) : this.token === 'd' ? day + 1 : this.token === 'ddd' ? this.locales.weekdaysShort[day] : this.token === 'dddd' ? this.locales.weekdays[day] : date; + } + + } + + day$1 = Day; + return day$1; +} + +var hours$1; +var hasRequiredHours$1; + +function requireHours$1 () { + if (hasRequiredHours$1) return hours$1; + hasRequiredHours$1 = 1; + + const DatePart = requireDatepart$1(); + + class Hours extends DatePart { + constructor(opts = {}) { + super(opts); + } + + up() { + this.date.setHours(this.date.getHours() + 1); + } + + down() { + this.date.setHours(this.date.getHours() - 1); + } + + setTo(val) { + this.date.setHours(parseInt(val.substr(-2))); + } + + toString() { + let hours = this.date.getHours(); + if (/h/.test(this.token)) hours = hours % 12 || 12; + return this.token.length > 1 ? String(hours).padStart(2, '0') : hours; + } + + } + + hours$1 = Hours; + return hours$1; +} + +var milliseconds$1; +var hasRequiredMilliseconds$1; + +function requireMilliseconds$1 () { + if (hasRequiredMilliseconds$1) return milliseconds$1; + hasRequiredMilliseconds$1 = 1; + + const DatePart = requireDatepart$1(); + + class Milliseconds extends DatePart { + constructor(opts = {}) { + super(opts); + } + + up() { + this.date.setMilliseconds(this.date.getMilliseconds() + 1); + } + + down() { + this.date.setMilliseconds(this.date.getMilliseconds() - 1); + } + + setTo(val) { + this.date.setMilliseconds(parseInt(val.substr(-this.token.length))); + } + + toString() { + return String(this.date.getMilliseconds()).padStart(4, '0').substr(0, this.token.length); + } + + } + + milliseconds$1 = Milliseconds; + return milliseconds$1; +} + +var minutes$1; +var hasRequiredMinutes$1; + +function requireMinutes$1 () { + if (hasRequiredMinutes$1) return minutes$1; + hasRequiredMinutes$1 = 1; + + const DatePart = requireDatepart$1(); + + class Minutes extends DatePart { + constructor(opts = {}) { + super(opts); + } + + up() { + this.date.setMinutes(this.date.getMinutes() + 1); + } + + down() { + this.date.setMinutes(this.date.getMinutes() - 1); + } + + setTo(val) { + this.date.setMinutes(parseInt(val.substr(-2))); + } + + toString() { + let m = this.date.getMinutes(); + return this.token.length > 1 ? String(m).padStart(2, '0') : m; + } + + } + + minutes$1 = Minutes; + return minutes$1; +} + +var month$1; +var hasRequiredMonth$1; + +function requireMonth$1 () { + if (hasRequiredMonth$1) return month$1; + hasRequiredMonth$1 = 1; + + const DatePart = requireDatepart$1(); + + class Month extends DatePart { + constructor(opts = {}) { + super(opts); + } + + up() { + this.date.setMonth(this.date.getMonth() + 1); + } + + down() { + this.date.setMonth(this.date.getMonth() - 1); + } + + setTo(val) { + val = parseInt(val.substr(-2)) - 1; + this.date.setMonth(val < 0 ? 0 : val); + } + + toString() { + let month = this.date.getMonth(); + let tl = this.token.length; + return tl === 2 ? String(month + 1).padStart(2, '0') : tl === 3 ? this.locales.monthsShort[month] : tl === 4 ? this.locales.months[month] : String(month + 1); + } + + } + + month$1 = Month; + return month$1; +} + +var seconds$1; +var hasRequiredSeconds$1; + +function requireSeconds$1 () { + if (hasRequiredSeconds$1) return seconds$1; + hasRequiredSeconds$1 = 1; + + const DatePart = requireDatepart$1(); + + class Seconds extends DatePart { + constructor(opts = {}) { + super(opts); + } + + up() { + this.date.setSeconds(this.date.getSeconds() + 1); + } + + down() { + this.date.setSeconds(this.date.getSeconds() - 1); + } + + setTo(val) { + this.date.setSeconds(parseInt(val.substr(-2))); + } + + toString() { + let s = this.date.getSeconds(); + return this.token.length > 1 ? String(s).padStart(2, '0') : s; + } + + } + + seconds$1 = Seconds; + return seconds$1; +} + +var year$1; +var hasRequiredYear$1; + +function requireYear$1 () { + if (hasRequiredYear$1) return year$1; + hasRequiredYear$1 = 1; + + const DatePart = requireDatepart$1(); + + class Year extends DatePart { + constructor(opts = {}) { + super(opts); + } + + up() { + this.date.setFullYear(this.date.getFullYear() + 1); + } + + down() { + this.date.setFullYear(this.date.getFullYear() - 1); + } + + setTo(val) { + this.date.setFullYear(val.substr(-4)); + } + + toString() { + let year = String(this.date.getFullYear()).padStart(4, '0'); + return this.token.length === 2 ? year.substr(-2) : year; + } + + } + + year$1 = Year; + return year$1; +} + +var dateparts$1; +var hasRequiredDateparts$1; + +function requireDateparts$1 () { + if (hasRequiredDateparts$1) return dateparts$1; + hasRequiredDateparts$1 = 1; + + dateparts$1 = { + DatePart: requireDatepart$1(), + Meridiem: requireMeridiem$1(), + Day: requireDay$1(), + Hours: requireHours$1(), + Milliseconds: requireMilliseconds$1(), + Minutes: requireMinutes$1(), + Month: requireMonth$1(), + Seconds: requireSeconds$1(), + Year: requireYear$1() + }; + return dateparts$1; +} + +var date$1; +var hasRequiredDate$1; + +function requireDate$1 () { + if (hasRequiredDate$1) return date$1; + hasRequiredDate$1 = 1; + + function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } + + function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } + + const color = requireKleur(); + + const Prompt = requirePrompt$1(); + + const _require = requireUtil$2(), + style = _require.style, + clear = _require.clear, + figures = _require.figures; + + const _require2 = requireSrc(), + erase = _require2.erase, + cursor = _require2.cursor; + + const _require3 = requireDateparts$1(), + DatePart = _require3.DatePart, + Meridiem = _require3.Meridiem, + Day = _require3.Day, + Hours = _require3.Hours, + Milliseconds = _require3.Milliseconds, + Minutes = _require3.Minutes, + Month = _require3.Month, + Seconds = _require3.Seconds, + Year = _require3.Year; + + const regex = /\\(.)|"((?:\\["\\]|[^"])+)"|(D[Do]?|d{3,4}|d)|(M{1,4})|(YY(?:YY)?)|([aA])|([Hh]{1,2})|(m{1,2})|(s{1,2})|(S{1,4})|./g; + const regexGroups = { + 1: ({ + token + }) => token.replace(/\\(.)/g, '$1'), + 2: opts => new Day(opts), + // Day // TODO + 3: opts => new Month(opts), + // Month + 4: opts => new Year(opts), + // Year + 5: opts => new Meridiem(opts), + // AM/PM // TODO (special) + 6: opts => new Hours(opts), + // Hours + 7: opts => new Minutes(opts), + // Minutes + 8: opts => new Seconds(opts), + // Seconds + 9: opts => new Milliseconds(opts) // Fractional seconds + + }; + const dfltLocales = { + months: 'January,February,March,April,May,June,July,August,September,October,November,December'.split(','), + monthsShort: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','), + weekdays: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','), + weekdaysShort: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(',') + }; + /** + * DatePrompt Base Element + * @param {Object} opts Options + * @param {String} opts.message Message + * @param {Number} [opts.initial] Index of default value + * @param {String} [opts.mask] The format mask + * @param {object} [opts.locales] The date locales + * @param {String} [opts.error] The error message shown on invalid value + * @param {Function} [opts.validate] Function to validate the submitted value + * @param {Stream} [opts.stdin] The Readable stream to listen to + * @param {Stream} [opts.stdout] The Writable stream to write readline data to + */ + + class DatePrompt extends Prompt { + constructor(opts = {}) { + super(opts); + this.msg = opts.message; + this.cursor = 0; + this.typed = ''; + this.locales = Object.assign(dfltLocales, opts.locales); + this._date = opts.initial || new Date(); + this.errorMsg = opts.error || 'Please Enter A Valid Value'; + + this.validator = opts.validate || (() => true); + + this.mask = opts.mask || 'YYYY-MM-DD HH:mm:ss'; + this.clear = clear('', this.out.columns); + this.render(); + } + + get value() { + return this.date; + } + + get date() { + return this._date; + } + + set date(date) { + if (date) this._date.setTime(date.getTime()); + } + + set mask(mask) { + let result; + this.parts = []; + + while (result = regex.exec(mask)) { + let match = result.shift(); + let idx = result.findIndex(gr => gr != null); + this.parts.push(idx in regexGroups ? regexGroups[idx]({ + token: result[idx] || match, + date: this.date, + parts: this.parts, + locales: this.locales + }) : result[idx] || match); + } + + let parts = this.parts.reduce((arr, i) => { + if (typeof i === 'string' && typeof arr[arr.length - 1] === 'string') arr[arr.length - 1] += i;else arr.push(i); + return arr; + }, []); + this.parts.splice(0); + this.parts.push(...parts); + this.reset(); + } + + moveCursor(n) { + this.typed = ''; + this.cursor = n; + this.fire(); + } + + reset() { + this.moveCursor(this.parts.findIndex(p => p instanceof DatePart)); + this.fire(); + this.render(); + } + + exit() { + this.abort(); + } + + abort() { + this.done = this.aborted = true; + this.error = false; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + + validate() { + var _this = this; + + return _asyncToGenerator(function* () { + let valid = yield _this.validator(_this.value); + + if (typeof valid === 'string') { + _this.errorMsg = valid; + valid = false; + } + + _this.error = !valid; + })(); + } + + submit() { + var _this2 = this; + + return _asyncToGenerator(function* () { + yield _this2.validate(); + + if (_this2.error) { + _this2.color = 'red'; + + _this2.fire(); + + _this2.render(); + + return; + } + + _this2.done = true; + _this2.aborted = false; + + _this2.fire(); + + _this2.render(); + + _this2.out.write('\n'); + + _this2.close(); + })(); + } + + up() { + this.typed = ''; + this.parts[this.cursor].up(); + this.render(); + } + + down() { + this.typed = ''; + this.parts[this.cursor].down(); + this.render(); + } + + left() { + let prev = this.parts[this.cursor].prev(); + if (prev == null) return this.bell(); + this.moveCursor(this.parts.indexOf(prev)); + this.render(); + } + + right() { + let next = this.parts[this.cursor].next(); + if (next == null) return this.bell(); + this.moveCursor(this.parts.indexOf(next)); + this.render(); + } + + next() { + let next = this.parts[this.cursor].next(); + this.moveCursor(next ? this.parts.indexOf(next) : this.parts.findIndex(part => part instanceof DatePart)); + this.render(); + } + + _(c) { + if (/\d/.test(c)) { + this.typed += c; + this.parts[this.cursor].setTo(this.typed); + this.render(); + } + } + + render() { + if (this.closed) return; + if (this.firstRender) this.out.write(cursor.hide);else this.out.write(clear(this.outputText, this.out.columns)); + super.render(); // Print prompt + + this.outputText = [style.symbol(this.done, this.aborted), color.bold(this.msg), style.delimiter(false), this.parts.reduce((arr, p, idx) => arr.concat(idx === this.cursor && !this.done ? color.cyan().underline(p.toString()) : p), []).join('')].join(' '); // Print error + + if (this.error) { + this.outputText += this.errorMsg.split('\n').reduce((a, l, i) => a + `\n${i ? ` ` : figures.pointerSmall} ${color.red().italic(l)}`, ``); + } + + this.out.write(erase.line + cursor.to(0) + this.outputText); + } + + } + + date$1 = DatePrompt; + return date$1; +} + +var number$1; +var hasRequiredNumber$1; + +function requireNumber$1 () { + if (hasRequiredNumber$1) return number$1; + hasRequiredNumber$1 = 1; + + function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } + + function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } + + const color = requireKleur(); + + const Prompt = requirePrompt$1(); + + const _require = requireSrc(), + cursor = _require.cursor, + erase = _require.erase; + + const _require2 = requireUtil$2(), + style = _require2.style, + figures = _require2.figures, + clear = _require2.clear, + lines = _require2.lines; + + const isNumber = /[0-9]/; + + const isDef = any => any !== undefined; + + const round = (number, precision) => { + let factor = Math.pow(10, precision); + return Math.round(number * factor) / factor; + }; + /** + * NumberPrompt Base Element + * @param {Object} opts Options + * @param {String} opts.message Message + * @param {String} [opts.style='default'] Render style + * @param {Number} [opts.initial] Default value + * @param {Number} [opts.max=+Infinity] Max value + * @param {Number} [opts.min=-Infinity] Min value + * @param {Boolean} [opts.float=false] Parse input as floats + * @param {Number} [opts.round=2] Round floats to x decimals + * @param {Number} [opts.increment=1] Number to increment by when using arrow-keys + * @param {Function} [opts.validate] Validate function + * @param {Stream} [opts.stdin] The Readable stream to listen to + * @param {Stream} [opts.stdout] The Writable stream to write readline data to + * @param {String} [opts.error] The invalid error label + */ + + + class NumberPrompt extends Prompt { + constructor(opts = {}) { + super(opts); + this.transform = style.render(opts.style); + this.msg = opts.message; + this.initial = isDef(opts.initial) ? opts.initial : ''; + this.float = !!opts.float; + this.round = opts.round || 2; + this.inc = opts.increment || 1; + this.min = isDef(opts.min) ? opts.min : -Infinity; + this.max = isDef(opts.max) ? opts.max : Infinity; + this.errorMsg = opts.error || `Please Enter A Valid Value`; + + this.validator = opts.validate || (() => true); + + this.color = `cyan`; + this.value = ``; + this.typed = ``; + this.lastHit = 0; + this.render(); + } + + set value(v) { + if (!v && v !== 0) { + this.placeholder = true; + this.rendered = color.gray(this.transform.render(`${this.initial}`)); + this._value = ``; + } else { + this.placeholder = false; + this.rendered = this.transform.render(`${round(v, this.round)}`); + this._value = round(v, this.round); + } + + this.fire(); + } + + get value() { + return this._value; + } + + parse(x) { + return this.float ? parseFloat(x) : parseInt(x); + } + + valid(c) { + return c === `-` || c === `.` && this.float || isNumber.test(c); + } + + reset() { + this.typed = ``; + this.value = ``; + this.fire(); + this.render(); + } + + exit() { + this.abort(); + } + + abort() { + let x = this.value; + this.value = x !== `` ? x : this.initial; + this.done = this.aborted = true; + this.error = false; + this.fire(); + this.render(); + this.out.write(`\n`); + this.close(); + } + + validate() { + var _this = this; + + return _asyncToGenerator(function* () { + let valid = yield _this.validator(_this.value); + + if (typeof valid === `string`) { + _this.errorMsg = valid; + valid = false; + } + + _this.error = !valid; + })(); + } + + submit() { + var _this2 = this; + + return _asyncToGenerator(function* () { + yield _this2.validate(); + + if (_this2.error) { + _this2.color = `red`; + + _this2.fire(); + + _this2.render(); + + return; + } + + let x = _this2.value; + _this2.value = x !== `` ? x : _this2.initial; + _this2.done = true; + _this2.aborted = false; + _this2.error = false; + + _this2.fire(); + + _this2.render(); + + _this2.out.write(`\n`); + + _this2.close(); + })(); + } + + up() { + this.typed = ``; + + if (this.value === '') { + this.value = this.min - this.inc; + } + + if (this.value >= this.max) return this.bell(); + this.value += this.inc; + this.color = `cyan`; + this.fire(); + this.render(); + } + + down() { + this.typed = ``; + + if (this.value === '') { + this.value = this.min + this.inc; + } + + if (this.value <= this.min) return this.bell(); + this.value -= this.inc; + this.color = `cyan`; + this.fire(); + this.render(); + } + + delete() { + let val = this.value.toString(); + if (val.length === 0) return this.bell(); + this.value = this.parse(val = val.slice(0, -1)) || ``; + + if (this.value !== '' && this.value < this.min) { + this.value = this.min; + } + + this.color = `cyan`; + this.fire(); + this.render(); + } + + next() { + this.value = this.initial; + this.fire(); + this.render(); + } + + _(c, key) { + if (!this.valid(c)) return this.bell(); + const now = Date.now(); + if (now - this.lastHit > 1000) this.typed = ``; // 1s elapsed + + this.typed += c; + this.lastHit = now; + this.color = `cyan`; + if (c === `.`) return this.fire(); + this.value = Math.min(this.parse(this.typed), this.max); + if (this.value > this.max) this.value = this.max; + if (this.value < this.min) this.value = this.min; + this.fire(); + this.render(); + } + + render() { + if (this.closed) return; + + if (!this.firstRender) { + if (this.outputError) this.out.write(cursor.down(lines(this.outputError, this.out.columns) - 1) + clear(this.outputError, this.out.columns)); + this.out.write(clear(this.outputText, this.out.columns)); + } + + super.render(); + this.outputError = ''; // Print prompt + + this.outputText = [style.symbol(this.done, this.aborted), color.bold(this.msg), style.delimiter(this.done), !this.done || !this.done && !this.placeholder ? color[this.color]().underline(this.rendered) : this.rendered].join(` `); // Print error + + if (this.error) { + this.outputError += this.errorMsg.split(`\n`).reduce((a, l, i) => a + `\n${i ? ` ` : figures.pointerSmall} ${color.red().italic(l)}`, ``); + } + + this.out.write(erase.line + cursor.to(0) + this.outputText + cursor.save + this.outputError + cursor.restore); + } + + } + + number$1 = NumberPrompt; + return number$1; +} + +var multiselect$1; +var hasRequiredMultiselect$1; + +function requireMultiselect$1 () { + if (hasRequiredMultiselect$1) return multiselect$1; + hasRequiredMultiselect$1 = 1; + + const color = requireKleur(); + + const _require = requireSrc(), + cursor = _require.cursor; + + const Prompt = requirePrompt$1(); + + const _require2 = requireUtil$2(), + clear = _require2.clear, + figures = _require2.figures, + style = _require2.style, + wrap = _require2.wrap, + entriesToDisplay = _require2.entriesToDisplay; + /** + * MultiselectPrompt Base Element + * @param {Object} opts Options + * @param {String} opts.message Message + * @param {Array} opts.choices Array of choice objects + * @param {String} [opts.hint] Hint to display + * @param {String} [opts.warn] Hint shown for disabled choices + * @param {Number} [opts.max] Max choices + * @param {Number} [opts.cursor=0] Cursor start position + * @param {Number} [opts.optionsPerPage=10] Max options to display at once + * @param {Stream} [opts.stdin] The Readable stream to listen to + * @param {Stream} [opts.stdout] The Writable stream to write readline data to + */ + + + class MultiselectPrompt extends Prompt { + constructor(opts = {}) { + super(opts); + this.msg = opts.message; + this.cursor = opts.cursor || 0; + this.scrollIndex = opts.cursor || 0; + this.hint = opts.hint || ''; + this.warn = opts.warn || '- This option is disabled -'; + this.minSelected = opts.min; + this.showMinError = false; + this.maxChoices = opts.max; + this.instructions = opts.instructions; + this.optionsPerPage = opts.optionsPerPage || 10; + this.value = opts.choices.map((ch, idx) => { + if (typeof ch === 'string') ch = { + title: ch, + value: idx + }; + return { + title: ch && (ch.title || ch.value || ch), + description: ch && ch.description, + value: ch && (ch.value === undefined ? idx : ch.value), + selected: ch && ch.selected, + disabled: ch && ch.disabled + }; + }); + this.clear = clear('', this.out.columns); + + if (!opts.overrideRender) { + this.render(); + } + } + + reset() { + this.value.map(v => !v.selected); + this.cursor = 0; + this.fire(); + this.render(); + } + + selected() { + return this.value.filter(v => v.selected); + } + + exit() { + this.abort(); + } + + abort() { + this.done = this.aborted = true; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + + submit() { + const selected = this.value.filter(e => e.selected); + + if (this.minSelected && selected.length < this.minSelected) { + this.showMinError = true; + this.render(); + } else { + this.done = true; + this.aborted = false; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + } + + first() { + this.cursor = 0; + this.render(); + } + + last() { + this.cursor = this.value.length - 1; + this.render(); + } + + next() { + this.cursor = (this.cursor + 1) % this.value.length; + this.render(); + } + + up() { + if (this.cursor === 0) { + this.cursor = this.value.length - 1; + } else { + this.cursor--; + } + + this.render(); + } + + down() { + if (this.cursor === this.value.length - 1) { + this.cursor = 0; + } else { + this.cursor++; + } + + this.render(); + } + + left() { + this.value[this.cursor].selected = false; + this.render(); + } + + right() { + if (this.value.filter(e => e.selected).length >= this.maxChoices) return this.bell(); + this.value[this.cursor].selected = true; + this.render(); + } + + handleSpaceToggle() { + const v = this.value[this.cursor]; + + if (v.selected) { + v.selected = false; + this.render(); + } else if (v.disabled || this.value.filter(e => e.selected).length >= this.maxChoices) { + return this.bell(); + } else { + v.selected = true; + this.render(); + } + } + + toggleAll() { + if (this.maxChoices !== undefined || this.value[this.cursor].disabled) { + return this.bell(); + } + + const newSelected = !this.value[this.cursor].selected; + this.value.filter(v => !v.disabled).forEach(v => v.selected = newSelected); + this.render(); + } + + _(c, key) { + if (c === ' ') { + this.handleSpaceToggle(); + } else if (c === 'a') { + this.toggleAll(); + } else { + return this.bell(); + } + } + + renderInstructions() { + if (this.instructions === undefined || this.instructions) { + if (typeof this.instructions === 'string') { + return this.instructions; + } + + return '\nInstructions:\n' + ` ${figures.arrowUp}/${figures.arrowDown}: Highlight option\n` + ` ${figures.arrowLeft}/${figures.arrowRight}/[space]: Toggle selection\n` + (this.maxChoices === undefined ? ` a: Toggle all\n` : '') + ` enter/return: Complete answer`; + } + + return ''; + } + + renderOption(cursor, v, i, arrowIndicator) { + const prefix = (v.selected ? color.green(figures.radioOn) : figures.radioOff) + ' ' + arrowIndicator + ' '; + let title, desc; + + if (v.disabled) { + title = cursor === i ? color.gray().underline(v.title) : color.strikethrough().gray(v.title); + } else { + title = cursor === i ? color.cyan().underline(v.title) : v.title; + + if (cursor === i && v.description) { + desc = ` - ${v.description}`; + + if (prefix.length + title.length + desc.length >= this.out.columns || v.description.split(/\r?\n/).length > 1) { + desc = '\n' + wrap(v.description, { + margin: prefix.length, + width: this.out.columns + }); + } + } + } + + return prefix + title + color.gray(desc || ''); + } // shared with autocompleteMultiselect + + + paginateOptions(options) { + if (options.length === 0) { + return color.red('No matches for this query.'); + } + + let _entriesToDisplay = entriesToDisplay(this.cursor, options.length, this.optionsPerPage), + startIndex = _entriesToDisplay.startIndex, + endIndex = _entriesToDisplay.endIndex; + + let prefix, + styledOptions = []; + + for (let i = startIndex; i < endIndex; i++) { + if (i === startIndex && startIndex > 0) { + prefix = figures.arrowUp; + } else if (i === endIndex - 1 && endIndex < options.length) { + prefix = figures.arrowDown; + } else { + prefix = ' '; + } + + styledOptions.push(this.renderOption(this.cursor, options[i], i, prefix)); + } + + return '\n' + styledOptions.join('\n'); + } // shared with autocomleteMultiselect + + + renderOptions(options) { + if (!this.done) { + return this.paginateOptions(options); + } + + return ''; + } + + renderDoneOrInstructions() { + if (this.done) { + return this.value.filter(e => e.selected).map(v => v.title).join(', '); + } + + const output = [color.gray(this.hint), this.renderInstructions()]; + + if (this.value[this.cursor].disabled) { + output.push(color.yellow(this.warn)); + } + + return output.join(' '); + } + + render() { + if (this.closed) return; + if (this.firstRender) this.out.write(cursor.hide); + super.render(); // print prompt + + let prompt = [style.symbol(this.done, this.aborted), color.bold(this.msg), style.delimiter(false), this.renderDoneOrInstructions()].join(' '); + + if (this.showMinError) { + prompt += color.red(`You must select a minimum of ${this.minSelected} choices.`); + this.showMinError = false; + } + + prompt += this.renderOptions(this.value); + this.out.write(this.clear + prompt); + this.clear = clear(prompt, this.out.columns); + } + + } + + multiselect$1 = MultiselectPrompt; + return multiselect$1; +} + +var autocomplete$1; +var hasRequiredAutocomplete$1; + +function requireAutocomplete$1 () { + if (hasRequiredAutocomplete$1) return autocomplete$1; + hasRequiredAutocomplete$1 = 1; + + function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } + + function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } + + const color = requireKleur(); + + const Prompt = requirePrompt$1(); + + const _require = requireSrc(), + erase = _require.erase, + cursor = _require.cursor; + + const _require2 = requireUtil$2(), + style = _require2.style, + clear = _require2.clear, + figures = _require2.figures, + wrap = _require2.wrap, + entriesToDisplay = _require2.entriesToDisplay; + + const getVal = (arr, i) => arr[i] && (arr[i].value || arr[i].title || arr[i]); + + const getTitle = (arr, i) => arr[i] && (arr[i].title || arr[i].value || arr[i]); + + const getIndex = (arr, valOrTitle) => { + const index = arr.findIndex(el => el.value === valOrTitle || el.title === valOrTitle); + return index > -1 ? index : undefined; + }; + /** + * TextPrompt Base Element + * @param {Object} opts Options + * @param {String} opts.message Message + * @param {Array} opts.choices Array of auto-complete choices objects + * @param {Function} [opts.suggest] Filter function. Defaults to sort by title + * @param {Number} [opts.limit=10] Max number of results to show + * @param {Number} [opts.cursor=0] Cursor start position + * @param {String} [opts.style='default'] Render style + * @param {String} [opts.fallback] Fallback message - initial to default value + * @param {String} [opts.initial] Index of the default value + * @param {Boolean} [opts.clearFirst] The first ESCAPE keypress will clear the input + * @param {Stream} [opts.stdin] The Readable stream to listen to + * @param {Stream} [opts.stdout] The Writable stream to write readline data to + * @param {String} [opts.noMatches] The no matches found label + */ + + + class AutocompletePrompt extends Prompt { + constructor(opts = {}) { + super(opts); + this.msg = opts.message; + this.suggest = opts.suggest; + this.choices = opts.choices; + this.initial = typeof opts.initial === 'number' ? opts.initial : getIndex(opts.choices, opts.initial); + this.select = this.initial || opts.cursor || 0; + this.i18n = { + noMatches: opts.noMatches || 'no matches found' + }; + this.fallback = opts.fallback || this.initial; + this.clearFirst = opts.clearFirst || false; + this.suggestions = []; + this.input = ''; + this.limit = opts.limit || 10; + this.cursor = 0; + this.transform = style.render(opts.style); + this.scale = this.transform.scale; + this.render = this.render.bind(this); + this.complete = this.complete.bind(this); + this.clear = clear('', this.out.columns); + this.complete(this.render); + this.render(); + } + + set fallback(fb) { + this._fb = Number.isSafeInteger(parseInt(fb)) ? parseInt(fb) : fb; + } + + get fallback() { + let choice; + if (typeof this._fb === 'number') choice = this.choices[this._fb];else if (typeof this._fb === 'string') choice = { + title: this._fb + }; + return choice || this._fb || { + title: this.i18n.noMatches + }; + } + + moveSelect(i) { + this.select = i; + if (this.suggestions.length > 0) this.value = getVal(this.suggestions, i);else this.value = this.fallback.value; + this.fire(); + } + + complete(cb) { + var _this = this; + + return _asyncToGenerator(function* () { + const p = _this.completing = _this.suggest(_this.input, _this.choices); + + const suggestions = yield p; + if (_this.completing !== p) return; + _this.suggestions = suggestions.map((s, i, arr) => ({ + title: getTitle(arr, i), + value: getVal(arr, i), + description: s.description + })); + _this.completing = false; + const l = Math.max(suggestions.length - 1, 0); + + _this.moveSelect(Math.min(l, _this.select)); + + cb && cb(); + })(); + } + + reset() { + this.input = ''; + this.complete(() => { + this.moveSelect(this.initial !== void 0 ? this.initial : 0); + this.render(); + }); + this.render(); + } + + exit() { + if (this.clearFirst && this.input.length > 0) { + this.reset(); + } else { + this.done = this.exited = true; + this.aborted = false; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + } + + abort() { + this.done = this.aborted = true; + this.exited = false; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + + submit() { + this.done = true; + this.aborted = this.exited = false; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + + _(c, key) { + let s1 = this.input.slice(0, this.cursor); + let s2 = this.input.slice(this.cursor); + this.input = `${s1}${c}${s2}`; + this.cursor = s1.length + 1; + this.complete(this.render); + this.render(); + } + + delete() { + if (this.cursor === 0) return this.bell(); + let s1 = this.input.slice(0, this.cursor - 1); + let s2 = this.input.slice(this.cursor); + this.input = `${s1}${s2}`; + this.complete(this.render); + this.cursor = this.cursor - 1; + this.render(); + } + + deleteForward() { + if (this.cursor * this.scale >= this.rendered.length) return this.bell(); + let s1 = this.input.slice(0, this.cursor); + let s2 = this.input.slice(this.cursor + 1); + this.input = `${s1}${s2}`; + this.complete(this.render); + this.render(); + } + + first() { + this.moveSelect(0); + this.render(); + } + + last() { + this.moveSelect(this.suggestions.length - 1); + this.render(); + } + + up() { + if (this.select === 0) { + this.moveSelect(this.suggestions.length - 1); + } else { + this.moveSelect(this.select - 1); + } + + this.render(); + } + + down() { + if (this.select === this.suggestions.length - 1) { + this.moveSelect(0); + } else { + this.moveSelect(this.select + 1); + } + + this.render(); + } + + next() { + if (this.select === this.suggestions.length - 1) { + this.moveSelect(0); + } else this.moveSelect(this.select + 1); + + this.render(); + } + + nextPage() { + this.moveSelect(Math.min(this.select + this.limit, this.suggestions.length - 1)); + this.render(); + } + + prevPage() { + this.moveSelect(Math.max(this.select - this.limit, 0)); + this.render(); + } + + left() { + if (this.cursor <= 0) return this.bell(); + this.cursor = this.cursor - 1; + this.render(); + } + + right() { + if (this.cursor * this.scale >= this.rendered.length) return this.bell(); + this.cursor = this.cursor + 1; + this.render(); + } + + renderOption(v, hovered, isStart, isEnd) { + let desc; + let prefix = isStart ? figures.arrowUp : isEnd ? figures.arrowDown : ' '; + let title = hovered ? color.cyan().underline(v.title) : v.title; + prefix = (hovered ? color.cyan(figures.pointer) + ' ' : ' ') + prefix; + + if (v.description) { + desc = ` - ${v.description}`; + + if (prefix.length + title.length + desc.length >= this.out.columns || v.description.split(/\r?\n/).length > 1) { + desc = '\n' + wrap(v.description, { + margin: 3, + width: this.out.columns + }); + } + } + + return prefix + ' ' + title + color.gray(desc || ''); + } + + render() { + if (this.closed) return; + if (this.firstRender) this.out.write(cursor.hide);else this.out.write(clear(this.outputText, this.out.columns)); + super.render(); + + let _entriesToDisplay = entriesToDisplay(this.select, this.choices.length, this.limit), + startIndex = _entriesToDisplay.startIndex, + endIndex = _entriesToDisplay.endIndex; + + this.outputText = [style.symbol(this.done, this.aborted, this.exited), color.bold(this.msg), style.delimiter(this.completing), this.done && this.suggestions[this.select] ? this.suggestions[this.select].title : this.rendered = this.transform.render(this.input)].join(' '); + + if (!this.done) { + const suggestions = this.suggestions.slice(startIndex, endIndex).map((item, i) => this.renderOption(item, this.select === i + startIndex, i === 0 && startIndex > 0, i + startIndex === endIndex - 1 && endIndex < this.choices.length)).join('\n'); + this.outputText += `\n` + (suggestions || color.gray(this.fallback.title)); + } + + this.out.write(erase.line + cursor.to(0) + this.outputText); + } + + } + + autocomplete$1 = AutocompletePrompt; + return autocomplete$1; +} + +var autocompleteMultiselect$1; +var hasRequiredAutocompleteMultiselect$1; + +function requireAutocompleteMultiselect$1 () { + if (hasRequiredAutocompleteMultiselect$1) return autocompleteMultiselect$1; + hasRequiredAutocompleteMultiselect$1 = 1; + + const color = requireKleur(); + + const _require = requireSrc(), + cursor = _require.cursor; + + const MultiselectPrompt = requireMultiselect$1(); + + const _require2 = requireUtil$2(), + clear = _require2.clear, + style = _require2.style, + figures = _require2.figures; + /** + * MultiselectPrompt Base Element + * @param {Object} opts Options + * @param {String} opts.message Message + * @param {Array} opts.choices Array of choice objects + * @param {String} [opts.hint] Hint to display + * @param {String} [opts.warn] Hint shown for disabled choices + * @param {Number} [opts.max] Max choices + * @param {Number} [opts.cursor=0] Cursor start position + * @param {Stream} [opts.stdin] The Readable stream to listen to + * @param {Stream} [opts.stdout] The Writable stream to write readline data to + */ + + + class AutocompleteMultiselectPrompt extends MultiselectPrompt { + constructor(opts = {}) { + opts.overrideRender = true; + super(opts); + this.inputValue = ''; + this.clear = clear('', this.out.columns); + this.filteredOptions = this.value; + this.render(); + } + + last() { + this.cursor = this.filteredOptions.length - 1; + this.render(); + } + + next() { + this.cursor = (this.cursor + 1) % this.filteredOptions.length; + this.render(); + } + + up() { + if (this.cursor === 0) { + this.cursor = this.filteredOptions.length - 1; + } else { + this.cursor--; + } + + this.render(); + } + + down() { + if (this.cursor === this.filteredOptions.length - 1) { + this.cursor = 0; + } else { + this.cursor++; + } + + this.render(); + } + + left() { + this.filteredOptions[this.cursor].selected = false; + this.render(); + } + + right() { + if (this.value.filter(e => e.selected).length >= this.maxChoices) return this.bell(); + this.filteredOptions[this.cursor].selected = true; + this.render(); + } + + delete() { + if (this.inputValue.length) { + this.inputValue = this.inputValue.substr(0, this.inputValue.length - 1); + this.updateFilteredOptions(); + } + } + + updateFilteredOptions() { + const currentHighlight = this.filteredOptions[this.cursor]; + this.filteredOptions = this.value.filter(v => { + if (this.inputValue) { + if (typeof v.title === 'string') { + if (v.title.toLowerCase().includes(this.inputValue.toLowerCase())) { + return true; + } + } + + if (typeof v.value === 'string') { + if (v.value.toLowerCase().includes(this.inputValue.toLowerCase())) { + return true; + } + } + + return false; + } + + return true; + }); + const newHighlightIndex = this.filteredOptions.findIndex(v => v === currentHighlight); + this.cursor = newHighlightIndex < 0 ? 0 : newHighlightIndex; + this.render(); + } + + handleSpaceToggle() { + const v = this.filteredOptions[this.cursor]; + + if (v.selected) { + v.selected = false; + this.render(); + } else if (v.disabled || this.value.filter(e => e.selected).length >= this.maxChoices) { + return this.bell(); + } else { + v.selected = true; + this.render(); + } + } + + handleInputChange(c) { + this.inputValue = this.inputValue + c; + this.updateFilteredOptions(); + } + + _(c, key) { + if (c === ' ') { + this.handleSpaceToggle(); + } else { + this.handleInputChange(c); + } + } + + renderInstructions() { + if (this.instructions === undefined || this.instructions) { + if (typeof this.instructions === 'string') { + return this.instructions; + } + + return ` +Instructions: + ${figures.arrowUp}/${figures.arrowDown}: Highlight option + ${figures.arrowLeft}/${figures.arrowRight}/[space]: Toggle selection + [a,b,c]/delete: Filter choices + enter/return: Complete answer +`; + } + + return ''; + } + + renderCurrentInput() { + return ` +Filtered results for: ${this.inputValue ? this.inputValue : color.gray('Enter something to filter')}\n`; + } + + renderOption(cursor, v, i) { + let title; + if (v.disabled) title = cursor === i ? color.gray().underline(v.title) : color.strikethrough().gray(v.title);else title = cursor === i ? color.cyan().underline(v.title) : v.title; + return (v.selected ? color.green(figures.radioOn) : figures.radioOff) + ' ' + title; + } + + renderDoneOrInstructions() { + if (this.done) { + return this.value.filter(e => e.selected).map(v => v.title).join(', '); + } + + const output = [color.gray(this.hint), this.renderInstructions(), this.renderCurrentInput()]; + + if (this.filteredOptions.length && this.filteredOptions[this.cursor].disabled) { + output.push(color.yellow(this.warn)); + } + + return output.join(' '); + } + + render() { + if (this.closed) return; + if (this.firstRender) this.out.write(cursor.hide); + super.render(); // print prompt + + let prompt = [style.symbol(this.done, this.aborted), color.bold(this.msg), style.delimiter(false), this.renderDoneOrInstructions()].join(' '); + + if (this.showMinError) { + prompt += color.red(`You must select a minimum of ${this.minSelected} choices.`); + this.showMinError = false; + } + + prompt += this.renderOptions(this.filteredOptions); + this.out.write(this.clear + prompt); + this.clear = clear(prompt, this.out.columns); + } + + } + + autocompleteMultiselect$1 = AutocompleteMultiselectPrompt; + return autocompleteMultiselect$1; +} + +var confirm$1; +var hasRequiredConfirm$1; + +function requireConfirm$1 () { + if (hasRequiredConfirm$1) return confirm$1; + hasRequiredConfirm$1 = 1; + + const color = requireKleur(); + + const Prompt = requirePrompt$1(); + + const _require = requireUtil$2(), + style = _require.style, + clear = _require.clear; + + const _require2 = requireSrc(), + erase = _require2.erase, + cursor = _require2.cursor; + /** + * ConfirmPrompt Base Element + * @param {Object} opts Options + * @param {String} opts.message Message + * @param {Boolean} [opts.initial] Default value (true/false) + * @param {Stream} [opts.stdin] The Readable stream to listen to + * @param {Stream} [opts.stdout] The Writable stream to write readline data to + * @param {String} [opts.yes] The "Yes" label + * @param {String} [opts.yesOption] The "Yes" option when choosing between yes/no + * @param {String} [opts.no] The "No" label + * @param {String} [opts.noOption] The "No" option when choosing between yes/no + */ + + + class ConfirmPrompt extends Prompt { + constructor(opts = {}) { + super(opts); + this.msg = opts.message; + this.value = opts.initial; + this.initialValue = !!opts.initial; + this.yesMsg = opts.yes || 'yes'; + this.yesOption = opts.yesOption || '(Y/n)'; + this.noMsg = opts.no || 'no'; + this.noOption = opts.noOption || '(y/N)'; + this.render(); + } + + reset() { + this.value = this.initialValue; + this.fire(); + this.render(); + } + + exit() { + this.abort(); + } + + abort() { + this.done = this.aborted = true; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + + submit() { + this.value = this.value || false; + this.done = true; + this.aborted = false; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + + _(c, key) { + if (c.toLowerCase() === 'y') { + this.value = true; + return this.submit(); + } + + if (c.toLowerCase() === 'n') { + this.value = false; + return this.submit(); + } + + return this.bell(); + } + + render() { + if (this.closed) return; + if (this.firstRender) this.out.write(cursor.hide);else this.out.write(clear(this.outputText, this.out.columns)); + super.render(); + this.outputText = [style.symbol(this.done, this.aborted), color.bold(this.msg), style.delimiter(this.done), this.done ? this.value ? this.yesMsg : this.noMsg : color.gray(this.initialValue ? this.yesOption : this.noOption)].join(' '); + this.out.write(erase.line + cursor.to(0) + this.outputText); + } + + } + + confirm$1 = ConfirmPrompt; + return confirm$1; +} + +var elements$1; +var hasRequiredElements$1; + +function requireElements$1 () { + if (hasRequiredElements$1) return elements$1; + hasRequiredElements$1 = 1; + + elements$1 = { + TextPrompt: requireText$1(), + SelectPrompt: requireSelect$1(), + TogglePrompt: requireToggle$1(), + DatePrompt: requireDate$1(), + NumberPrompt: requireNumber$1(), + MultiselectPrompt: requireMultiselect$1(), + AutocompletePrompt: requireAutocomplete$1(), + AutocompleteMultiselectPrompt: requireAutocompleteMultiselect$1(), + ConfirmPrompt: requireConfirm$1() + }; + return elements$1; +} + +var hasRequiredPrompts$1; + +function requirePrompts$1 () { + if (hasRequiredPrompts$1) return prompts$3; + hasRequiredPrompts$1 = 1; + (function (exports) { + + const $ = exports; + + const el = requireElements$1(); + + const noop = v => v; + + function toPrompt(type, args, opts = {}) { + return new Promise((res, rej) => { + const p = new el[type](args); + const onAbort = opts.onAbort || noop; + const onSubmit = opts.onSubmit || noop; + const onExit = opts.onExit || noop; + p.on('state', args.onState || noop); + p.on('submit', x => res(onSubmit(x))); + p.on('exit', x => res(onExit(x))); + p.on('abort', x => rej(onAbort(x))); + }); + } + /** + * Text prompt + * @param {string} args.message Prompt message to display + * @param {string} [args.initial] Default string value + * @param {string} [args.style="default"] Render style ('default', 'password', 'invisible') + * @param {function} [args.onState] On state change callback + * @param {function} [args.validate] Function to validate user input + * @param {Stream} [args.stdin] The Readable stream to listen to + * @param {Stream} [args.stdout] The Writable stream to write readline data to + * @returns {Promise} Promise with user input + */ + + + $.text = args => toPrompt('TextPrompt', args); + /** + * Password prompt with masked input + * @param {string} args.message Prompt message to display + * @param {string} [args.initial] Default string value + * @param {function} [args.onState] On state change callback + * @param {function} [args.validate] Function to validate user input + * @param {Stream} [args.stdin] The Readable stream to listen to + * @param {Stream} [args.stdout] The Writable stream to write readline data to + * @returns {Promise} Promise with user input + */ + + + $.password = args => { + args.style = 'password'; + return $.text(args); + }; + /** + * Prompt where input is invisible, like sudo + * @param {string} args.message Prompt message to display + * @param {string} [args.initial] Default string value + * @param {function} [args.onState] On state change callback + * @param {function} [args.validate] Function to validate user input + * @param {Stream} [args.stdin] The Readable stream to listen to + * @param {Stream} [args.stdout] The Writable stream to write readline data to + * @returns {Promise} Promise with user input + */ + + + $.invisible = args => { + args.style = 'invisible'; + return $.text(args); + }; + /** + * Number prompt + * @param {string} args.message Prompt message to display + * @param {number} args.initial Default number value + * @param {function} [args.onState] On state change callback + * @param {number} [args.max] Max value + * @param {number} [args.min] Min value + * @param {string} [args.style="default"] Render style ('default', 'password', 'invisible') + * @param {Boolean} [opts.float=false] Parse input as floats + * @param {Number} [opts.round=2] Round floats to x decimals + * @param {Number} [opts.increment=1] Number to increment by when using arrow-keys + * @param {function} [args.validate] Function to validate user input + * @param {Stream} [args.stdin] The Readable stream to listen to + * @param {Stream} [args.stdout] The Writable stream to write readline data to + * @returns {Promise} Promise with user input + */ + + + $.number = args => toPrompt('NumberPrompt', args); + /** + * Date prompt + * @param {string} args.message Prompt message to display + * @param {number} args.initial Default number value + * @param {function} [args.onState] On state change callback + * @param {number} [args.max] Max value + * @param {number} [args.min] Min value + * @param {string} [args.style="default"] Render style ('default', 'password', 'invisible') + * @param {Boolean} [opts.float=false] Parse input as floats + * @param {Number} [opts.round=2] Round floats to x decimals + * @param {Number} [opts.increment=1] Number to increment by when using arrow-keys + * @param {function} [args.validate] Function to validate user input + * @param {Stream} [args.stdin] The Readable stream to listen to + * @param {Stream} [args.stdout] The Writable stream to write readline data to + * @returns {Promise} Promise with user input + */ + + + $.date = args => toPrompt('DatePrompt', args); + /** + * Classic yes/no prompt + * @param {string} args.message Prompt message to display + * @param {boolean} [args.initial=false] Default value + * @param {function} [args.onState] On state change callback + * @param {Stream} [args.stdin] The Readable stream to listen to + * @param {Stream} [args.stdout] The Writable stream to write readline data to + * @returns {Promise} Promise with user input + */ + + + $.confirm = args => toPrompt('ConfirmPrompt', args); + /** + * List prompt, split intput string by `seperator` + * @param {string} args.message Prompt message to display + * @param {string} [args.initial] Default string value + * @param {string} [args.style="default"] Render style ('default', 'password', 'invisible') + * @param {string} [args.separator] String separator + * @param {function} [args.onState] On state change callback + * @param {Stream} [args.stdin] The Readable stream to listen to + * @param {Stream} [args.stdout] The Writable stream to write readline data to + * @returns {Promise} Promise with user input, in form of an `Array` + */ + + + $.list = args => { + const sep = args.separator || ','; + return toPrompt('TextPrompt', args, { + onSubmit: str => str.split(sep).map(s => s.trim()) + }); + }; + /** + * Toggle/switch prompt + * @param {string} args.message Prompt message to display + * @param {boolean} [args.initial=false] Default value + * @param {string} [args.active="on"] Text for `active` state + * @param {string} [args.inactive="off"] Text for `inactive` state + * @param {function} [args.onState] On state change callback + * @param {Stream} [args.stdin] The Readable stream to listen to + * @param {Stream} [args.stdout] The Writable stream to write readline data to + * @returns {Promise} Promise with user input + */ + + + $.toggle = args => toPrompt('TogglePrompt', args); + /** + * Interactive select prompt + * @param {string} args.message Prompt message to display + * @param {Array} args.choices Array of choices objects `[{ title, value }, ...]` + * @param {number} [args.initial] Index of default value + * @param {String} [args.hint] Hint to display + * @param {function} [args.onState] On state change callback + * @param {Stream} [args.stdin] The Readable stream to listen to + * @param {Stream} [args.stdout] The Writable stream to write readline data to + * @returns {Promise} Promise with user input + */ + + + $.select = args => toPrompt('SelectPrompt', args); + /** + * Interactive multi-select / autocompleteMultiselect prompt + * @param {string} args.message Prompt message to display + * @param {Array} args.choices Array of choices objects `[{ title, value, [selected] }, ...]` + * @param {number} [args.max] Max select + * @param {string} [args.hint] Hint to display user + * @param {Number} [args.cursor=0] Cursor start position + * @param {function} [args.onState] On state change callback + * @param {Stream} [args.stdin] The Readable stream to listen to + * @param {Stream} [args.stdout] The Writable stream to write readline data to + * @returns {Promise} Promise with user input + */ + + + $.multiselect = args => { + args.choices = [].concat(args.choices || []); + + const toSelected = items => items.filter(item => item.selected).map(item => item.value); + + return toPrompt('MultiselectPrompt', args, { + onAbort: toSelected, + onSubmit: toSelected + }); + }; + + $.autocompleteMultiselect = args => { + args.choices = [].concat(args.choices || []); + + const toSelected = items => items.filter(item => item.selected).map(item => item.value); + + return toPrompt('AutocompleteMultiselectPrompt', args, { + onAbort: toSelected, + onSubmit: toSelected + }); + }; + + const byTitle = (input, choices) => Promise.resolve(choices.filter(item => item.title.slice(0, input.length).toLowerCase() === input.toLowerCase())); + /** + * Interactive auto-complete prompt + * @param {string} args.message Prompt message to display + * @param {Array} args.choices Array of auto-complete choices objects `[{ title, value }, ...]` + * @param {Function} [args.suggest] Function to filter results based on user input. Defaults to sort by `title` + * @param {number} [args.limit=10] Max number of results to show + * @param {string} [args.style="default"] Render style ('default', 'password', 'invisible') + * @param {String} [args.initial] Index of the default value + * @param {boolean} [opts.clearFirst] The first ESCAPE keypress will clear the input + * @param {String} [args.fallback] Fallback message - defaults to initial value + * @param {function} [args.onState] On state change callback + * @param {Stream} [args.stdin] The Readable stream to listen to + * @param {Stream} [args.stdout] The Writable stream to write readline data to + * @returns {Promise} Promise with user input + */ + + + $.autocomplete = args => { + args.suggest = args.suggest || byTitle; + args.choices = [].concat(args.choices || []); + return toPrompt('AutocompletePrompt', args); + }; + } (prompts$3)); + return prompts$3; +} + +var dist$4; +var hasRequiredDist; + +function requireDist () { + if (hasRequiredDist) return dist$4; + hasRequiredDist = 1; + + function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } + + function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + + function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + + function _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 asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } + + function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } + + const prompts = requirePrompts$1(); + + const passOn = ['suggest', 'format', 'onState', 'validate', 'onRender', 'type']; + + const noop = () => {}; + /** + * Prompt for a series of questions + * @param {Array|Object} questions Single question object or Array of question objects + * @param {Function} [onSubmit] Callback function called on prompt submit + * @param {Function} [onCancel] Callback function called on cancel/abort + * @returns {Object} Object with values from user input + */ + + + function prompt() { + return _prompt.apply(this, arguments); + } + + function _prompt() { + _prompt = _asyncToGenerator(function* (questions = [], { + onSubmit = noop, + onCancel = noop + } = {}) { + const answers = {}; + const override = prompt._override || {}; + questions = [].concat(questions); + let answer, question, quit, name, type, lastPrompt; + + const getFormattedAnswer = /*#__PURE__*/function () { + var _ref = _asyncToGenerator(function* (question, answer, skipValidation = false) { + if (!skipValidation && question.validate && question.validate(answer) !== true) { + return; + } + + return question.format ? yield question.format(answer, answers) : answer; + }); + + return function getFormattedAnswer(_x, _x2) { + return _ref.apply(this, arguments); + }; + }(); + + var _iterator = _createForOfIteratorHelper(questions), + _step; + + try { + for (_iterator.s(); !(_step = _iterator.n()).done;) { + question = _step.value; + var _question = question; + name = _question.name; + type = _question.type; + + // evaluate type first and skip if type is a falsy value + if (typeof type === 'function') { + type = yield type(answer, _objectSpread({}, answers), question); + question['type'] = type; + } + + if (!type) continue; // if property is a function, invoke it unless it's a special function + + for (let key in question) { + if (passOn.includes(key)) continue; + let value = question[key]; + question[key] = typeof value === 'function' ? yield value(answer, _objectSpread({}, answers), lastPrompt) : value; + } + + lastPrompt = question; + + if (typeof question.message !== 'string') { + throw new Error('prompt message is required'); + } // update vars in case they changed + + + var _question2 = question; + name = _question2.name; + type = _question2.type; + + if (prompts[type] === void 0) { + throw new Error(`prompt type (${type}) is not defined`); + } + + if (override[question.name] !== undefined) { + answer = yield getFormattedAnswer(question, override[question.name]); + + if (answer !== undefined) { + answers[name] = answer; + continue; + } + } + + try { + // Get the injected answer if there is one or prompt the user + answer = prompt._injected ? getInjectedAnswer(prompt._injected, question.initial) : yield prompts[type](question); + answers[name] = answer = yield getFormattedAnswer(question, answer, true); + quit = yield onSubmit(question, answer, answers); + } catch (err) { + quit = !(yield onCancel(question, answers)); + } + + if (quit) return answers; + } + } catch (err) { + _iterator.e(err); + } finally { + _iterator.f(); + } + + return answers; + }); + return _prompt.apply(this, arguments); + } + + function getInjectedAnswer(injected, deafultValue) { + const answer = injected.shift(); + + if (answer instanceof Error) { + throw answer; + } + + return answer === undefined ? deafultValue : answer; + } + + function inject(answers) { + prompt._injected = (prompt._injected || []).concat(answers); + } + + function override(answers) { + prompt._override = Object.assign({}, answers); + } + + dist$4 = Object.assign(prompt, { + prompt, + prompts, + inject, + override + }); + return dist$4; +} + +var prompts$2 = {}; + +var action; +var hasRequiredAction; + +function requireAction () { + if (hasRequiredAction) return action; + hasRequiredAction = 1; + + action = (key, isSelect) => { + if (key.meta && key.name !== 'escape') return; + + if (key.ctrl) { + if (key.name === 'a') return 'first'; + if (key.name === 'c') return 'abort'; + if (key.name === 'd') return 'abort'; + if (key.name === 'e') return 'last'; + if (key.name === 'g') return 'reset'; + } + + if (isSelect) { + if (key.name === 'j') return 'down'; + if (key.name === 'k') return 'up'; + } + + if (key.name === 'return') return 'submit'; + if (key.name === 'enter') return 'submit'; // ctrl + J + if (key.name === 'backspace') return 'delete'; + if (key.name === 'delete') return 'deleteForward'; + if (key.name === 'abort') return 'abort'; + if (key.name === 'escape') return 'exit'; + if (key.name === 'tab') return 'next'; + if (key.name === 'pagedown') return 'nextPage'; + if (key.name === 'pageup') return 'prevPage'; + // TODO create home() in prompt types (e.g. TextPrompt) + if (key.name === 'home') return 'home'; + // TODO create end() in prompt types (e.g. TextPrompt) + if (key.name === 'end') return 'end'; + + if (key.name === 'up') return 'up'; + if (key.name === 'down') return 'down'; + if (key.name === 'right') return 'right'; + if (key.name === 'left') return 'left'; + + return false; + }; + return action; +} + +var strip; +var hasRequiredStrip; + +function requireStrip () { + if (hasRequiredStrip) return strip; + hasRequiredStrip = 1; + + strip = str => { + const pattern = [ + '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)', + '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PRZcf-ntqry=><~]))' + ].join('|'); + + const RGX = new RegExp(pattern, 'g'); + return typeof str === 'string' ? str.replace(RGX, '') : str; + }; + return strip; +} + +var clear; +var hasRequiredClear; + +function requireClear () { + if (hasRequiredClear) return clear; + hasRequiredClear = 1; + + const strip = requireStrip(); + const { erase, cursor } = requireSrc(); + + const width = str => [...strip(str)].length; + + /** + * @param {string} prompt + * @param {number} perLine + */ + clear = function(prompt, perLine) { + if (!perLine) return erase.line + cursor.to(0); + + let rows = 0; + const lines = prompt.split(/\r?\n/); + for (let line of lines) { + rows += 1 + Math.floor(Math.max(width(line) - 1, 0) / perLine); + } + + return erase.lines(rows); + }; + return clear; +} + +var figures_1; +var hasRequiredFigures; + +function requireFigures () { + if (hasRequiredFigures) return figures_1; + hasRequiredFigures = 1; + + const main = { + arrowUp: '↑', + arrowDown: '↓', + arrowLeft: '←', + arrowRight: '→', + radioOn: '◉', + radioOff: '◯', + tick: '✔', + cross: '✖', + ellipsis: '…', + pointerSmall: '›', + line: '─', + pointer: '❯' + }; + const win = { + arrowUp: main.arrowUp, + arrowDown: main.arrowDown, + arrowLeft: main.arrowLeft, + arrowRight: main.arrowRight, + radioOn: '(*)', + radioOff: '( )', + tick: '√', + cross: '×', + ellipsis: '...', + pointerSmall: '»', + line: '─', + pointer: '>' + }; + const figures = process.platform === 'win32' ? win : main; + + figures_1 = figures; + return figures_1; +} + +var style; +var hasRequiredStyle; + +function requireStyle () { + if (hasRequiredStyle) return style; + hasRequiredStyle = 1; + + const c = requireKleur(); + const figures = requireFigures(); + + // rendering user input. + const styles = Object.freeze({ + password: { scale: 1, render: input => '*'.repeat(input.length) }, + emoji: { scale: 2, render: input => '😃'.repeat(input.length) }, + invisible: { scale: 0, render: input => '' }, + default: { scale: 1, render: input => `${input}` } + }); + const render = type => styles[type] || styles.default; + + // icon to signalize a prompt. + const symbols = Object.freeze({ + aborted: c.red(figures.cross), + done: c.green(figures.tick), + exited: c.yellow(figures.cross), + default: c.cyan('?') + }); + + const symbol = (done, aborted, exited) => + aborted ? symbols.aborted : exited ? symbols.exited : done ? symbols.done : symbols.default; + + // between the question and the user's input. + const delimiter = completing => + c.gray(completing ? figures.ellipsis : figures.pointerSmall); + + const item = (expandable, expanded) => + c.gray(expandable ? (expanded ? figures.pointerSmall : '+') : figures.line); + + style = { + styles, + render, + symbols, + symbol, + delimiter, + item + }; + return style; +} + +var lines; +var hasRequiredLines; + +function requireLines () { + if (hasRequiredLines) return lines; + hasRequiredLines = 1; + + const strip = requireStrip(); + + /** + * @param {string} msg + * @param {number} perLine + */ + lines = function (msg, perLine) { + let lines = String(strip(msg) || '').split(/\r?\n/); + + if (!perLine) return lines.length; + return lines.map(l => Math.ceil(l.length / perLine)) + .reduce((a, b) => a + b); + }; + return lines; +} + +var wrap; +var hasRequiredWrap; + +function requireWrap () { + if (hasRequiredWrap) return wrap; + hasRequiredWrap = 1; + + /** + * @param {string} msg The message to wrap + * @param {object} opts + * @param {number|string} [opts.margin] Left margin + * @param {number} opts.width Maximum characters per line including the margin + */ + wrap = (msg, opts = {}) => { + const tab = Number.isSafeInteger(parseInt(opts.margin)) + ? new Array(parseInt(opts.margin)).fill(' ').join('') + : (opts.margin || ''); + + const width = opts.width; + + return (msg || '').split(/\r?\n/g) + .map(line => line + .split(/\s+/g) + .reduce((arr, w) => { + if (w.length + tab.length >= width || arr[arr.length - 1].length + w.length + 1 < width) + arr[arr.length - 1] += ` ${w}`; + else arr.push(`${tab}${w}`); + return arr; + }, [ tab ]) + .join('\n')) + .join('\n'); + }; + return wrap; +} + +var entriesToDisplay; +var hasRequiredEntriesToDisplay; + +function requireEntriesToDisplay () { + if (hasRequiredEntriesToDisplay) return entriesToDisplay; + hasRequiredEntriesToDisplay = 1; + + /** + * Determine what entries should be displayed on the screen, based on the + * currently selected index and the maximum visible. Used in list-based + * prompts like `select` and `multiselect`. + * + * @param {number} cursor the currently selected entry + * @param {number} total the total entries available to display + * @param {number} [maxVisible] the number of entries that can be displayed + */ + entriesToDisplay = (cursor, total, maxVisible) => { + maxVisible = maxVisible || total; + + let startIndex = Math.min(total- maxVisible, cursor - Math.floor(maxVisible / 2)); + if (startIndex < 0) startIndex = 0; + + let endIndex = Math.min(startIndex + maxVisible, total); + + return { startIndex, endIndex }; + }; + return entriesToDisplay; +} + +var util$a; +var hasRequiredUtil$1; + +function requireUtil$1 () { + if (hasRequiredUtil$1) return util$a; + hasRequiredUtil$1 = 1; + + util$a = { + action: requireAction(), + clear: requireClear(), + style: requireStyle(), + strip: requireStrip(), + figures: requireFigures(), + lines: requireLines(), + wrap: requireWrap(), + entriesToDisplay: requireEntriesToDisplay() + }; + return util$a; +} + +var prompt; +var hasRequiredPrompt; + +function requirePrompt () { + if (hasRequiredPrompt) return prompt; + hasRequiredPrompt = 1; + + const readline = require$$0$g; + const { action } = requireUtil$1(); + const EventEmitter = require$$2$3; + const { beep, cursor } = requireSrc(); + const color = requireKleur(); + + /** + * Base prompt skeleton + * @param {Stream} [opts.stdin] The Readable stream to listen to + * @param {Stream} [opts.stdout] The Writable stream to write readline data to + */ + class Prompt extends EventEmitter { + constructor(opts={}) { + super(); + + this.firstRender = true; + this.in = opts.stdin || process.stdin; + this.out = opts.stdout || process.stdout; + this.onRender = (opts.onRender || (() => void 0)).bind(this); + const rl = readline.createInterface({ input:this.in, escapeCodeTimeout:50 }); + readline.emitKeypressEvents(this.in, rl); + + if (this.in.isTTY) this.in.setRawMode(true); + const isSelect = [ 'SelectPrompt', 'MultiselectPrompt' ].indexOf(this.constructor.name) > -1; + const keypress = (str, key) => { + let a = action(key, isSelect); + if (a === false) { + this._ && this._(str, key); + } else if (typeof this[a] === 'function') { + this[a](key); + } else { + this.bell(); + } + }; + + this.close = () => { + this.out.write(cursor.show); + this.in.removeListener('keypress', keypress); + if (this.in.isTTY) this.in.setRawMode(false); + rl.close(); + this.emit(this.aborted ? 'abort' : this.exited ? 'exit' : 'submit', this.value); + this.closed = true; + }; + + this.in.on('keypress', keypress); + } + + fire() { + this.emit('state', { + value: this.value, + aborted: !!this.aborted, + exited: !!this.exited + }); + } + + bell() { + this.out.write(beep); + } + + render() { + this.onRender(color); + if (this.firstRender) this.firstRender = false; + } + } + + prompt = Prompt; + return prompt; +} + +var text$1; +var hasRequiredText; + +function requireText () { + if (hasRequiredText) return text$1; + hasRequiredText = 1; + const color = requireKleur(); + const Prompt = requirePrompt(); + const { erase, cursor } = requireSrc(); + const { style, clear, lines, figures } = requireUtil$1(); + + /** + * TextPrompt Base Element + * @param {Object} opts Options + * @param {String} opts.message Message + * @param {String} [opts.style='default'] Render style + * @param {String} [opts.initial] Default value + * @param {Function} [opts.validate] Validate function + * @param {Stream} [opts.stdin] The Readable stream to listen to + * @param {Stream} [opts.stdout] The Writable stream to write readline data to + * @param {String} [opts.error] The invalid error label + */ + class TextPrompt extends Prompt { + constructor(opts={}) { + super(opts); + this.transform = style.render(opts.style); + this.scale = this.transform.scale; + this.msg = opts.message; + this.initial = opts.initial || ``; + this.validator = opts.validate || (() => true); + this.value = ``; + this.errorMsg = opts.error || `Please Enter A Valid Value`; + this.cursor = Number(!!this.initial); + this.cursorOffset = 0; + this.clear = clear(``, this.out.columns); + this.render(); + } + + set value(v) { + if (!v && this.initial) { + this.placeholder = true; + this.rendered = color.gray(this.transform.render(this.initial)); + } else { + this.placeholder = false; + this.rendered = this.transform.render(v); + } + this._value = v; + this.fire(); + } + + get value() { + return this._value; + } + + reset() { + this.value = ``; + this.cursor = Number(!!this.initial); + this.cursorOffset = 0; + this.fire(); + this.render(); + } + + exit() { + this.abort(); + } + + abort() { + this.value = this.value || this.initial; + this.done = this.aborted = true; + this.error = false; + this.red = false; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + + async validate() { + let valid = await this.validator(this.value); + if (typeof valid === `string`) { + this.errorMsg = valid; + valid = false; + } + this.error = !valid; + } + + async submit() { + this.value = this.value || this.initial; + this.cursorOffset = 0; + this.cursor = this.rendered.length; + await this.validate(); + if (this.error) { + this.red = true; + this.fire(); + this.render(); + return; + } + this.done = true; + this.aborted = false; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + + next() { + if (!this.placeholder) return this.bell(); + this.value = this.initial; + this.cursor = this.rendered.length; + this.fire(); + this.render(); + } + + moveCursor(n) { + if (this.placeholder) return; + this.cursor = this.cursor+n; + this.cursorOffset += n; + } + + _(c, key) { + let s1 = this.value.slice(0, this.cursor); + let s2 = this.value.slice(this.cursor); + this.value = `${s1}${c}${s2}`; + this.red = false; + this.cursor = this.placeholder ? 0 : s1.length+1; + this.render(); + } + + delete() { + if (this.isCursorAtStart()) return this.bell(); + let s1 = this.value.slice(0, this.cursor-1); + let s2 = this.value.slice(this.cursor); + this.value = `${s1}${s2}`; + this.red = false; + if (this.isCursorAtStart()) { + this.cursorOffset = 0; + } else { + this.cursorOffset++; + this.moveCursor(-1); + } + this.render(); + } + + deleteForward() { + if(this.cursor*this.scale >= this.rendered.length || this.placeholder) return this.bell(); + let s1 = this.value.slice(0, this.cursor); + let s2 = this.value.slice(this.cursor+1); + this.value = `${s1}${s2}`; + this.red = false; + if (this.isCursorAtEnd()) { + this.cursorOffset = 0; + } else { + this.cursorOffset++; + } + this.render(); + } + + first() { + this.cursor = 0; + this.render(); + } + + last() { + this.cursor = this.value.length; + this.render(); + } + + left() { + if (this.cursor <= 0 || this.placeholder) return this.bell(); + this.moveCursor(-1); + this.render(); + } + + right() { + if (this.cursor*this.scale >= this.rendered.length || this.placeholder) return this.bell(); + this.moveCursor(1); + this.render(); + } + + isCursorAtStart() { + return this.cursor === 0 || (this.placeholder && this.cursor === 1); + } + + isCursorAtEnd() { + return this.cursor === this.rendered.length || (this.placeholder && this.cursor === this.rendered.length + 1) + } + + render() { + if (this.closed) return; + if (!this.firstRender) { + if (this.outputError) + this.out.write(cursor.down(lines(this.outputError, this.out.columns) - 1) + clear(this.outputError, this.out.columns)); + this.out.write(clear(this.outputText, this.out.columns)); + } + super.render(); + this.outputError = ''; + + this.outputText = [ + style.symbol(this.done, this.aborted), + color.bold(this.msg), + style.delimiter(this.done), + this.red ? color.red(this.rendered) : this.rendered + ].join(` `); + + if (this.error) { + this.outputError += this.errorMsg.split(`\n`) + .reduce((a, l, i) => a + `\n${i ? ' ' : figures.pointerSmall} ${color.red().italic(l)}`, ``); + } + + this.out.write(erase.line + cursor.to(0) + this.outputText + cursor.save + this.outputError + cursor.restore + cursor.move(this.cursorOffset, 0)); + } + } + + text$1 = TextPrompt; + return text$1; +} + +var select; +var hasRequiredSelect; + +function requireSelect () { + if (hasRequiredSelect) return select; + hasRequiredSelect = 1; + + const color = requireKleur(); + const Prompt = requirePrompt(); + const { style, clear, figures, wrap, entriesToDisplay } = requireUtil$1(); + const { cursor } = requireSrc(); + + /** + * SelectPrompt Base Element + * @param {Object} opts Options + * @param {String} opts.message Message + * @param {Array} opts.choices Array of choice objects + * @param {String} [opts.hint] Hint to display + * @param {Number} [opts.initial] Index of default value + * @param {Stream} [opts.stdin] The Readable stream to listen to + * @param {Stream} [opts.stdout] The Writable stream to write readline data to + * @param {Number} [opts.optionsPerPage=10] Max options to display at once + */ + class SelectPrompt extends Prompt { + constructor(opts={}) { + super(opts); + this.msg = opts.message; + this.hint = opts.hint || '- Use arrow-keys. Return to submit.'; + this.warn = opts.warn || '- This option is disabled'; + this.cursor = opts.initial || 0; + this.choices = opts.choices.map((ch, idx) => { + if (typeof ch === 'string') + ch = {title: ch, value: idx}; + return { + title: ch && (ch.title || ch.value || ch), + value: ch && (ch.value === undefined ? idx : ch.value), + description: ch && ch.description, + selected: ch && ch.selected, + disabled: ch && ch.disabled + }; + }); + this.optionsPerPage = opts.optionsPerPage || 10; + this.value = (this.choices[this.cursor] || {}).value; + this.clear = clear('', this.out.columns); + this.render(); + } + + moveCursor(n) { + this.cursor = n; + this.value = this.choices[n].value; + this.fire(); + } + + reset() { + this.moveCursor(0); + this.fire(); + this.render(); + } + + exit() { + this.abort(); + } + + abort() { + this.done = this.aborted = true; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + + submit() { + if (!this.selection.disabled) { + this.done = true; + this.aborted = false; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } else + this.bell(); + } + + first() { + this.moveCursor(0); + this.render(); + } + + last() { + this.moveCursor(this.choices.length - 1); + this.render(); + } + + up() { + if (this.cursor === 0) { + this.moveCursor(this.choices.length - 1); + } else { + this.moveCursor(this.cursor - 1); + } + this.render(); + } + + down() { + if (this.cursor === this.choices.length - 1) { + this.moveCursor(0); + } else { + this.moveCursor(this.cursor + 1); + } + this.render(); + } + + next() { + this.moveCursor((this.cursor + 1) % this.choices.length); + this.render(); + } + + _(c, key) { + if (c === ' ') return this.submit(); + } + + get selection() { + return this.choices[this.cursor]; + } + + render() { + if (this.closed) return; + if (this.firstRender) this.out.write(cursor.hide); + else this.out.write(clear(this.outputText, this.out.columns)); + super.render(); + + let { startIndex, endIndex } = entriesToDisplay(this.cursor, this.choices.length, this.optionsPerPage); + + // Print prompt + this.outputText = [ + style.symbol(this.done, this.aborted), + color.bold(this.msg), + style.delimiter(false), + this.done ? this.selection.title : this.selection.disabled + ? color.yellow(this.warn) : color.gray(this.hint) + ].join(' '); + + // Print choices + if (!this.done) { + this.outputText += '\n'; + for (let i = startIndex; i < endIndex; i++) { + let title, prefix, desc = '', v = this.choices[i]; + + // Determine whether to display "more choices" indicators + if (i === startIndex && startIndex > 0) { + prefix = figures.arrowUp; + } else if (i === endIndex - 1 && endIndex < this.choices.length) { + prefix = figures.arrowDown; + } else { + prefix = ' '; + } + + if (v.disabled) { + title = this.cursor === i ? color.gray().underline(v.title) : color.strikethrough().gray(v.title); + prefix = (this.cursor === i ? color.bold().gray(figures.pointer) + ' ' : ' ') + prefix; + } else { + title = this.cursor === i ? color.cyan().underline(v.title) : v.title; + prefix = (this.cursor === i ? color.cyan(figures.pointer) + ' ' : ' ') + prefix; + if (v.description && this.cursor === i) { + desc = ` - ${v.description}`; + if (prefix.length + title.length + desc.length >= this.out.columns + || v.description.split(/\r?\n/).length > 1) { + desc = '\n' + wrap(v.description, { margin: 3, width: this.out.columns }); + } + } + } + + this.outputText += `${prefix} ${title}${color.gray(desc)}\n`; + } + } + + this.out.write(this.outputText); + } + } + + select = SelectPrompt; + return select; +} + +var toggle$1; +var hasRequiredToggle; + +function requireToggle () { + if (hasRequiredToggle) return toggle$1; + hasRequiredToggle = 1; + const color = requireKleur(); + const Prompt = requirePrompt(); + const { style, clear } = requireUtil$1(); + const { cursor, erase } = requireSrc(); + + /** + * TogglePrompt Base Element + * @param {Object} opts Options + * @param {String} opts.message Message + * @param {Boolean} [opts.initial=false] Default value + * @param {String} [opts.active='no'] Active label + * @param {String} [opts.inactive='off'] Inactive label + * @param {Stream} [opts.stdin] The Readable stream to listen to + * @param {Stream} [opts.stdout] The Writable stream to write readline data to + */ + class TogglePrompt extends Prompt { + constructor(opts={}) { + super(opts); + this.msg = opts.message; + this.value = !!opts.initial; + this.active = opts.active || 'on'; + this.inactive = opts.inactive || 'off'; + this.initialValue = this.value; + this.render(); + } + + reset() { + this.value = this.initialValue; + this.fire(); + this.render(); + } + + exit() { + this.abort(); + } + + abort() { + this.done = this.aborted = true; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + + submit() { + this.done = true; + this.aborted = false; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + + deactivate() { + if (this.value === false) return this.bell(); + this.value = false; + this.render(); + } + + activate() { + if (this.value === true) return this.bell(); + this.value = true; + this.render(); + } + + delete() { + this.deactivate(); + } + left() { + this.deactivate(); + } + right() { + this.activate(); + } + down() { + this.deactivate(); + } + up() { + this.activate(); + } + + next() { + this.value = !this.value; + this.fire(); + this.render(); + } + + _(c, key) { + if (c === ' ') { + this.value = !this.value; + } else if (c === '1') { + this.value = true; + } else if (c === '0') { + this.value = false; + } else return this.bell(); + this.render(); + } + + render() { + if (this.closed) return; + if (this.firstRender) this.out.write(cursor.hide); + else this.out.write(clear(this.outputText, this.out.columns)); + super.render(); + + this.outputText = [ + style.symbol(this.done, this.aborted), + color.bold(this.msg), + style.delimiter(this.done), + this.value ? this.inactive : color.cyan().underline(this.inactive), + color.gray('/'), + this.value ? color.cyan().underline(this.active) : this.active + ].join(' '); + + this.out.write(erase.line + cursor.to(0) + this.outputText); + } + } + + toggle$1 = TogglePrompt; + return toggle$1; +} + +var datepart; +var hasRequiredDatepart; + +function requireDatepart () { + if (hasRequiredDatepart) return datepart; + hasRequiredDatepart = 1; + + class DatePart { + constructor({token, date, parts, locales}) { + this.token = token; + this.date = date || new Date(); + this.parts = parts || [this]; + this.locales = locales || {}; + } + + up() {} + + down() {} + + next() { + const currentIdx = this.parts.indexOf(this); + return this.parts.find((part, idx) => idx > currentIdx && part instanceof DatePart); + } + + setTo(val) {} + + prev() { + let parts = [].concat(this.parts).reverse(); + const currentIdx = parts.indexOf(this); + return parts.find((part, idx) => idx > currentIdx && part instanceof DatePart); + } + + toString() { + return String(this.date); + } + } + + datepart = DatePart; + return datepart; +} + +var meridiem; +var hasRequiredMeridiem; + +function requireMeridiem () { + if (hasRequiredMeridiem) return meridiem; + hasRequiredMeridiem = 1; + + const DatePart = requireDatepart(); + + class Meridiem extends DatePart { + constructor(opts={}) { + super(opts); + } + + up() { + this.date.setHours((this.date.getHours() + 12) % 24); + } + + down() { + this.up(); + } + + toString() { + let meridiem = this.date.getHours() > 12 ? 'pm' : 'am'; + return /\A/.test(this.token) ? meridiem.toUpperCase() : meridiem; + } + } + + meridiem = Meridiem; + return meridiem; +} + +var day; +var hasRequiredDay; + +function requireDay () { + if (hasRequiredDay) return day; + hasRequiredDay = 1; + + const DatePart = requireDatepart(); + + const pos = n => { + n = n % 10; + return n === 1 ? 'st' + : n === 2 ? 'nd' + : n === 3 ? 'rd' + : 'th'; + }; + + class Day extends DatePart { + constructor(opts={}) { + super(opts); + } + + up() { + this.date.setDate(this.date.getDate() + 1); + } + + down() { + this.date.setDate(this.date.getDate() - 1); + } + + setTo(val) { + this.date.setDate(parseInt(val.substr(-2))); + } + + toString() { + let date = this.date.getDate(); + let day = this.date.getDay(); + return this.token === 'DD' ? String(date).padStart(2, '0') + : this.token === 'Do' ? date + pos(date) + : this.token === 'd' ? day + 1 + : this.token === 'ddd' ? this.locales.weekdaysShort[day] + : this.token === 'dddd' ? this.locales.weekdays[day] + : date; + } + } + + day = Day; + return day; +} + +var hours; +var hasRequiredHours; + +function requireHours () { + if (hasRequiredHours) return hours; + hasRequiredHours = 1; + + const DatePart = requireDatepart(); + + class Hours extends DatePart { + constructor(opts={}) { + super(opts); + } + + up() { + this.date.setHours(this.date.getHours() + 1); + } + + down() { + this.date.setHours(this.date.getHours() - 1); + } + + setTo(val) { + this.date.setHours(parseInt(val.substr(-2))); + } + + toString() { + let hours = this.date.getHours(); + if (/h/.test(this.token)) + hours = (hours % 12) || 12; + return this.token.length > 1 ? String(hours).padStart(2, '0') : hours; + } + } + + hours = Hours; + return hours; +} + +var milliseconds; +var hasRequiredMilliseconds; + +function requireMilliseconds () { + if (hasRequiredMilliseconds) return milliseconds; + hasRequiredMilliseconds = 1; + + const DatePart = requireDatepart(); + + class Milliseconds extends DatePart { + constructor(opts={}) { + super(opts); + } + + up() { + this.date.setMilliseconds(this.date.getMilliseconds() + 1); + } + + down() { + this.date.setMilliseconds(this.date.getMilliseconds() - 1); + } + + setTo(val) { + this.date.setMilliseconds(parseInt(val.substr(-(this.token.length)))); + } + + toString() { + return String(this.date.getMilliseconds()).padStart(4, '0') + .substr(0, this.token.length); + } + } + + milliseconds = Milliseconds; + return milliseconds; +} + +var minutes; +var hasRequiredMinutes; + +function requireMinutes () { + if (hasRequiredMinutes) return minutes; + hasRequiredMinutes = 1; + + const DatePart = requireDatepart(); + + class Minutes extends DatePart { + constructor(opts={}) { + super(opts); + } + + up() { + this.date.setMinutes(this.date.getMinutes() + 1); + } + + down() { + this.date.setMinutes(this.date.getMinutes() - 1); + } + + setTo(val) { + this.date.setMinutes(parseInt(val.substr(-2))); + } + + toString() { + let m = this.date.getMinutes(); + return this.token.length > 1 ? String(m).padStart(2, '0') : m; + } + } + + minutes = Minutes; + return minutes; +} + +var month; +var hasRequiredMonth; + +function requireMonth () { + if (hasRequiredMonth) return month; + hasRequiredMonth = 1; + + const DatePart = requireDatepart(); + + class Month extends DatePart { + constructor(opts={}) { + super(opts); + } + + up() { + this.date.setMonth(this.date.getMonth() + 1); + } + + down() { + this.date.setMonth(this.date.getMonth() - 1); + } + + setTo(val) { + val = parseInt(val.substr(-2)) - 1; + this.date.setMonth(val < 0 ? 0 : val); + } + + toString() { + let month = this.date.getMonth(); + let tl = this.token.length; + return tl === 2 ? String(month + 1).padStart(2, '0') + : tl === 3 ? this.locales.monthsShort[month] + : tl === 4 ? this.locales.months[month] + : String(month + 1); + } + } + + month = Month; + return month; +} + +var seconds; +var hasRequiredSeconds; + +function requireSeconds () { + if (hasRequiredSeconds) return seconds; + hasRequiredSeconds = 1; + + const DatePart = requireDatepart(); + + class Seconds extends DatePart { + constructor(opts={}) { + super(opts); + } + + up() { + this.date.setSeconds(this.date.getSeconds() + 1); + } + + down() { + this.date.setSeconds(this.date.getSeconds() - 1); + } + + setTo(val) { + this.date.setSeconds(parseInt(val.substr(-2))); + } + + toString() { + let s = this.date.getSeconds(); + return this.token.length > 1 ? String(s).padStart(2, '0') : s; + } + } + + seconds = Seconds; + return seconds; +} + +var year; +var hasRequiredYear; + +function requireYear () { + if (hasRequiredYear) return year; + hasRequiredYear = 1; + + const DatePart = requireDatepart(); + + class Year extends DatePart { + constructor(opts={}) { + super(opts); + } + + up() { + this.date.setFullYear(this.date.getFullYear() + 1); + } + + down() { + this.date.setFullYear(this.date.getFullYear() - 1); + } + + setTo(val) { + this.date.setFullYear(val.substr(-4)); + } + + toString() { + let year = String(this.date.getFullYear()).padStart(4, '0'); + return this.token.length === 2 ? year.substr(-2) : year; + } + } + + year = Year; + return year; +} + +var dateparts; +var hasRequiredDateparts; + +function requireDateparts () { + if (hasRequiredDateparts) return dateparts; + hasRequiredDateparts = 1; + + dateparts = { + DatePart: requireDatepart(), + Meridiem: requireMeridiem(), + Day: requireDay(), + Hours: requireHours(), + Milliseconds: requireMilliseconds(), + Minutes: requireMinutes(), + Month: requireMonth(), + Seconds: requireSeconds(), + Year: requireYear(), + }; + return dateparts; +} + +var date; +var hasRequiredDate; + +function requireDate () { + if (hasRequiredDate) return date; + hasRequiredDate = 1; + + const color = requireKleur(); + const Prompt = requirePrompt(); + const { style, clear, figures } = requireUtil$1(); + const { erase, cursor } = requireSrc(); + const { DatePart, Meridiem, Day, Hours, Milliseconds, Minutes, Month, Seconds, Year } = requireDateparts(); + + const regex = /\\(.)|"((?:\\["\\]|[^"])+)"|(D[Do]?|d{3,4}|d)|(M{1,4})|(YY(?:YY)?)|([aA])|([Hh]{1,2})|(m{1,2})|(s{1,2})|(S{1,4})|./g; + const regexGroups = { + 1: ({token}) => token.replace(/\\(.)/g, '$1'), + 2: (opts) => new Day(opts), // Day // TODO + 3: (opts) => new Month(opts), // Month + 4: (opts) => new Year(opts), // Year + 5: (opts) => new Meridiem(opts), // AM/PM // TODO (special) + 6: (opts) => new Hours(opts), // Hours + 7: (opts) => new Minutes(opts), // Minutes + 8: (opts) => new Seconds(opts), // Seconds + 9: (opts) => new Milliseconds(opts), // Fractional seconds + }; + + const dfltLocales = { + months: 'January,February,March,April,May,June,July,August,September,October,November,December'.split(','), + monthsShort: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','), + weekdays: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','), + weekdaysShort: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(',') + }; + + + /** + * DatePrompt Base Element + * @param {Object} opts Options + * @param {String} opts.message Message + * @param {Number} [opts.initial] Index of default value + * @param {String} [opts.mask] The format mask + * @param {object} [opts.locales] The date locales + * @param {String} [opts.error] The error message shown on invalid value + * @param {Function} [opts.validate] Function to validate the submitted value + * @param {Stream} [opts.stdin] The Readable stream to listen to + * @param {Stream} [opts.stdout] The Writable stream to write readline data to + */ + class DatePrompt extends Prompt { + constructor(opts={}) { + super(opts); + this.msg = opts.message; + this.cursor = 0; + this.typed = ''; + this.locales = Object.assign(dfltLocales, opts.locales); + this._date = opts.initial || new Date(); + this.errorMsg = opts.error || 'Please Enter A Valid Value'; + this.validator = opts.validate || (() => true); + this.mask = opts.mask || 'YYYY-MM-DD HH:mm:ss'; + this.clear = clear('', this.out.columns); + this.render(); + } + + get value() { + return this.date + } + + get date() { + return this._date; + } + + set date(date) { + if (date) this._date.setTime(date.getTime()); + } + + set mask(mask) { + let result; + this.parts = []; + while(result = regex.exec(mask)) { + let match = result.shift(); + let idx = result.findIndex(gr => gr != null); + this.parts.push(idx in regexGroups + ? regexGroups[idx]({ token: result[idx] || match, date: this.date, parts: this.parts, locales: this.locales }) + : result[idx] || match); + } + + let parts = this.parts.reduce((arr, i) => { + if (typeof i === 'string' && typeof arr[arr.length - 1] === 'string') + arr[arr.length - 1] += i; + else arr.push(i); + return arr; + }, []); + + this.parts.splice(0); + this.parts.push(...parts); + this.reset(); + } + + moveCursor(n) { + this.typed = ''; + this.cursor = n; + this.fire(); + } + + reset() { + this.moveCursor(this.parts.findIndex(p => p instanceof DatePart)); + this.fire(); + this.render(); + } + + exit() { + this.abort(); + } + + abort() { + this.done = this.aborted = true; + this.error = false; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + + async validate() { + let valid = await this.validator(this.value); + if (typeof valid === 'string') { + this.errorMsg = valid; + valid = false; + } + this.error = !valid; + } + + async submit() { + await this.validate(); + if (this.error) { + this.color = 'red'; + this.fire(); + this.render(); + return; + } + this.done = true; + this.aborted = false; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + + up() { + this.typed = ''; + this.parts[this.cursor].up(); + this.render(); + } + + down() { + this.typed = ''; + this.parts[this.cursor].down(); + this.render(); + } + + left() { + let prev = this.parts[this.cursor].prev(); + if (prev == null) return this.bell(); + this.moveCursor(this.parts.indexOf(prev)); + this.render(); + } + + right() { + let next = this.parts[this.cursor].next(); + if (next == null) return this.bell(); + this.moveCursor(this.parts.indexOf(next)); + this.render(); + } + + next() { + let next = this.parts[this.cursor].next(); + this.moveCursor(next + ? this.parts.indexOf(next) + : this.parts.findIndex((part) => part instanceof DatePart)); + this.render(); + } + + _(c) { + if (/\d/.test(c)) { + this.typed += c; + this.parts[this.cursor].setTo(this.typed); + this.render(); + } + } + + render() { + if (this.closed) return; + if (this.firstRender) this.out.write(cursor.hide); + else this.out.write(clear(this.outputText, this.out.columns)); + super.render(); + + // Print prompt + this.outputText = [ + style.symbol(this.done, this.aborted), + color.bold(this.msg), + style.delimiter(false), + this.parts.reduce((arr, p, idx) => arr.concat(idx === this.cursor && !this.done ? color.cyan().underline(p.toString()) : p), []) + .join('') + ].join(' '); + + // Print error + if (this.error) { + this.outputText += this.errorMsg.split('\n').reduce( + (a, l, i) => a + `\n${i ? ` ` : figures.pointerSmall} ${color.red().italic(l)}`, ``); + } + + this.out.write(erase.line + cursor.to(0) + this.outputText); + } + } + + date = DatePrompt; + return date; +} + +var number; +var hasRequiredNumber; + +function requireNumber () { + if (hasRequiredNumber) return number; + hasRequiredNumber = 1; + const color = requireKleur(); + const Prompt = requirePrompt(); + const { cursor, erase } = requireSrc(); + const { style, figures, clear, lines } = requireUtil$1(); + + const isNumber = /[0-9]/; + const isDef = any => any !== undefined; + const round = (number, precision) => { + let factor = Math.pow(10, precision); + return Math.round(number * factor) / factor; + }; + + /** + * NumberPrompt Base Element + * @param {Object} opts Options + * @param {String} opts.message Message + * @param {String} [opts.style='default'] Render style + * @param {Number} [opts.initial] Default value + * @param {Number} [opts.max=+Infinity] Max value + * @param {Number} [opts.min=-Infinity] Min value + * @param {Boolean} [opts.float=false] Parse input as floats + * @param {Number} [opts.round=2] Round floats to x decimals + * @param {Number} [opts.increment=1] Number to increment by when using arrow-keys + * @param {Function} [opts.validate] Validate function + * @param {Stream} [opts.stdin] The Readable stream to listen to + * @param {Stream} [opts.stdout] The Writable stream to write readline data to + * @param {String} [opts.error] The invalid error label + */ + class NumberPrompt extends Prompt { + constructor(opts={}) { + super(opts); + this.transform = style.render(opts.style); + this.msg = opts.message; + this.initial = isDef(opts.initial) ? opts.initial : ''; + this.float = !!opts.float; + this.round = opts.round || 2; + this.inc = opts.increment || 1; + this.min = isDef(opts.min) ? opts.min : -Infinity; + this.max = isDef(opts.max) ? opts.max : Infinity; + this.errorMsg = opts.error || `Please Enter A Valid Value`; + this.validator = opts.validate || (() => true); + this.color = `cyan`; + this.value = ``; + this.typed = ``; + this.lastHit = 0; + this.render(); + } + + set value(v) { + if (!v && v !== 0) { + this.placeholder = true; + this.rendered = color.gray(this.transform.render(`${this.initial}`)); + this._value = ``; + } else { + this.placeholder = false; + this.rendered = this.transform.render(`${round(v, this.round)}`); + this._value = round(v, this.round); + } + this.fire(); + } + + get value() { + return this._value; + } + + parse(x) { + return this.float ? parseFloat(x) : parseInt(x); + } + + valid(c) { + return c === `-` || c === `.` && this.float || isNumber.test(c) + } + + reset() { + this.typed = ``; + this.value = ``; + this.fire(); + this.render(); + } + + exit() { + this.abort(); + } + + abort() { + let x = this.value; + this.value = x !== `` ? x : this.initial; + this.done = this.aborted = true; + this.error = false; + this.fire(); + this.render(); + this.out.write(`\n`); + this.close(); + } + + async validate() { + let valid = await this.validator(this.value); + if (typeof valid === `string`) { + this.errorMsg = valid; + valid = false; + } + this.error = !valid; + } + + async submit() { + await this.validate(); + if (this.error) { + this.color = `red`; + this.fire(); + this.render(); + return; + } + let x = this.value; + this.value = x !== `` ? x : this.initial; + this.done = true; + this.aborted = false; + this.error = false; + this.fire(); + this.render(); + this.out.write(`\n`); + this.close(); + } + + up() { + this.typed = ``; + if(this.value === '') { + this.value = this.min - this.inc; + } + if (this.value >= this.max) return this.bell(); + this.value += this.inc; + this.color = `cyan`; + this.fire(); + this.render(); + } + + down() { + this.typed = ``; + if(this.value === '') { + this.value = this.min + this.inc; + } + if (this.value <= this.min) return this.bell(); + this.value -= this.inc; + this.color = `cyan`; + this.fire(); + this.render(); + } + + delete() { + let val = this.value.toString(); + if (val.length === 0) return this.bell(); + this.value = this.parse((val = val.slice(0, -1))) || ``; + if (this.value !== '' && this.value < this.min) { + this.value = this.min; + } + this.color = `cyan`; + this.fire(); + this.render(); + } + + next() { + this.value = this.initial; + this.fire(); + this.render(); + } + + _(c, key) { + if (!this.valid(c)) return this.bell(); + + const now = Date.now(); + if (now - this.lastHit > 1000) this.typed = ``; // 1s elapsed + this.typed += c; + this.lastHit = now; + this.color = `cyan`; + + if (c === `.`) return this.fire(); + + this.value = Math.min(this.parse(this.typed), this.max); + if (this.value > this.max) this.value = this.max; + if (this.value < this.min) this.value = this.min; + this.fire(); + this.render(); + } + + render() { + if (this.closed) return; + if (!this.firstRender) { + if (this.outputError) + this.out.write(cursor.down(lines(this.outputError, this.out.columns) - 1) + clear(this.outputError, this.out.columns)); + this.out.write(clear(this.outputText, this.out.columns)); + } + super.render(); + this.outputError = ''; + + // Print prompt + this.outputText = [ + style.symbol(this.done, this.aborted), + color.bold(this.msg), + style.delimiter(this.done), + !this.done || (!this.done && !this.placeholder) + ? color[this.color]().underline(this.rendered) : this.rendered + ].join(` `); + + // Print error + if (this.error) { + this.outputError += this.errorMsg.split(`\n`) + .reduce((a, l, i) => a + `\n${i ? ` ` : figures.pointerSmall} ${color.red().italic(l)}`, ``); + } + + this.out.write(erase.line + cursor.to(0) + this.outputText + cursor.save + this.outputError + cursor.restore); + } + } + + number = NumberPrompt; + return number; +} + +var multiselect; +var hasRequiredMultiselect; + +function requireMultiselect () { + if (hasRequiredMultiselect) return multiselect; + hasRequiredMultiselect = 1; + + const color = requireKleur(); + const { cursor } = requireSrc(); + const Prompt = requirePrompt(); + const { clear, figures, style, wrap, entriesToDisplay } = requireUtil$1(); + + /** + * MultiselectPrompt Base Element + * @param {Object} opts Options + * @param {String} opts.message Message + * @param {Array} opts.choices Array of choice objects + * @param {String} [opts.hint] Hint to display + * @param {String} [opts.warn] Hint shown for disabled choices + * @param {Number} [opts.max] Max choices + * @param {Number} [opts.cursor=0] Cursor start position + * @param {Number} [opts.optionsPerPage=10] Max options to display at once + * @param {Stream} [opts.stdin] The Readable stream to listen to + * @param {Stream} [opts.stdout] The Writable stream to write readline data to + */ + class MultiselectPrompt extends Prompt { + constructor(opts={}) { + super(opts); + this.msg = opts.message; + this.cursor = opts.cursor || 0; + this.scrollIndex = opts.cursor || 0; + this.hint = opts.hint || ''; + this.warn = opts.warn || '- This option is disabled -'; + this.minSelected = opts.min; + this.showMinError = false; + this.maxChoices = opts.max; + this.instructions = opts.instructions; + this.optionsPerPage = opts.optionsPerPage || 10; + this.value = opts.choices.map((ch, idx) => { + if (typeof ch === 'string') + ch = {title: ch, value: idx}; + return { + title: ch && (ch.title || ch.value || ch), + description: ch && ch.description, + value: ch && (ch.value === undefined ? idx : ch.value), + selected: ch && ch.selected, + disabled: ch && ch.disabled + }; + }); + this.clear = clear('', this.out.columns); + if (!opts.overrideRender) { + this.render(); + } + } + + reset() { + this.value.map(v => !v.selected); + this.cursor = 0; + this.fire(); + this.render(); + } + + selected() { + return this.value.filter(v => v.selected); + } + + exit() { + this.abort(); + } + + abort() { + this.done = this.aborted = true; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + + submit() { + const selected = this.value + .filter(e => e.selected); + if (this.minSelected && selected.length < this.minSelected) { + this.showMinError = true; + this.render(); + } else { + this.done = true; + this.aborted = false; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + } + + first() { + this.cursor = 0; + this.render(); + } + + last() { + this.cursor = this.value.length - 1; + this.render(); + } + next() { + this.cursor = (this.cursor + 1) % this.value.length; + this.render(); + } + + up() { + if (this.cursor === 0) { + this.cursor = this.value.length - 1; + } else { + this.cursor--; + } + this.render(); + } + + down() { + if (this.cursor === this.value.length - 1) { + this.cursor = 0; + } else { + this.cursor++; + } + this.render(); + } + + left() { + this.value[this.cursor].selected = false; + this.render(); + } + + right() { + if (this.value.filter(e => e.selected).length >= this.maxChoices) return this.bell(); + this.value[this.cursor].selected = true; + this.render(); + } + + handleSpaceToggle() { + const v = this.value[this.cursor]; + + if (v.selected) { + v.selected = false; + this.render(); + } else if (v.disabled || this.value.filter(e => e.selected).length >= this.maxChoices) { + return this.bell(); + } else { + v.selected = true; + this.render(); + } + } + + toggleAll() { + if (this.maxChoices !== undefined || this.value[this.cursor].disabled) { + return this.bell(); + } + + const newSelected = !this.value[this.cursor].selected; + this.value.filter(v => !v.disabled).forEach(v => v.selected = newSelected); + this.render(); + } + + _(c, key) { + if (c === ' ') { + this.handleSpaceToggle(); + } else if (c === 'a') { + this.toggleAll(); + } else { + return this.bell(); + } + } + + renderInstructions() { + if (this.instructions === undefined || this.instructions) { + if (typeof this.instructions === 'string') { + return this.instructions; + } + return '\nInstructions:\n' + + ` ${figures.arrowUp}/${figures.arrowDown}: Highlight option\n` + + ` ${figures.arrowLeft}/${figures.arrowRight}/[space]: Toggle selection\n` + + (this.maxChoices === undefined ? ` a: Toggle all\n` : '') + + ` enter/return: Complete answer`; + } + return ''; + } + + renderOption(cursor, v, i, arrowIndicator) { + const prefix = (v.selected ? color.green(figures.radioOn) : figures.radioOff) + ' ' + arrowIndicator + ' '; + let title, desc; + + if (v.disabled) { + title = cursor === i ? color.gray().underline(v.title) : color.strikethrough().gray(v.title); + } else { + title = cursor === i ? color.cyan().underline(v.title) : v.title; + if (cursor === i && v.description) { + desc = ` - ${v.description}`; + if (prefix.length + title.length + desc.length >= this.out.columns + || v.description.split(/\r?\n/).length > 1) { + desc = '\n' + wrap(v.description, { margin: prefix.length, width: this.out.columns }); + } + } + } + + return prefix + title + color.gray(desc || ''); + } + + // shared with autocompleteMultiselect + paginateOptions(options) { + if (options.length === 0) { + return color.red('No matches for this query.'); + } + + let { startIndex, endIndex } = entriesToDisplay(this.cursor, options.length, this.optionsPerPage); + let prefix, styledOptions = []; + + for (let i = startIndex; i < endIndex; i++) { + if (i === startIndex && startIndex > 0) { + prefix = figures.arrowUp; + } else if (i === endIndex - 1 && endIndex < options.length) { + prefix = figures.arrowDown; + } else { + prefix = ' '; + } + styledOptions.push(this.renderOption(this.cursor, options[i], i, prefix)); + } + + return '\n' + styledOptions.join('\n'); + } + + // shared with autocomleteMultiselect + renderOptions(options) { + if (!this.done) { + return this.paginateOptions(options); + } + return ''; + } + + renderDoneOrInstructions() { + if (this.done) { + return this.value + .filter(e => e.selected) + .map(v => v.title) + .join(', '); + } + + const output = [color.gray(this.hint), this.renderInstructions()]; + + if (this.value[this.cursor].disabled) { + output.push(color.yellow(this.warn)); + } + return output.join(' '); + } + + render() { + if (this.closed) return; + if (this.firstRender) this.out.write(cursor.hide); + super.render(); + + // print prompt + let prompt = [ + style.symbol(this.done, this.aborted), + color.bold(this.msg), + style.delimiter(false), + this.renderDoneOrInstructions() + ].join(' '); + if (this.showMinError) { + prompt += color.red(`You must select a minimum of ${this.minSelected} choices.`); + this.showMinError = false; + } + prompt += this.renderOptions(this.value); + + this.out.write(this.clear + prompt); + this.clear = clear(prompt, this.out.columns); + } + } + + multiselect = MultiselectPrompt; + return multiselect; +} + +var autocomplete; +var hasRequiredAutocomplete; + +function requireAutocomplete () { + if (hasRequiredAutocomplete) return autocomplete; + hasRequiredAutocomplete = 1; + + const color = requireKleur(); + const Prompt = requirePrompt(); + const { erase, cursor } = requireSrc(); + const { style, clear, figures, wrap, entriesToDisplay } = requireUtil$1(); + + const getVal = (arr, i) => arr[i] && (arr[i].value || arr[i].title || arr[i]); + const getTitle = (arr, i) => arr[i] && (arr[i].title || arr[i].value || arr[i]); + const getIndex = (arr, valOrTitle) => { + const index = arr.findIndex(el => el.value === valOrTitle || el.title === valOrTitle); + return index > -1 ? index : undefined; + }; + + /** + * TextPrompt Base Element + * @param {Object} opts Options + * @param {String} opts.message Message + * @param {Array} opts.choices Array of auto-complete choices objects + * @param {Function} [opts.suggest] Filter function. Defaults to sort by title + * @param {Number} [opts.limit=10] Max number of results to show + * @param {Number} [opts.cursor=0] Cursor start position + * @param {String} [opts.style='default'] Render style + * @param {String} [opts.fallback] Fallback message - initial to default value + * @param {String} [opts.initial] Index of the default value + * @param {Boolean} [opts.clearFirst] The first ESCAPE keypress will clear the input + * @param {Stream} [opts.stdin] The Readable stream to listen to + * @param {Stream} [opts.stdout] The Writable stream to write readline data to + * @param {String} [opts.noMatches] The no matches found label + */ + class AutocompletePrompt extends Prompt { + constructor(opts={}) { + super(opts); + this.msg = opts.message; + this.suggest = opts.suggest; + this.choices = opts.choices; + this.initial = typeof opts.initial === 'number' + ? opts.initial + : getIndex(opts.choices, opts.initial); + this.select = this.initial || opts.cursor || 0; + this.i18n = { noMatches: opts.noMatches || 'no matches found' }; + this.fallback = opts.fallback || this.initial; + this.clearFirst = opts.clearFirst || false; + this.suggestions = []; + this.input = ''; + this.limit = opts.limit || 10; + this.cursor = 0; + this.transform = style.render(opts.style); + this.scale = this.transform.scale; + this.render = this.render.bind(this); + this.complete = this.complete.bind(this); + this.clear = clear('', this.out.columns); + this.complete(this.render); + this.render(); + } + + set fallback(fb) { + this._fb = Number.isSafeInteger(parseInt(fb)) ? parseInt(fb) : fb; + } + + get fallback() { + let choice; + if (typeof this._fb === 'number') + choice = this.choices[this._fb]; + else if (typeof this._fb === 'string') + choice = { title: this._fb }; + return choice || this._fb || { title: this.i18n.noMatches }; + } + + moveSelect(i) { + this.select = i; + if (this.suggestions.length > 0) + this.value = getVal(this.suggestions, i); + else this.value = this.fallback.value; + this.fire(); + } + + async complete(cb) { + const p = (this.completing = this.suggest(this.input, this.choices)); + const suggestions = await p; + + if (this.completing !== p) return; + this.suggestions = suggestions + .map((s, i, arr) => ({ title: getTitle(arr, i), value: getVal(arr, i), description: s.description })); + this.completing = false; + const l = Math.max(suggestions.length - 1, 0); + this.moveSelect(Math.min(l, this.select)); + + cb && cb(); + } + + reset() { + this.input = ''; + this.complete(() => { + this.moveSelect(this.initial !== void 0 ? this.initial : 0); + this.render(); + }); + this.render(); + } + + exit() { + if (this.clearFirst && this.input.length > 0) { + this.reset(); + } else { + this.done = this.exited = true; + this.aborted = false; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + } + + abort() { + this.done = this.aborted = true; + this.exited = false; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + + submit() { + this.done = true; + this.aborted = this.exited = false; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + + _(c, key) { + let s1 = this.input.slice(0, this.cursor); + let s2 = this.input.slice(this.cursor); + this.input = `${s1}${c}${s2}`; + this.cursor = s1.length+1; + this.complete(this.render); + this.render(); + } + + delete() { + if (this.cursor === 0) return this.bell(); + let s1 = this.input.slice(0, this.cursor-1); + let s2 = this.input.slice(this.cursor); + this.input = `${s1}${s2}`; + this.complete(this.render); + this.cursor = this.cursor-1; + this.render(); + } + + deleteForward() { + if(this.cursor*this.scale >= this.rendered.length) return this.bell(); + let s1 = this.input.slice(0, this.cursor); + let s2 = this.input.slice(this.cursor+1); + this.input = `${s1}${s2}`; + this.complete(this.render); + this.render(); + } + + first() { + this.moveSelect(0); + this.render(); + } + + last() { + this.moveSelect(this.suggestions.length - 1); + this.render(); + } + + up() { + if (this.select === 0) { + this.moveSelect(this.suggestions.length - 1); + } else { + this.moveSelect(this.select - 1); + } + this.render(); + } + + down() { + if (this.select === this.suggestions.length - 1) { + this.moveSelect(0); + } else { + this.moveSelect(this.select + 1); + } + this.render(); + } + + next() { + if (this.select === this.suggestions.length - 1) { + this.moveSelect(0); + } else this.moveSelect(this.select + 1); + this.render(); + } + + nextPage() { + this.moveSelect(Math.min(this.select + this.limit, this.suggestions.length - 1)); + this.render(); + } + + prevPage() { + this.moveSelect(Math.max(this.select - this.limit, 0)); + this.render(); + } + + left() { + if (this.cursor <= 0) return this.bell(); + this.cursor = this.cursor-1; + this.render(); + } + + right() { + if (this.cursor*this.scale >= this.rendered.length) return this.bell(); + this.cursor = this.cursor+1; + this.render(); + } + + renderOption(v, hovered, isStart, isEnd) { + let desc; + let prefix = isStart ? figures.arrowUp : isEnd ? figures.arrowDown : ' '; + let title = hovered ? color.cyan().underline(v.title) : v.title; + prefix = (hovered ? color.cyan(figures.pointer) + ' ' : ' ') + prefix; + if (v.description) { + desc = ` - ${v.description}`; + if (prefix.length + title.length + desc.length >= this.out.columns + || v.description.split(/\r?\n/).length > 1) { + desc = '\n' + wrap(v.description, { margin: 3, width: this.out.columns }); + } + } + return prefix + ' ' + title + color.gray(desc || ''); + } + + render() { + if (this.closed) return; + if (this.firstRender) this.out.write(cursor.hide); + else this.out.write(clear(this.outputText, this.out.columns)); + super.render(); + + let { startIndex, endIndex } = entriesToDisplay(this.select, this.choices.length, this.limit); + + this.outputText = [ + style.symbol(this.done, this.aborted, this.exited), + color.bold(this.msg), + style.delimiter(this.completing), + this.done && this.suggestions[this.select] + ? this.suggestions[this.select].title + : this.rendered = this.transform.render(this.input) + ].join(' '); + + if (!this.done) { + const suggestions = this.suggestions + .slice(startIndex, endIndex) + .map((item, i) => this.renderOption(item, + this.select === i + startIndex, + i === 0 && startIndex > 0, + i + startIndex === endIndex - 1 && endIndex < this.choices.length)) + .join('\n'); + this.outputText += `\n` + (suggestions || color.gray(this.fallback.title)); + } + + this.out.write(erase.line + cursor.to(0) + this.outputText); + } + } + + autocomplete = AutocompletePrompt; + return autocomplete; +} + +var autocompleteMultiselect; +var hasRequiredAutocompleteMultiselect; + +function requireAutocompleteMultiselect () { + if (hasRequiredAutocompleteMultiselect) return autocompleteMultiselect; + hasRequiredAutocompleteMultiselect = 1; + + const color = requireKleur(); + const { cursor } = requireSrc(); + const MultiselectPrompt = requireMultiselect(); + const { clear, style, figures } = requireUtil$1(); + /** + * MultiselectPrompt Base Element + * @param {Object} opts Options + * @param {String} opts.message Message + * @param {Array} opts.choices Array of choice objects + * @param {String} [opts.hint] Hint to display + * @param {String} [opts.warn] Hint shown for disabled choices + * @param {Number} [opts.max] Max choices + * @param {Number} [opts.cursor=0] Cursor start position + * @param {Stream} [opts.stdin] The Readable stream to listen to + * @param {Stream} [opts.stdout] The Writable stream to write readline data to + */ + class AutocompleteMultiselectPrompt extends MultiselectPrompt { + constructor(opts={}) { + opts.overrideRender = true; + super(opts); + this.inputValue = ''; + this.clear = clear('', this.out.columns); + this.filteredOptions = this.value; + this.render(); + } + + last() { + this.cursor = this.filteredOptions.length - 1; + this.render(); + } + next() { + this.cursor = (this.cursor + 1) % this.filteredOptions.length; + this.render(); + } + + up() { + if (this.cursor === 0) { + this.cursor = this.filteredOptions.length - 1; + } else { + this.cursor--; + } + this.render(); + } + + down() { + if (this.cursor === this.filteredOptions.length - 1) { + this.cursor = 0; + } else { + this.cursor++; + } + this.render(); + } + + left() { + this.filteredOptions[this.cursor].selected = false; + this.render(); + } + + right() { + if (this.value.filter(e => e.selected).length >= this.maxChoices) return this.bell(); + this.filteredOptions[this.cursor].selected = true; + this.render(); + } + + delete() { + if (this.inputValue.length) { + this.inputValue = this.inputValue.substr(0, this.inputValue.length - 1); + this.updateFilteredOptions(); + } + } + + updateFilteredOptions() { + const currentHighlight = this.filteredOptions[this.cursor]; + this.filteredOptions = this.value + .filter(v => { + if (this.inputValue) { + if (typeof v.title === 'string') { + if (v.title.toLowerCase().includes(this.inputValue.toLowerCase())) { + return true; + } + } + if (typeof v.value === 'string') { + if (v.value.toLowerCase().includes(this.inputValue.toLowerCase())) { + return true; + } + } + return false; + } + return true; + }); + const newHighlightIndex = this.filteredOptions.findIndex(v => v === currentHighlight); + this.cursor = newHighlightIndex < 0 ? 0 : newHighlightIndex; + this.render(); + } + + handleSpaceToggle() { + const v = this.filteredOptions[this.cursor]; + + if (v.selected) { + v.selected = false; + this.render(); + } else if (v.disabled || this.value.filter(e => e.selected).length >= this.maxChoices) { + return this.bell(); + } else { + v.selected = true; + this.render(); + } + } + + handleInputChange(c) { + this.inputValue = this.inputValue + c; + this.updateFilteredOptions(); + } + + _(c, key) { + if (c === ' ') { + this.handleSpaceToggle(); + } else { + this.handleInputChange(c); + } + } + + renderInstructions() { + if (this.instructions === undefined || this.instructions) { + if (typeof this.instructions === 'string') { + return this.instructions; + } + return ` +Instructions: + ${figures.arrowUp}/${figures.arrowDown}: Highlight option + ${figures.arrowLeft}/${figures.arrowRight}/[space]: Toggle selection + [a,b,c]/delete: Filter choices + enter/return: Complete answer +`; + } + return ''; + } + + renderCurrentInput() { + return ` +Filtered results for: ${this.inputValue ? this.inputValue : color.gray('Enter something to filter')}\n`; + } + + renderOption(cursor, v, i) { + let title; + if (v.disabled) title = cursor === i ? color.gray().underline(v.title) : color.strikethrough().gray(v.title); + else title = cursor === i ? color.cyan().underline(v.title) : v.title; + return (v.selected ? color.green(figures.radioOn) : figures.radioOff) + ' ' + title + } + + renderDoneOrInstructions() { + if (this.done) { + return this.value + .filter(e => e.selected) + .map(v => v.title) + .join(', '); + } + + const output = [color.gray(this.hint), this.renderInstructions(), this.renderCurrentInput()]; + + if (this.filteredOptions.length && this.filteredOptions[this.cursor].disabled) { + output.push(color.yellow(this.warn)); + } + return output.join(' '); + } + + render() { + if (this.closed) return; + if (this.firstRender) this.out.write(cursor.hide); + super.render(); + + // print prompt + + let prompt = [ + style.symbol(this.done, this.aborted), + color.bold(this.msg), + style.delimiter(false), + this.renderDoneOrInstructions() + ].join(' '); + + if (this.showMinError) { + prompt += color.red(`You must select a minimum of ${this.minSelected} choices.`); + this.showMinError = false; + } + prompt += this.renderOptions(this.filteredOptions); + + this.out.write(this.clear + prompt); + this.clear = clear(prompt, this.out.columns); + } + } + + autocompleteMultiselect = AutocompleteMultiselectPrompt; + return autocompleteMultiselect; +} + +var confirm; +var hasRequiredConfirm; + +function requireConfirm () { + if (hasRequiredConfirm) return confirm; + hasRequiredConfirm = 1; + const color = requireKleur(); + const Prompt = requirePrompt(); + const { style, clear } = requireUtil$1(); + const { erase, cursor } = requireSrc(); + + /** + * ConfirmPrompt Base Element + * @param {Object} opts Options + * @param {String} opts.message Message + * @param {Boolean} [opts.initial] Default value (true/false) + * @param {Stream} [opts.stdin] The Readable stream to listen to + * @param {Stream} [opts.stdout] The Writable stream to write readline data to + * @param {String} [opts.yes] The "Yes" label + * @param {String} [opts.yesOption] The "Yes" option when choosing between yes/no + * @param {String} [opts.no] The "No" label + * @param {String} [opts.noOption] The "No" option when choosing between yes/no + */ + class ConfirmPrompt extends Prompt { + constructor(opts={}) { + super(opts); + this.msg = opts.message; + this.value = opts.initial; + this.initialValue = !!opts.initial; + this.yesMsg = opts.yes || 'yes'; + this.yesOption = opts.yesOption || '(Y/n)'; + this.noMsg = opts.no || 'no'; + this.noOption = opts.noOption || '(y/N)'; + this.render(); + } + + reset() { + this.value = this.initialValue; + this.fire(); + this.render(); + } + + exit() { + this.abort(); + } + + abort() { + this.done = this.aborted = true; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + + submit() { + this.value = this.value || false; + this.done = true; + this.aborted = false; + this.fire(); + this.render(); + this.out.write('\n'); + this.close(); + } + + _(c, key) { + if (c.toLowerCase() === 'y') { + this.value = true; + return this.submit(); + } + if (c.toLowerCase() === 'n') { + this.value = false; + return this.submit(); + } + return this.bell(); + } + + render() { + if (this.closed) return; + if (this.firstRender) this.out.write(cursor.hide); + else this.out.write(clear(this.outputText, this.out.columns)); + super.render(); + + this.outputText = [ + style.symbol(this.done, this.aborted), + color.bold(this.msg), + style.delimiter(this.done), + this.done ? (this.value ? this.yesMsg : this.noMsg) + : color.gray(this.initialValue ? this.yesOption : this.noOption) + ].join(' '); + + this.out.write(erase.line + cursor.to(0) + this.outputText); + } + } + + confirm = ConfirmPrompt; + return confirm; +} + +var elements; +var hasRequiredElements; + +function requireElements () { + if (hasRequiredElements) return elements; + hasRequiredElements = 1; + + elements = { + TextPrompt: requireText(), + SelectPrompt: requireSelect(), + TogglePrompt: requireToggle(), + DatePrompt: requireDate(), + NumberPrompt: requireNumber(), + MultiselectPrompt: requireMultiselect(), + AutocompletePrompt: requireAutocomplete(), + AutocompleteMultiselectPrompt: requireAutocompleteMultiselect(), + ConfirmPrompt: requireConfirm() + }; + return elements; +} + +var hasRequiredPrompts; + +function requirePrompts () { + if (hasRequiredPrompts) return prompts$2; + hasRequiredPrompts = 1; + (function (exports) { + const $ = exports; + const el = requireElements(); + const noop = v => v; + + function toPrompt(type, args, opts={}) { + return new Promise((res, rej) => { + const p = new el[type](args); + const onAbort = opts.onAbort || noop; + const onSubmit = opts.onSubmit || noop; + const onExit = opts.onExit || noop; + p.on('state', args.onState || noop); + p.on('submit', x => res(onSubmit(x))); + p.on('exit', x => res(onExit(x))); + p.on('abort', x => rej(onAbort(x))); + }); + } + + /** + * Text prompt + * @param {string} args.message Prompt message to display + * @param {string} [args.initial] Default string value + * @param {string} [args.style="default"] Render style ('default', 'password', 'invisible') + * @param {function} [args.onState] On state change callback + * @param {function} [args.validate] Function to validate user input + * @param {Stream} [args.stdin] The Readable stream to listen to + * @param {Stream} [args.stdout] The Writable stream to write readline data to + * @returns {Promise} Promise with user input + */ + $.text = args => toPrompt('TextPrompt', args); + + /** + * Password prompt with masked input + * @param {string} args.message Prompt message to display + * @param {string} [args.initial] Default string value + * @param {function} [args.onState] On state change callback + * @param {function} [args.validate] Function to validate user input + * @param {Stream} [args.stdin] The Readable stream to listen to + * @param {Stream} [args.stdout] The Writable stream to write readline data to + * @returns {Promise} Promise with user input + */ + $.password = args => { + args.style = 'password'; + return $.text(args); + }; + + /** + * Prompt where input is invisible, like sudo + * @param {string} args.message Prompt message to display + * @param {string} [args.initial] Default string value + * @param {function} [args.onState] On state change callback + * @param {function} [args.validate] Function to validate user input + * @param {Stream} [args.stdin] The Readable stream to listen to + * @param {Stream} [args.stdout] The Writable stream to write readline data to + * @returns {Promise} Promise with user input + */ + $.invisible = args => { + args.style = 'invisible'; + return $.text(args); + }; + + /** + * Number prompt + * @param {string} args.message Prompt message to display + * @param {number} args.initial Default number value + * @param {function} [args.onState] On state change callback + * @param {number} [args.max] Max value + * @param {number} [args.min] Min value + * @param {string} [args.style="default"] Render style ('default', 'password', 'invisible') + * @param {Boolean} [opts.float=false] Parse input as floats + * @param {Number} [opts.round=2] Round floats to x decimals + * @param {Number} [opts.increment=1] Number to increment by when using arrow-keys + * @param {function} [args.validate] Function to validate user input + * @param {Stream} [args.stdin] The Readable stream to listen to + * @param {Stream} [args.stdout] The Writable stream to write readline data to + * @returns {Promise} Promise with user input + */ + $.number = args => toPrompt('NumberPrompt', args); + + /** + * Date prompt + * @param {string} args.message Prompt message to display + * @param {number} args.initial Default number value + * @param {function} [args.onState] On state change callback + * @param {number} [args.max] Max value + * @param {number} [args.min] Min value + * @param {string} [args.style="default"] Render style ('default', 'password', 'invisible') + * @param {Boolean} [opts.float=false] Parse input as floats + * @param {Number} [opts.round=2] Round floats to x decimals + * @param {Number} [opts.increment=1] Number to increment by when using arrow-keys + * @param {function} [args.validate] Function to validate user input + * @param {Stream} [args.stdin] The Readable stream to listen to + * @param {Stream} [args.stdout] The Writable stream to write readline data to + * @returns {Promise} Promise with user input + */ + $.date = args => toPrompt('DatePrompt', args); + + /** + * Classic yes/no prompt + * @param {string} args.message Prompt message to display + * @param {boolean} [args.initial=false] Default value + * @param {function} [args.onState] On state change callback + * @param {Stream} [args.stdin] The Readable stream to listen to + * @param {Stream} [args.stdout] The Writable stream to write readline data to + * @returns {Promise} Promise with user input + */ + $.confirm = args => toPrompt('ConfirmPrompt', args); + + /** + * List prompt, split intput string by `seperator` + * @param {string} args.message Prompt message to display + * @param {string} [args.initial] Default string value + * @param {string} [args.style="default"] Render style ('default', 'password', 'invisible') + * @param {string} [args.separator] String separator + * @param {function} [args.onState] On state change callback + * @param {Stream} [args.stdin] The Readable stream to listen to + * @param {Stream} [args.stdout] The Writable stream to write readline data to + * @returns {Promise} Promise with user input, in form of an `Array` + */ + $.list = args => { + const sep = args.separator || ','; + return toPrompt('TextPrompt', args, { + onSubmit: str => str.split(sep).map(s => s.trim()) + }); + }; + + /** + * Toggle/switch prompt + * @param {string} args.message Prompt message to display + * @param {boolean} [args.initial=false] Default value + * @param {string} [args.active="on"] Text for `active` state + * @param {string} [args.inactive="off"] Text for `inactive` state + * @param {function} [args.onState] On state change callback + * @param {Stream} [args.stdin] The Readable stream to listen to + * @param {Stream} [args.stdout] The Writable stream to write readline data to + * @returns {Promise} Promise with user input + */ + $.toggle = args => toPrompt('TogglePrompt', args); + + /** + * Interactive select prompt + * @param {string} args.message Prompt message to display + * @param {Array} args.choices Array of choices objects `[{ title, value }, ...]` + * @param {number} [args.initial] Index of default value + * @param {String} [args.hint] Hint to display + * @param {function} [args.onState] On state change callback + * @param {Stream} [args.stdin] The Readable stream to listen to + * @param {Stream} [args.stdout] The Writable stream to write readline data to + * @returns {Promise} Promise with user input + */ + $.select = args => toPrompt('SelectPrompt', args); + + /** + * Interactive multi-select / autocompleteMultiselect prompt + * @param {string} args.message Prompt message to display + * @param {Array} args.choices Array of choices objects `[{ title, value, [selected] }, ...]` + * @param {number} [args.max] Max select + * @param {string} [args.hint] Hint to display user + * @param {Number} [args.cursor=0] Cursor start position + * @param {function} [args.onState] On state change callback + * @param {Stream} [args.stdin] The Readable stream to listen to + * @param {Stream} [args.stdout] The Writable stream to write readline data to + * @returns {Promise} Promise with user input + */ + $.multiselect = args => { + args.choices = [].concat(args.choices || []); + const toSelected = items => items.filter(item => item.selected).map(item => item.value); + return toPrompt('MultiselectPrompt', args, { + onAbort: toSelected, + onSubmit: toSelected + }); + }; + + $.autocompleteMultiselect = args => { + args.choices = [].concat(args.choices || []); + const toSelected = items => items.filter(item => item.selected).map(item => item.value); + return toPrompt('AutocompleteMultiselectPrompt', args, { + onAbort: toSelected, + onSubmit: toSelected + }); + }; + + const byTitle = (input, choices) => Promise.resolve( + choices.filter(item => item.title.slice(0, input.length).toLowerCase() === input.toLowerCase()) + ); + + /** + * Interactive auto-complete prompt + * @param {string} args.message Prompt message to display + * @param {Array} args.choices Array of auto-complete choices objects `[{ title, value }, ...]` + * @param {Function} [args.suggest] Function to filter results based on user input. Defaults to sort by `title` + * @param {number} [args.limit=10] Max number of results to show + * @param {string} [args.style="default"] Render style ('default', 'password', 'invisible') + * @param {String} [args.initial] Index of the default value + * @param {boolean} [opts.clearFirst] The first ESCAPE keypress will clear the input + * @param {String} [args.fallback] Fallback message - defaults to initial value + * @param {function} [args.onState] On state change callback + * @param {Stream} [args.stdin] The Readable stream to listen to + * @param {Stream} [args.stdout] The Writable stream to write readline data to + * @returns {Promise} Promise with user input + */ + $.autocomplete = args => { + args.suggest = args.suggest || byTitle; + args.choices = [].concat(args.choices || []); + return toPrompt('AutocompletePrompt', args); + }; + } (prompts$2)); + return prompts$2; +} + +var lib$i; +var hasRequiredLib$3; + +function requireLib$3 () { + if (hasRequiredLib$3) return lib$i; + hasRequiredLib$3 = 1; + + const prompts = requirePrompts(); + + const passOn = ['suggest', 'format', 'onState', 'validate', 'onRender', 'type']; + const noop = () => {}; + + /** + * Prompt for a series of questions + * @param {Array|Object} questions Single question object or Array of question objects + * @param {Function} [onSubmit] Callback function called on prompt submit + * @param {Function} [onCancel] Callback function called on cancel/abort + * @returns {Object} Object with values from user input + */ + async function prompt(questions=[], { onSubmit=noop, onCancel=noop }={}) { + const answers = {}; + const override = prompt._override || {}; + questions = [].concat(questions); + let answer, question, quit, name, type, lastPrompt; + + const getFormattedAnswer = async (question, answer, skipValidation = false) => { + if (!skipValidation && question.validate && question.validate(answer) !== true) { + return; + } + return question.format ? await question.format(answer, answers) : answer + }; + + for (question of questions) { + ({ name, type } = question); + + // evaluate type first and skip if type is a falsy value + if (typeof type === 'function') { + type = await type(answer, { ...answers }, question); + question['type'] = type; + } + if (!type) continue; + + // if property is a function, invoke it unless it's a special function + for (let key in question) { + if (passOn.includes(key)) continue; + let value = question[key]; + question[key] = typeof value === 'function' ? await value(answer, { ...answers }, lastPrompt) : value; + } + + lastPrompt = question; + + if (typeof question.message !== 'string') { + throw new Error('prompt message is required'); + } + + // update vars in case they changed + ({ name, type } = question); + + if (prompts[type] === void 0) { + throw new Error(`prompt type (${type}) is not defined`); + } + + if (override[question.name] !== undefined) { + answer = await getFormattedAnswer(question, override[question.name]); + if (answer !== undefined) { + answers[name] = answer; + continue; + } + } + + try { + // Get the injected answer if there is one or prompt the user + answer = prompt._injected ? getInjectedAnswer(prompt._injected, question.initial) : await prompts[type](question); + answers[name] = answer = await getFormattedAnswer(question, answer, true); + quit = await onSubmit(question, answer, answers); + } catch (err) { + quit = !(await onCancel(question, answers)); + } + + if (quit) return answers; + } + + return answers; + } + + function getInjectedAnswer(injected, deafultValue) { + const answer = injected.shift(); + if (answer instanceof Error) { + throw answer; + } + + return (answer === undefined) ? deafultValue : answer; + } + + function inject(answers) { + prompt._injected = (prompt._injected || []).concat(answers); + } + + function override(answers) { + prompt._override = Object.assign({}, answers); + } + + lib$i = Object.assign(prompt, { prompt, prompts, inject, override }); + return lib$i; +} + +function isNodeLT(tar) { + tar = (Array.isArray(tar) ? tar : tar.split('.')).map(Number); + let i=0, src=process.versions.node.split('.').map(Number); + for (; i < tar.length; i++) { + if (src[i] > tar[i]) return false; + if (tar[i] > src[i]) return true; + } + return false; +} + +var prompts = + isNodeLT('8.6.0') + ? requireDist() + : requireLib$3(); + +var prompts$1 = /*@__PURE__*/getDefaultExportFromCjs(prompts); + +/** + * The `prompts` library doesn't always interpret CTRL+C and release the terminal back to the user + * so we need handle this ourselves. This function is just a simple overload of the main `prompts` + * import that we use. + * + * @see {@link https://github.com/terkelg/prompts/issues/252} + */ +async function promptTerminal(questions, options) { + /** + * The CTRL+C handler discussed above. + * @see {@link https://github.com/terkelg/prompts#optionsoncancel} + */ + const onCancel = () => { + process.stdout.write('\n'); + process.stdout.write('Thanks for using rdme! See you soon ✌️'); + process.stdout.write('\n\n'); + process.exit(1); + }; + /** + * Runs a check before every prompt renders to make sure that + * prompt is not being run in a CI environment. + */ + function onRender() { + if (isCI()) { + process.stdout.write('\n'); + process.stdout.write('Yikes! Looks like we were about to prompt you for something in a CI environment. Are you missing an argument?'); + process.stdout.write('\n\n'); + process.stdout.write('Try running `rdme --help` or get in touch at support@readme.io.'); + process.stdout.write('\n\n'); + process.exit(1); + } + } + if (Array.isArray(questions)) { + // eslint-disable-next-line no-param-reassign + questions = questions.map(question => ({ onRender, ...question })); + } + else { + // eslint-disable-next-line no-param-reassign + questions.onRender = onRender; + } + return prompts$1(questions, { onCancel, ...options }); +} + +var mimeTypes = {}; + +var require$$0$4 = { + "application/1d-interleaved-parityfec": { + source: "iana" +}, + "application/3gpdash-qoe-report+xml": { + source: "iana", + charset: "UTF-8", + compressible: true +}, + "application/3gpp-ims+xml": { + source: "iana", + compressible: true +}, + "application/3gpphal+json": { + source: "iana", + compressible: true +}, + "application/3gpphalforms+json": { + source: "iana", + compressible: true +}, + "application/a2l": { + source: "iana" +}, + "application/ace+cbor": { + source: "iana" +}, + "application/activemessage": { + source: "iana" +}, + "application/activity+json": { + source: "iana", + compressible: true +}, + "application/alto-costmap+json": { + source: "iana", + compressible: true +}, + "application/alto-costmapfilter+json": { + source: "iana", + compressible: true +}, + "application/alto-directory+json": { + source: "iana", + compressible: true +}, + "application/alto-endpointcost+json": { + source: "iana", + compressible: true +}, + "application/alto-endpointcostparams+json": { + source: "iana", + compressible: true +}, + "application/alto-endpointprop+json": { + source: "iana", + compressible: true +}, + "application/alto-endpointpropparams+json": { + source: "iana", + compressible: true +}, + "application/alto-error+json": { + source: "iana", + compressible: true +}, + "application/alto-networkmap+json": { + source: "iana", + compressible: true +}, + "application/alto-networkmapfilter+json": { + source: "iana", + compressible: true +}, + "application/alto-updatestreamcontrol+json": { + source: "iana", + compressible: true +}, + "application/alto-updatestreamparams+json": { + source: "iana", + compressible: true +}, + "application/aml": { + source: "iana" +}, + "application/andrew-inset": { + source: "iana", + extensions: [ + "ez" + ] +}, + "application/applefile": { + source: "iana" +}, + "application/applixware": { + source: "apache", + extensions: [ + "aw" + ] +}, + "application/at+jwt": { + source: "iana" +}, + "application/atf": { + source: "iana" +}, + "application/atfx": { + source: "iana" +}, + "application/atom+xml": { + source: "iana", + compressible: true, + extensions: [ + "atom" + ] +}, + "application/atomcat+xml": { + source: "iana", + compressible: true, + extensions: [ + "atomcat" + ] +}, + "application/atomdeleted+xml": { + source: "iana", + compressible: true, + extensions: [ + "atomdeleted" + ] +}, + "application/atomicmail": { + source: "iana" +}, + "application/atomsvc+xml": { + source: "iana", + compressible: true, + extensions: [ + "atomsvc" + ] +}, + "application/atsc-dwd+xml": { + source: "iana", + compressible: true, + extensions: [ + "dwd" + ] +}, + "application/atsc-dynamic-event-message": { + source: "iana" +}, + "application/atsc-held+xml": { + source: "iana", + compressible: true, + extensions: [ + "held" + ] +}, + "application/atsc-rdt+json": { + source: "iana", + compressible: true +}, + "application/atsc-rsat+xml": { + source: "iana", + compressible: true, + extensions: [ + "rsat" + ] +}, + "application/atxml": { + source: "iana" +}, + "application/auth-policy+xml": { + source: "iana", + compressible: true +}, + "application/bacnet-xdd+zip": { + source: "iana", + compressible: false +}, + "application/batch-smtp": { + source: "iana" +}, + "application/bdoc": { + compressible: false, + extensions: [ + "bdoc" + ] +}, + "application/beep+xml": { + source: "iana", + charset: "UTF-8", + compressible: true +}, + "application/calendar+json": { + source: "iana", + compressible: true +}, + "application/calendar+xml": { + source: "iana", + compressible: true, + extensions: [ + "xcs" + ] +}, + "application/call-completion": { + source: "iana" +}, + "application/cals-1840": { + source: "iana" +}, + "application/captive+json": { + source: "iana", + compressible: true +}, + "application/cbor": { + source: "iana" +}, + "application/cbor-seq": { + source: "iana" +}, + "application/cccex": { + source: "iana" +}, + "application/ccmp+xml": { + source: "iana", + compressible: true +}, + "application/ccxml+xml": { + source: "iana", + compressible: true, + extensions: [ + "ccxml" + ] +}, + "application/cdfx+xml": { + source: "iana", + compressible: true, + extensions: [ + "cdfx" + ] +}, + "application/cdmi-capability": { + source: "iana", + extensions: [ + "cdmia" + ] +}, + "application/cdmi-container": { + source: "iana", + extensions: [ + "cdmic" + ] +}, + "application/cdmi-domain": { + source: "iana", + extensions: [ + "cdmid" + ] +}, + "application/cdmi-object": { + source: "iana", + extensions: [ + "cdmio" + ] +}, + "application/cdmi-queue": { + source: "iana", + extensions: [ + "cdmiq" + ] +}, + "application/cdni": { + source: "iana" +}, + "application/cea": { + source: "iana" +}, + "application/cea-2018+xml": { + source: "iana", + compressible: true +}, + "application/cellml+xml": { + source: "iana", + compressible: true +}, + "application/cfw": { + source: "iana" +}, + "application/city+json": { + source: "iana", + compressible: true +}, + "application/clr": { + source: "iana" +}, + "application/clue+xml": { + source: "iana", + compressible: true +}, + "application/clue_info+xml": { + source: "iana", + compressible: true +}, + "application/cms": { + source: "iana" +}, + "application/cnrp+xml": { + source: "iana", + compressible: true +}, + "application/coap-group+json": { + source: "iana", + compressible: true +}, + "application/coap-payload": { + source: "iana" +}, + "application/commonground": { + source: "iana" +}, + "application/conference-info+xml": { + source: "iana", + compressible: true +}, + "application/cose": { + source: "iana" +}, + "application/cose-key": { + source: "iana" +}, + "application/cose-key-set": { + source: "iana" +}, + "application/cpl+xml": { + source: "iana", + compressible: true, + extensions: [ + "cpl" + ] +}, + "application/csrattrs": { + source: "iana" +}, + "application/csta+xml": { + source: "iana", + compressible: true +}, + "application/cstadata+xml": { + source: "iana", + compressible: true +}, + "application/csvm+json": { + source: "iana", + compressible: true +}, + "application/cu-seeme": { + source: "apache", + extensions: [ + "cu" + ] +}, + "application/cwt": { + source: "iana" +}, + "application/cybercash": { + source: "iana" +}, + "application/dart": { + compressible: true +}, + "application/dash+xml": { + source: "iana", + compressible: true, + extensions: [ + "mpd" + ] +}, + "application/dash-patch+xml": { + source: "iana", + compressible: true, + extensions: [ + "mpp" + ] +}, + "application/dashdelta": { + source: "iana" +}, + "application/davmount+xml": { + source: "iana", + compressible: true, + extensions: [ + "davmount" + ] +}, + "application/dca-rft": { + source: "iana" +}, + "application/dcd": { + source: "iana" +}, + "application/dec-dx": { + source: "iana" +}, + "application/dialog-info+xml": { + source: "iana", + compressible: true +}, + "application/dicom": { + source: "iana" +}, + "application/dicom+json": { + source: "iana", + compressible: true +}, + "application/dicom+xml": { + source: "iana", + compressible: true +}, + "application/dii": { + source: "iana" +}, + "application/dit": { + source: "iana" +}, + "application/dns": { + source: "iana" +}, + "application/dns+json": { + source: "iana", + compressible: true +}, + "application/dns-message": { + source: "iana" +}, + "application/docbook+xml": { + source: "apache", + compressible: true, + extensions: [ + "dbk" + ] +}, + "application/dots+cbor": { + source: "iana" +}, + "application/dskpp+xml": { + source: "iana", + compressible: true +}, + "application/dssc+der": { + source: "iana", + extensions: [ + "dssc" + ] +}, + "application/dssc+xml": { + source: "iana", + compressible: true, + extensions: [ + "xdssc" + ] +}, + "application/dvcs": { + source: "iana" +}, + "application/ecmascript": { + source: "iana", + compressible: true, + extensions: [ + "es", + "ecma" + ] +}, + "application/edi-consent": { + source: "iana" +}, + "application/edi-x12": { + source: "iana", + compressible: false +}, + "application/edifact": { + source: "iana", + compressible: false +}, + "application/efi": { + source: "iana" +}, + "application/elm+json": { + source: "iana", + charset: "UTF-8", + compressible: true +}, + "application/elm+xml": { + source: "iana", + compressible: true +}, + "application/emergencycalldata.cap+xml": { + source: "iana", + charset: "UTF-8", + compressible: true +}, + "application/emergencycalldata.comment+xml": { + source: "iana", + compressible: true +}, + "application/emergencycalldata.control+xml": { + source: "iana", + compressible: true +}, + "application/emergencycalldata.deviceinfo+xml": { + source: "iana", + compressible: true +}, + "application/emergencycalldata.ecall.msd": { + source: "iana" +}, + "application/emergencycalldata.providerinfo+xml": { + source: "iana", + compressible: true +}, + "application/emergencycalldata.serviceinfo+xml": { + source: "iana", + compressible: true +}, + "application/emergencycalldata.subscriberinfo+xml": { + source: "iana", + compressible: true +}, + "application/emergencycalldata.veds+xml": { + source: "iana", + compressible: true +}, + "application/emma+xml": { + source: "iana", + compressible: true, + extensions: [ + "emma" + ] +}, + "application/emotionml+xml": { + source: "iana", + compressible: true, + extensions: [ + "emotionml" + ] +}, + "application/encaprtp": { + source: "iana" +}, + "application/epp+xml": { + source: "iana", + compressible: true +}, + "application/epub+zip": { + source: "iana", + compressible: false, + extensions: [ + "epub" + ] +}, + "application/eshop": { + source: "iana" +}, + "application/exi": { + source: "iana", + extensions: [ + "exi" + ] +}, + "application/expect-ct-report+json": { + source: "iana", + compressible: true +}, + "application/express": { + source: "iana", + extensions: [ + "exp" + ] +}, + "application/fastinfoset": { + source: "iana" +}, + "application/fastsoap": { + source: "iana" +}, + "application/fdt+xml": { + source: "iana", + compressible: true, + extensions: [ + "fdt" + ] +}, + "application/fhir+json": { + source: "iana", + charset: "UTF-8", + compressible: true +}, + "application/fhir+xml": { + source: "iana", + charset: "UTF-8", + compressible: true +}, + "application/fido.trusted-apps+json": { + compressible: true +}, + "application/fits": { + source: "iana" +}, + "application/flexfec": { + source: "iana" +}, + "application/font-sfnt": { + source: "iana" +}, + "application/font-tdpfr": { + source: "iana", + extensions: [ + "pfr" + ] +}, + "application/font-woff": { + source: "iana", + compressible: false +}, + "application/framework-attributes+xml": { + source: "iana", + compressible: true +}, + "application/geo+json": { + source: "iana", + compressible: true, + extensions: [ + "geojson" + ] +}, + "application/geo+json-seq": { + source: "iana" +}, + "application/geopackage+sqlite3": { + source: "iana" +}, + "application/geoxacml+xml": { + source: "iana", + compressible: true +}, + "application/gltf-buffer": { + source: "iana" +}, + "application/gml+xml": { + source: "iana", + compressible: true, + extensions: [ + "gml" + ] +}, + "application/gpx+xml": { + source: "apache", + compressible: true, + extensions: [ + "gpx" + ] +}, + "application/gxf": { + source: "apache", + extensions: [ + "gxf" + ] +}, + "application/gzip": { + source: "iana", + compressible: false, + extensions: [ + "gz" + ] +}, + "application/h224": { + source: "iana" +}, + "application/held+xml": { + source: "iana", + compressible: true +}, + "application/hjson": { + extensions: [ + "hjson" + ] +}, + "application/http": { + source: "iana" +}, + "application/hyperstudio": { + source: "iana", + extensions: [ + "stk" + ] +}, + "application/ibe-key-request+xml": { + source: "iana", + compressible: true +}, + "application/ibe-pkg-reply+xml": { + source: "iana", + compressible: true +}, + "application/ibe-pp-data": { + source: "iana" +}, + "application/iges": { + source: "iana" +}, + "application/im-iscomposing+xml": { + source: "iana", + charset: "UTF-8", + compressible: true +}, + "application/index": { + source: "iana" +}, + "application/index.cmd": { + source: "iana" +}, + "application/index.obj": { + source: "iana" +}, + "application/index.response": { + source: "iana" +}, + "application/index.vnd": { + source: "iana" +}, + "application/inkml+xml": { + source: "iana", + compressible: true, + extensions: [ + "ink", + "inkml" + ] +}, + "application/iotp": { + source: "iana" +}, + "application/ipfix": { + source: "iana", + extensions: [ + "ipfix" + ] +}, + "application/ipp": { + source: "iana" +}, + "application/isup": { + source: "iana" +}, + "application/its+xml": { + source: "iana", + compressible: true, + extensions: [ + "its" + ] +}, + "application/java-archive": { + source: "apache", + compressible: false, + extensions: [ + "jar", + "war", + "ear" + ] +}, + "application/java-serialized-object": { + source: "apache", + compressible: false, + extensions: [ + "ser" + ] +}, + "application/java-vm": { + source: "apache", + compressible: false, + extensions: [ + "class" + ] +}, + "application/javascript": { + source: "iana", + charset: "UTF-8", + compressible: true, + extensions: [ + "js", + "mjs" + ] +}, + "application/jf2feed+json": { + source: "iana", + compressible: true +}, + "application/jose": { + source: "iana" +}, + "application/jose+json": { + source: "iana", + compressible: true +}, + "application/jrd+json": { + source: "iana", + compressible: true +}, + "application/jscalendar+json": { + source: "iana", + compressible: true +}, + "application/json": { + source: "iana", + charset: "UTF-8", + compressible: true, + extensions: [ + "json", + "map" + ] +}, + "application/json-patch+json": { + source: "iana", + compressible: true +}, + "application/json-seq": { + source: "iana" +}, + "application/json5": { + extensions: [ + "json5" + ] +}, + "application/jsonml+json": { + source: "apache", + compressible: true, + extensions: [ + "jsonml" + ] +}, + "application/jwk+json": { + source: "iana", + compressible: true +}, + "application/jwk-set+json": { + source: "iana", + compressible: true +}, + "application/jwt": { + source: "iana" +}, + "application/kpml-request+xml": { + source: "iana", + compressible: true +}, + "application/kpml-response+xml": { + source: "iana", + compressible: true +}, + "application/ld+json": { + source: "iana", + compressible: true, + extensions: [ + "jsonld" + ] +}, + "application/lgr+xml": { + source: "iana", + compressible: true, + extensions: [ + "lgr" + ] +}, + "application/link-format": { + source: "iana" +}, + "application/load-control+xml": { + source: "iana", + compressible: true +}, + "application/lost+xml": { + source: "iana", + compressible: true, + extensions: [ + "lostxml" + ] +}, + "application/lostsync+xml": { + source: "iana", + compressible: true +}, + "application/lpf+zip": { + source: "iana", + compressible: false +}, + "application/lxf": { + source: "iana" +}, + "application/mac-binhex40": { + source: "iana", + extensions: [ + "hqx" + ] +}, + "application/mac-compactpro": { + source: "apache", + extensions: [ + "cpt" + ] +}, + "application/macwriteii": { + source: "iana" +}, + "application/mads+xml": { + source: "iana", + compressible: true, + extensions: [ + "mads" + ] +}, + "application/manifest+json": { + source: "iana", + charset: "UTF-8", + compressible: true, + extensions: [ + "webmanifest" + ] +}, + "application/marc": { + source: "iana", + extensions: [ + "mrc" + ] +}, + "application/marcxml+xml": { + source: "iana", + compressible: true, + extensions: [ + "mrcx" + ] +}, + "application/mathematica": { + source: "iana", + extensions: [ + "ma", + "nb", + "mb" + ] +}, + "application/mathml+xml": { + source: "iana", + compressible: true, + extensions: [ + "mathml" + ] +}, + "application/mathml-content+xml": { + source: "iana", + compressible: true +}, + "application/mathml-presentation+xml": { + source: "iana", + compressible: true +}, + "application/mbms-associated-procedure-description+xml": { + source: "iana", + compressible: true +}, + "application/mbms-deregister+xml": { + source: "iana", + compressible: true +}, + "application/mbms-envelope+xml": { + source: "iana", + compressible: true +}, + "application/mbms-msk+xml": { + source: "iana", + compressible: true +}, + "application/mbms-msk-response+xml": { + source: "iana", + compressible: true +}, + "application/mbms-protection-description+xml": { + source: "iana", + compressible: true +}, + "application/mbms-reception-report+xml": { + source: "iana", + compressible: true +}, + "application/mbms-register+xml": { + source: "iana", + compressible: true +}, + "application/mbms-register-response+xml": { + source: "iana", + compressible: true +}, + "application/mbms-schedule+xml": { + source: "iana", + compressible: true +}, + "application/mbms-user-service-description+xml": { + source: "iana", + compressible: true +}, + "application/mbox": { + source: "iana", + extensions: [ + "mbox" + ] +}, + "application/media-policy-dataset+xml": { + source: "iana", + compressible: true, + extensions: [ + "mpf" + ] +}, + "application/media_control+xml": { + source: "iana", + compressible: true +}, + "application/mediaservercontrol+xml": { + source: "iana", + compressible: true, + extensions: [ + "mscml" + ] +}, + "application/merge-patch+json": { + source: "iana", + compressible: true +}, + "application/metalink+xml": { + source: "apache", + compressible: true, + extensions: [ + "metalink" + ] +}, + "application/metalink4+xml": { + source: "iana", + compressible: true, + extensions: [ + "meta4" + ] +}, + "application/mets+xml": { + source: "iana", + compressible: true, + extensions: [ + "mets" + ] +}, + "application/mf4": { + source: "iana" +}, + "application/mikey": { + source: "iana" +}, + "application/mipc": { + source: "iana" +}, + "application/missing-blocks+cbor-seq": { + source: "iana" +}, + "application/mmt-aei+xml": { + source: "iana", + compressible: true, + extensions: [ + "maei" + ] +}, + "application/mmt-usd+xml": { + source: "iana", + compressible: true, + extensions: [ + "musd" + ] +}, + "application/mods+xml": { + source: "iana", + compressible: true, + extensions: [ + "mods" + ] +}, + "application/moss-keys": { + source: "iana" +}, + "application/moss-signature": { + source: "iana" +}, + "application/mosskey-data": { + source: "iana" +}, + "application/mosskey-request": { + source: "iana" +}, + "application/mp21": { + source: "iana", + extensions: [ + "m21", + "mp21" + ] +}, + "application/mp4": { + source: "iana", + extensions: [ + "mp4s", + "m4p" + ] +}, + "application/mpeg4-generic": { + source: "iana" +}, + "application/mpeg4-iod": { + source: "iana" +}, + "application/mpeg4-iod-xmt": { + source: "iana" +}, + "application/mrb-consumer+xml": { + source: "iana", + compressible: true +}, + "application/mrb-publish+xml": { + source: "iana", + compressible: true +}, + "application/msc-ivr+xml": { + source: "iana", + charset: "UTF-8", + compressible: true +}, + "application/msc-mixer+xml": { + source: "iana", + charset: "UTF-8", + compressible: true +}, + "application/msword": { + source: "iana", + compressible: false, + extensions: [ + "doc", + "dot" + ] +}, + "application/mud+json": { + source: "iana", + compressible: true +}, + "application/multipart-core": { + source: "iana" +}, + "application/mxf": { + source: "iana", + extensions: [ + "mxf" + ] +}, + "application/n-quads": { + source: "iana", + extensions: [ + "nq" + ] +}, + "application/n-triples": { + source: "iana", + extensions: [ + "nt" + ] +}, + "application/nasdata": { + source: "iana" +}, + "application/news-checkgroups": { + source: "iana", + charset: "US-ASCII" +}, + "application/news-groupinfo": { + source: "iana", + charset: "US-ASCII" +}, + "application/news-transmission": { + source: "iana" +}, + "application/nlsml+xml": { + source: "iana", + compressible: true +}, + "application/node": { + source: "iana", + extensions: [ + "cjs" + ] +}, + "application/nss": { + source: "iana" +}, + "application/oauth-authz-req+jwt": { + source: "iana" +}, + "application/oblivious-dns-message": { + source: "iana" +}, + "application/ocsp-request": { + source: "iana" +}, + "application/ocsp-response": { + source: "iana" +}, + "application/octet-stream": { + source: "iana", + compressible: false, + extensions: [ + "bin", + "dms", + "lrf", + "mar", + "so", + "dist", + "distz", + "pkg", + "bpk", + "dump", + "elc", + "deploy", + "exe", + "dll", + "deb", + "dmg", + "iso", + "img", + "msi", + "msp", + "msm", + "buffer" + ] +}, + "application/oda": { + source: "iana", + extensions: [ + "oda" + ] +}, + "application/odm+xml": { + source: "iana", + compressible: true +}, + "application/odx": { + source: "iana" +}, + "application/oebps-package+xml": { + source: "iana", + compressible: true, + extensions: [ + "opf" + ] +}, + "application/ogg": { + source: "iana", + compressible: false, + extensions: [ + "ogx" + ] +}, + "application/omdoc+xml": { + source: "apache", + compressible: true, + extensions: [ + "omdoc" + ] +}, + "application/onenote": { + source: "apache", + extensions: [ + "onetoc", + "onetoc2", + "onetmp", + "onepkg" + ] +}, + "application/opc-nodeset+xml": { + source: "iana", + compressible: true +}, + "application/oscore": { + source: "iana" +}, + "application/oxps": { + source: "iana", + extensions: [ + "oxps" + ] +}, + "application/p21": { + source: "iana" +}, + "application/p21+zip": { + source: "iana", + compressible: false +}, + "application/p2p-overlay+xml": { + source: "iana", + compressible: true, + extensions: [ + "relo" + ] +}, + "application/parityfec": { + source: "iana" +}, + "application/passport": { + source: "iana" +}, + "application/patch-ops-error+xml": { + source: "iana", + compressible: true, + extensions: [ + "xer" + ] +}, + "application/pdf": { + source: "iana", + compressible: false, + extensions: [ + "pdf" + ] +}, + "application/pdx": { + source: "iana" +}, + "application/pem-certificate-chain": { + source: "iana" +}, + "application/pgp-encrypted": { + source: "iana", + compressible: false, + extensions: [ + "pgp" + ] +}, + "application/pgp-keys": { + source: "iana", + extensions: [ + "asc" + ] +}, + "application/pgp-signature": { + source: "iana", + extensions: [ + "asc", + "sig" + ] +}, + "application/pics-rules": { + source: "apache", + extensions: [ + "prf" + ] +}, + "application/pidf+xml": { + source: "iana", + charset: "UTF-8", + compressible: true +}, + "application/pidf-diff+xml": { + source: "iana", + charset: "UTF-8", + compressible: true +}, + "application/pkcs10": { + source: "iana", + extensions: [ + "p10" + ] +}, + "application/pkcs12": { + source: "iana" +}, + "application/pkcs7-mime": { + source: "iana", + extensions: [ + "p7m", + "p7c" + ] +}, + "application/pkcs7-signature": { + source: "iana", + extensions: [ + "p7s" + ] +}, + "application/pkcs8": { + source: "iana", + extensions: [ + "p8" + ] +}, + "application/pkcs8-encrypted": { + source: "iana" +}, + "application/pkix-attr-cert": { + source: "iana", + extensions: [ + "ac" + ] +}, + "application/pkix-cert": { + source: "iana", + extensions: [ + "cer" + ] +}, + "application/pkix-crl": { + source: "iana", + extensions: [ + "crl" + ] +}, + "application/pkix-pkipath": { + source: "iana", + extensions: [ + "pkipath" + ] +}, + "application/pkixcmp": { + source: "iana", + extensions: [ + "pki" + ] +}, + "application/pls+xml": { + source: "iana", + compressible: true, + extensions: [ + "pls" + ] +}, + "application/poc-settings+xml": { + source: "iana", + charset: "UTF-8", + compressible: true +}, + "application/postscript": { + source: "iana", + compressible: true, + extensions: [ + "ai", + "eps", + "ps" + ] +}, + "application/ppsp-tracker+json": { + source: "iana", + compressible: true +}, + "application/problem+json": { + source: "iana", + compressible: true +}, + "application/problem+xml": { + source: "iana", + compressible: true +}, + "application/provenance+xml": { + source: "iana", + compressible: true, + extensions: [ + "provx" + ] +}, + "application/prs.alvestrand.titrax-sheet": { + source: "iana" +}, + "application/prs.cww": { + source: "iana", + extensions: [ + "cww" + ] +}, + "application/prs.cyn": { + source: "iana", + charset: "7-BIT" +}, + "application/prs.hpub+zip": { + source: "iana", + compressible: false +}, + "application/prs.nprend": { + source: "iana" +}, + "application/prs.plucker": { + source: "iana" +}, + "application/prs.rdf-xml-crypt": { + source: "iana" +}, + "application/prs.xsf+xml": { + source: "iana", + compressible: true +}, + "application/pskc+xml": { + source: "iana", + compressible: true, + extensions: [ + "pskcxml" + ] +}, + "application/pvd+json": { + source: "iana", + compressible: true +}, + "application/qsig": { + source: "iana" +}, + "application/raml+yaml": { + compressible: true, + extensions: [ + "raml" + ] +}, + "application/raptorfec": { + source: "iana" +}, + "application/rdap+json": { + source: "iana", + compressible: true +}, + "application/rdf+xml": { + source: "iana", + compressible: true, + extensions: [ + "rdf", + "owl" + ] +}, + "application/reginfo+xml": { + source: "iana", + compressible: true, + extensions: [ + "rif" + ] +}, + "application/relax-ng-compact-syntax": { + source: "iana", + extensions: [ + "rnc" + ] +}, + "application/remote-printing": { + source: "iana" +}, + "application/reputon+json": { + source: "iana", + compressible: true +}, + "application/resource-lists+xml": { + source: "iana", + compressible: true, + extensions: [ + "rl" + ] +}, + "application/resource-lists-diff+xml": { + source: "iana", + compressible: true, + extensions: [ + "rld" + ] +}, + "application/rfc+xml": { + source: "iana", + compressible: true +}, + "application/riscos": { + source: "iana" +}, + "application/rlmi+xml": { + source: "iana", + compressible: true +}, + "application/rls-services+xml": { + source: "iana", + compressible: true, + extensions: [ + "rs" + ] +}, + "application/route-apd+xml": { + source: "iana", + compressible: true, + extensions: [ + "rapd" + ] +}, + "application/route-s-tsid+xml": { + source: "iana", + compressible: true, + extensions: [ + "sls" + ] +}, + "application/route-usd+xml": { + source: "iana", + compressible: true, + extensions: [ + "rusd" + ] +}, + "application/rpki-ghostbusters": { + source: "iana", + extensions: [ + "gbr" + ] +}, + "application/rpki-manifest": { + source: "iana", + extensions: [ + "mft" + ] +}, + "application/rpki-publication": { + source: "iana" +}, + "application/rpki-roa": { + source: "iana", + extensions: [ + "roa" + ] +}, + "application/rpki-updown": { + source: "iana" +}, + "application/rsd+xml": { + source: "apache", + compressible: true, + extensions: [ + "rsd" + ] +}, + "application/rss+xml": { + source: "apache", + compressible: true, + extensions: [ + "rss" + ] +}, + "application/rtf": { + source: "iana", + compressible: true, + extensions: [ + "rtf" + ] +}, + "application/rtploopback": { + source: "iana" +}, + "application/rtx": { + source: "iana" +}, + "application/samlassertion+xml": { + source: "iana", + compressible: true +}, + "application/samlmetadata+xml": { + source: "iana", + compressible: true +}, + "application/sarif+json": { + source: "iana", + compressible: true +}, + "application/sarif-external-properties+json": { + source: "iana", + compressible: true +}, + "application/sbe": { + source: "iana" +}, + "application/sbml+xml": { + source: "iana", + compressible: true, + extensions: [ + "sbml" + ] +}, + "application/scaip+xml": { + source: "iana", + compressible: true +}, + "application/scim+json": { + source: "iana", + compressible: true +}, + "application/scvp-cv-request": { + source: "iana", + extensions: [ + "scq" + ] +}, + "application/scvp-cv-response": { + source: "iana", + extensions: [ + "scs" + ] +}, + "application/scvp-vp-request": { + source: "iana", + extensions: [ + "spq" + ] +}, + "application/scvp-vp-response": { + source: "iana", + extensions: [ + "spp" + ] +}, + "application/sdp": { + source: "iana", + extensions: [ + "sdp" + ] +}, + "application/secevent+jwt": { + source: "iana" +}, + "application/senml+cbor": { + source: "iana" +}, + "application/senml+json": { + source: "iana", + compressible: true +}, + "application/senml+xml": { + source: "iana", + compressible: true, + extensions: [ + "senmlx" + ] +}, + "application/senml-etch+cbor": { + source: "iana" +}, + "application/senml-etch+json": { + source: "iana", + compressible: true +}, + "application/senml-exi": { + source: "iana" +}, + "application/sensml+cbor": { + source: "iana" +}, + "application/sensml+json": { + source: "iana", + compressible: true +}, + "application/sensml+xml": { + source: "iana", + compressible: true, + extensions: [ + "sensmlx" + ] +}, + "application/sensml-exi": { + source: "iana" +}, + "application/sep+xml": { + source: "iana", + compressible: true +}, + "application/sep-exi": { + source: "iana" +}, + "application/session-info": { + source: "iana" +}, + "application/set-payment": { + source: "iana" +}, + "application/set-payment-initiation": { + source: "iana", + extensions: [ + "setpay" + ] +}, + "application/set-registration": { + source: "iana" +}, + "application/set-registration-initiation": { + source: "iana", + extensions: [ + "setreg" + ] +}, + "application/sgml": { + source: "iana" +}, + "application/sgml-open-catalog": { + source: "iana" +}, + "application/shf+xml": { + source: "iana", + compressible: true, + extensions: [ + "shf" + ] +}, + "application/sieve": { + source: "iana", + extensions: [ + "siv", + "sieve" + ] +}, + "application/simple-filter+xml": { + source: "iana", + compressible: true +}, + "application/simple-message-summary": { + source: "iana" +}, + "application/simplesymbolcontainer": { + source: "iana" +}, + "application/sipc": { + source: "iana" +}, + "application/slate": { + source: "iana" +}, + "application/smil": { + source: "iana" +}, + "application/smil+xml": { + source: "iana", + compressible: true, + extensions: [ + "smi", + "smil" + ] +}, + "application/smpte336m": { + source: "iana" +}, + "application/soap+fastinfoset": { + source: "iana" +}, + "application/soap+xml": { + source: "iana", + compressible: true +}, + "application/sparql-query": { + source: "iana", + extensions: [ + "rq" + ] +}, + "application/sparql-results+xml": { + source: "iana", + compressible: true, + extensions: [ + "srx" + ] +}, + "application/spdx+json": { + source: "iana", + compressible: true +}, + "application/spirits-event+xml": { + source: "iana", + compressible: true +}, + "application/sql": { + source: "iana" +}, + "application/srgs": { + source: "iana", + extensions: [ + "gram" + ] +}, + "application/srgs+xml": { + source: "iana", + compressible: true, + extensions: [ + "grxml" + ] +}, + "application/sru+xml": { + source: "iana", + compressible: true, + extensions: [ + "sru" + ] +}, + "application/ssdl+xml": { + source: "apache", + compressible: true, + extensions: [ + "ssdl" + ] +}, + "application/ssml+xml": { + source: "iana", + compressible: true, + extensions: [ + "ssml" + ] +}, + "application/stix+json": { + source: "iana", + compressible: true +}, + "application/swid+xml": { + source: "iana", + compressible: true, + extensions: [ + "swidtag" + ] +}, + "application/tamp-apex-update": { + source: "iana" +}, + "application/tamp-apex-update-confirm": { + source: "iana" +}, + "application/tamp-community-update": { + source: "iana" +}, + "application/tamp-community-update-confirm": { + source: "iana" +}, + "application/tamp-error": { + source: "iana" +}, + "application/tamp-sequence-adjust": { + source: "iana" +}, + "application/tamp-sequence-adjust-confirm": { + source: "iana" +}, + "application/tamp-status-query": { + source: "iana" +}, + "application/tamp-status-response": { + source: "iana" +}, + "application/tamp-update": { + source: "iana" +}, + "application/tamp-update-confirm": { + source: "iana" +}, + "application/tar": { + compressible: true +}, + "application/taxii+json": { + source: "iana", + compressible: true +}, + "application/td+json": { + source: "iana", + compressible: true +}, + "application/tei+xml": { + source: "iana", + compressible: true, + extensions: [ + "tei", + "teicorpus" + ] +}, + "application/tetra_isi": { + source: "iana" +}, + "application/thraud+xml": { + source: "iana", + compressible: true, + extensions: [ + "tfi" + ] +}, + "application/timestamp-query": { + source: "iana" +}, + "application/timestamp-reply": { + source: "iana" +}, + "application/timestamped-data": { + source: "iana", + extensions: [ + "tsd" + ] +}, + "application/tlsrpt+gzip": { + source: "iana" +}, + "application/tlsrpt+json": { + source: "iana", + compressible: true +}, + "application/tnauthlist": { + source: "iana" +}, + "application/token-introspection+jwt": { + source: "iana" +}, + "application/toml": { + compressible: true, + extensions: [ + "toml" + ] +}, + "application/trickle-ice-sdpfrag": { + source: "iana" +}, + "application/trig": { + source: "iana", + extensions: [ + "trig" + ] +}, + "application/ttml+xml": { + source: "iana", + compressible: true, + extensions: [ + "ttml" + ] +}, + "application/tve-trigger": { + source: "iana" +}, + "application/tzif": { + source: "iana" +}, + "application/tzif-leap": { + source: "iana" +}, + "application/ubjson": { + compressible: false, + extensions: [ + "ubj" + ] +}, + "application/ulpfec": { + source: "iana" +}, + "application/urc-grpsheet+xml": { + source: "iana", + compressible: true +}, + "application/urc-ressheet+xml": { + source: "iana", + compressible: true, + extensions: [ + "rsheet" + ] +}, + "application/urc-targetdesc+xml": { + source: "iana", + compressible: true, + extensions: [ + "td" + ] +}, + "application/urc-uisocketdesc+xml": { + source: "iana", + compressible: true +}, + "application/vcard+json": { + source: "iana", + compressible: true +}, + "application/vcard+xml": { + source: "iana", + compressible: true +}, + "application/vemmi": { + source: "iana" +}, + "application/vividence.scriptfile": { + source: "apache" +}, + "application/vnd.1000minds.decision-model+xml": { + source: "iana", + compressible: true, + extensions: [ + "1km" + ] +}, + "application/vnd.3gpp-prose+xml": { + source: "iana", + compressible: true +}, + "application/vnd.3gpp-prose-pc3ch+xml": { + source: "iana", + compressible: true +}, + "application/vnd.3gpp-v2x-local-service-information": { + source: "iana" +}, + "application/vnd.3gpp.5gnas": { + source: "iana" +}, + "application/vnd.3gpp.access-transfer-events+xml": { + source: "iana", + compressible: true +}, + "application/vnd.3gpp.bsf+xml": { + source: "iana", + compressible: true +}, + "application/vnd.3gpp.gmop+xml": { + source: "iana", + compressible: true +}, + "application/vnd.3gpp.gtpc": { + source: "iana" +}, + "application/vnd.3gpp.interworking-data": { + source: "iana" +}, + "application/vnd.3gpp.lpp": { + source: "iana" +}, + "application/vnd.3gpp.mc-signalling-ear": { + source: "iana" +}, + "application/vnd.3gpp.mcdata-affiliation-command+xml": { + source: "iana", + compressible: true +}, + "application/vnd.3gpp.mcdata-info+xml": { + source: "iana", + compressible: true +}, + "application/vnd.3gpp.mcdata-payload": { + source: "iana" +}, + "application/vnd.3gpp.mcdata-service-config+xml": { + source: "iana", + compressible: true +}, + "application/vnd.3gpp.mcdata-signalling": { + source: "iana" +}, + "application/vnd.3gpp.mcdata-ue-config+xml": { + source: "iana", + compressible: true +}, + "application/vnd.3gpp.mcdata-user-profile+xml": { + source: "iana", + compressible: true +}, + "application/vnd.3gpp.mcptt-affiliation-command+xml": { + source: "iana", + compressible: true +}, + "application/vnd.3gpp.mcptt-floor-request+xml": { + source: "iana", + compressible: true +}, + "application/vnd.3gpp.mcptt-info+xml": { + source: "iana", + compressible: true +}, + "application/vnd.3gpp.mcptt-location-info+xml": { + source: "iana", + compressible: true +}, + "application/vnd.3gpp.mcptt-mbms-usage-info+xml": { + source: "iana", + compressible: true +}, + "application/vnd.3gpp.mcptt-service-config+xml": { + source: "iana", + compressible: true +}, + "application/vnd.3gpp.mcptt-signed+xml": { + source: "iana", + compressible: true +}, + "application/vnd.3gpp.mcptt-ue-config+xml": { + source: "iana", + compressible: true +}, + "application/vnd.3gpp.mcptt-ue-init-config+xml": { + source: "iana", + compressible: true +}, + "application/vnd.3gpp.mcptt-user-profile+xml": { + source: "iana", + compressible: true +}, + "application/vnd.3gpp.mcvideo-affiliation-command+xml": { + source: "iana", + compressible: true +}, + "application/vnd.3gpp.mcvideo-affiliation-info+xml": { + source: "iana", + compressible: true +}, + "application/vnd.3gpp.mcvideo-info+xml": { + source: "iana", + compressible: true +}, + "application/vnd.3gpp.mcvideo-location-info+xml": { + source: "iana", + compressible: true +}, + "application/vnd.3gpp.mcvideo-mbms-usage-info+xml": { + source: "iana", + compressible: true +}, + "application/vnd.3gpp.mcvideo-service-config+xml": { + source: "iana", + compressible: true +}, + "application/vnd.3gpp.mcvideo-transmission-request+xml": { + source: "iana", + compressible: true +}, + "application/vnd.3gpp.mcvideo-ue-config+xml": { + source: "iana", + compressible: true +}, + "application/vnd.3gpp.mcvideo-user-profile+xml": { + source: "iana", + compressible: true +}, + "application/vnd.3gpp.mid-call+xml": { + source: "iana", + compressible: true +}, + "application/vnd.3gpp.ngap": { + source: "iana" +}, + "application/vnd.3gpp.pfcp": { + source: "iana" +}, + "application/vnd.3gpp.pic-bw-large": { + source: "iana", + extensions: [ + "plb" + ] +}, + "application/vnd.3gpp.pic-bw-small": { + source: "iana", + extensions: [ + "psb" + ] +}, + "application/vnd.3gpp.pic-bw-var": { + source: "iana", + extensions: [ + "pvb" + ] +}, + "application/vnd.3gpp.s1ap": { + source: "iana" +}, + "application/vnd.3gpp.sms": { + source: "iana" +}, + "application/vnd.3gpp.sms+xml": { + source: "iana", + compressible: true +}, + "application/vnd.3gpp.srvcc-ext+xml": { + source: "iana", + compressible: true +}, + "application/vnd.3gpp.srvcc-info+xml": { + source: "iana", + compressible: true +}, + "application/vnd.3gpp.state-and-event-info+xml": { + source: "iana", + compressible: true +}, + "application/vnd.3gpp.ussd+xml": { + source: "iana", + compressible: true +}, + "application/vnd.3gpp2.bcmcsinfo+xml": { + source: "iana", + compressible: true +}, + "application/vnd.3gpp2.sms": { + source: "iana" +}, + "application/vnd.3gpp2.tcap": { + source: "iana", + extensions: [ + "tcap" + ] +}, + "application/vnd.3lightssoftware.imagescal": { + source: "iana" +}, + "application/vnd.3m.post-it-notes": { + source: "iana", + extensions: [ + "pwn" + ] +}, + "application/vnd.accpac.simply.aso": { + source: "iana", + extensions: [ + "aso" + ] +}, + "application/vnd.accpac.simply.imp": { + source: "iana", + extensions: [ + "imp" + ] +}, + "application/vnd.acucobol": { + source: "iana", + extensions: [ + "acu" + ] +}, + "application/vnd.acucorp": { + source: "iana", + extensions: [ + "atc", + "acutc" + ] +}, + "application/vnd.adobe.air-application-installer-package+zip": { + source: "apache", + compressible: false, + extensions: [ + "air" + ] +}, + "application/vnd.adobe.flash.movie": { + source: "iana" +}, + "application/vnd.adobe.formscentral.fcdt": { + source: "iana", + extensions: [ + "fcdt" + ] +}, + "application/vnd.adobe.fxp": { + source: "iana", + extensions: [ + "fxp", + "fxpl" + ] +}, + "application/vnd.adobe.partial-upload": { + source: "iana" +}, + "application/vnd.adobe.xdp+xml": { + source: "iana", + compressible: true, + extensions: [ + "xdp" + ] +}, + "application/vnd.adobe.xfdf": { + source: "iana", + extensions: [ + "xfdf" + ] +}, + "application/vnd.aether.imp": { + source: "iana" +}, + "application/vnd.afpc.afplinedata": { + source: "iana" +}, + "application/vnd.afpc.afplinedata-pagedef": { + source: "iana" +}, + "application/vnd.afpc.cmoca-cmresource": { + source: "iana" +}, + "application/vnd.afpc.foca-charset": { + source: "iana" +}, + "application/vnd.afpc.foca-codedfont": { + source: "iana" +}, + "application/vnd.afpc.foca-codepage": { + source: "iana" +}, + "application/vnd.afpc.modca": { + source: "iana" +}, + "application/vnd.afpc.modca-cmtable": { + source: "iana" +}, + "application/vnd.afpc.modca-formdef": { + source: "iana" +}, + "application/vnd.afpc.modca-mediummap": { + source: "iana" +}, + "application/vnd.afpc.modca-objectcontainer": { + source: "iana" +}, + "application/vnd.afpc.modca-overlay": { + source: "iana" +}, + "application/vnd.afpc.modca-pagesegment": { + source: "iana" +}, + "application/vnd.age": { + source: "iana", + extensions: [ + "age" + ] +}, + "application/vnd.ah-barcode": { + source: "iana" +}, + "application/vnd.ahead.space": { + source: "iana", + extensions: [ + "ahead" + ] +}, + "application/vnd.airzip.filesecure.azf": { + source: "iana", + extensions: [ + "azf" + ] +}, + "application/vnd.airzip.filesecure.azs": { + source: "iana", + extensions: [ + "azs" + ] +}, + "application/vnd.amadeus+json": { + source: "iana", + compressible: true +}, + "application/vnd.amazon.ebook": { + source: "apache", + extensions: [ + "azw" + ] +}, + "application/vnd.amazon.mobi8-ebook": { + source: "iana" +}, + "application/vnd.americandynamics.acc": { + source: "iana", + extensions: [ + "acc" + ] +}, + "application/vnd.amiga.ami": { + source: "iana", + extensions: [ + "ami" + ] +}, + "application/vnd.amundsen.maze+xml": { + source: "iana", + compressible: true +}, + "application/vnd.android.ota": { + source: "iana" +}, + "application/vnd.android.package-archive": { + source: "apache", + compressible: false, + extensions: [ + "apk" + ] +}, + "application/vnd.anki": { + source: "iana" +}, + "application/vnd.anser-web-certificate-issue-initiation": { + source: "iana", + extensions: [ + "cii" + ] +}, + "application/vnd.anser-web-funds-transfer-initiation": { + source: "apache", + extensions: [ + "fti" + ] +}, + "application/vnd.antix.game-component": { + source: "iana", + extensions: [ + "atx" + ] +}, + "application/vnd.apache.arrow.file": { + source: "iana" +}, + "application/vnd.apache.arrow.stream": { + source: "iana" +}, + "application/vnd.apache.thrift.binary": { + source: "iana" +}, + "application/vnd.apache.thrift.compact": { + source: "iana" +}, + "application/vnd.apache.thrift.json": { + source: "iana" +}, + "application/vnd.api+json": { + source: "iana", + compressible: true +}, + "application/vnd.aplextor.warrp+json": { + source: "iana", + compressible: true +}, + "application/vnd.apothekende.reservation+json": { + source: "iana", + compressible: true +}, + "application/vnd.apple.installer+xml": { + source: "iana", + compressible: true, + extensions: [ + "mpkg" + ] +}, + "application/vnd.apple.keynote": { + source: "iana", + extensions: [ + "key" + ] +}, + "application/vnd.apple.mpegurl": { + source: "iana", + extensions: [ + "m3u8" + ] +}, + "application/vnd.apple.numbers": { + source: "iana", + extensions: [ + "numbers" + ] +}, + "application/vnd.apple.pages": { + source: "iana", + extensions: [ + "pages" + ] +}, + "application/vnd.apple.pkpass": { + compressible: false, + extensions: [ + "pkpass" + ] +}, + "application/vnd.arastra.swi": { + source: "iana" +}, + "application/vnd.aristanetworks.swi": { + source: "iana", + extensions: [ + "swi" + ] +}, + "application/vnd.artisan+json": { + source: "iana", + compressible: true +}, + "application/vnd.artsquare": { + source: "iana" +}, + "application/vnd.astraea-software.iota": { + source: "iana", + extensions: [ + "iota" + ] +}, + "application/vnd.audiograph": { + source: "iana", + extensions: [ + "aep" + ] +}, + "application/vnd.autopackage": { + source: "iana" +}, + "application/vnd.avalon+json": { + source: "iana", + compressible: true +}, + "application/vnd.avistar+xml": { + source: "iana", + compressible: true +}, + "application/vnd.balsamiq.bmml+xml": { + source: "iana", + compressible: true, + extensions: [ + "bmml" + ] +}, + "application/vnd.balsamiq.bmpr": { + source: "iana" +}, + "application/vnd.banana-accounting": { + source: "iana" +}, + "application/vnd.bbf.usp.error": { + source: "iana" +}, + "application/vnd.bbf.usp.msg": { + source: "iana" +}, + "application/vnd.bbf.usp.msg+json": { + source: "iana", + compressible: true +}, + "application/vnd.bekitzur-stech+json": { + source: "iana", + compressible: true +}, + "application/vnd.bint.med-content": { + source: "iana" +}, + "application/vnd.biopax.rdf+xml": { + source: "iana", + compressible: true +}, + "application/vnd.blink-idb-value-wrapper": { + source: "iana" +}, + "application/vnd.blueice.multipass": { + source: "iana", + extensions: [ + "mpm" + ] +}, + "application/vnd.bluetooth.ep.oob": { + source: "iana" +}, + "application/vnd.bluetooth.le.oob": { + source: "iana" +}, + "application/vnd.bmi": { + source: "iana", + extensions: [ + "bmi" + ] +}, + "application/vnd.bpf": { + source: "iana" +}, + "application/vnd.bpf3": { + source: "iana" +}, + "application/vnd.businessobjects": { + source: "iana", + extensions: [ + "rep" + ] +}, + "application/vnd.byu.uapi+json": { + source: "iana", + compressible: true +}, + "application/vnd.cab-jscript": { + source: "iana" +}, + "application/vnd.canon-cpdl": { + source: "iana" +}, + "application/vnd.canon-lips": { + source: "iana" +}, + "application/vnd.capasystems-pg+json": { + source: "iana", + compressible: true +}, + "application/vnd.cendio.thinlinc.clientconf": { + source: "iana" +}, + "application/vnd.century-systems.tcp_stream": { + source: "iana" +}, + "application/vnd.chemdraw+xml": { + source: "iana", + compressible: true, + extensions: [ + "cdxml" + ] +}, + "application/vnd.chess-pgn": { + source: "iana" +}, + "application/vnd.chipnuts.karaoke-mmd": { + source: "iana", + extensions: [ + "mmd" + ] +}, + "application/vnd.ciedi": { + source: "iana" +}, + "application/vnd.cinderella": { + source: "iana", + extensions: [ + "cdy" + ] +}, + "application/vnd.cirpack.isdn-ext": { + source: "iana" +}, + "application/vnd.citationstyles.style+xml": { + source: "iana", + compressible: true, + extensions: [ + "csl" + ] +}, + "application/vnd.claymore": { + source: "iana", + extensions: [ + "cla" + ] +}, + "application/vnd.cloanto.rp9": { + source: "iana", + extensions: [ + "rp9" + ] +}, + "application/vnd.clonk.c4group": { + source: "iana", + extensions: [ + "c4g", + "c4d", + "c4f", + "c4p", + "c4u" + ] +}, + "application/vnd.cluetrust.cartomobile-config": { + source: "iana", + extensions: [ + "c11amc" + ] +}, + "application/vnd.cluetrust.cartomobile-config-pkg": { + source: "iana", + extensions: [ + "c11amz" + ] +}, + "application/vnd.coffeescript": { + source: "iana" +}, + "application/vnd.collabio.xodocuments.document": { + source: "iana" +}, + "application/vnd.collabio.xodocuments.document-template": { + source: "iana" +}, + "application/vnd.collabio.xodocuments.presentation": { + source: "iana" +}, + "application/vnd.collabio.xodocuments.presentation-template": { + source: "iana" +}, + "application/vnd.collabio.xodocuments.spreadsheet": { + source: "iana" +}, + "application/vnd.collabio.xodocuments.spreadsheet-template": { + source: "iana" +}, + "application/vnd.collection+json": { + source: "iana", + compressible: true +}, + "application/vnd.collection.doc+json": { + source: "iana", + compressible: true +}, + "application/vnd.collection.next+json": { + source: "iana", + compressible: true +}, + "application/vnd.comicbook+zip": { + source: "iana", + compressible: false +}, + "application/vnd.comicbook-rar": { + source: "iana" +}, + "application/vnd.commerce-battelle": { + source: "iana" +}, + "application/vnd.commonspace": { + source: "iana", + extensions: [ + "csp" + ] +}, + "application/vnd.contact.cmsg": { + source: "iana", + extensions: [ + "cdbcmsg" + ] +}, + "application/vnd.coreos.ignition+json": { + source: "iana", + compressible: true +}, + "application/vnd.cosmocaller": { + source: "iana", + extensions: [ + "cmc" + ] +}, + "application/vnd.crick.clicker": { + source: "iana", + extensions: [ + "clkx" + ] +}, + "application/vnd.crick.clicker.keyboard": { + source: "iana", + extensions: [ + "clkk" + ] +}, + "application/vnd.crick.clicker.palette": { + source: "iana", + extensions: [ + "clkp" + ] +}, + "application/vnd.crick.clicker.template": { + source: "iana", + extensions: [ + "clkt" + ] +}, + "application/vnd.crick.clicker.wordbank": { + source: "iana", + extensions: [ + "clkw" + ] +}, + "application/vnd.criticaltools.wbs+xml": { + source: "iana", + compressible: true, + extensions: [ + "wbs" + ] +}, + "application/vnd.cryptii.pipe+json": { + source: "iana", + compressible: true +}, + "application/vnd.crypto-shade-file": { + source: "iana" +}, + "application/vnd.cryptomator.encrypted": { + source: "iana" +}, + "application/vnd.cryptomator.vault": { + source: "iana" +}, + "application/vnd.ctc-posml": { + source: "iana", + extensions: [ + "pml" + ] +}, + "application/vnd.ctct.ws+xml": { + source: "iana", + compressible: true +}, + "application/vnd.cups-pdf": { + source: "iana" +}, + "application/vnd.cups-postscript": { + source: "iana" +}, + "application/vnd.cups-ppd": { + source: "iana", + extensions: [ + "ppd" + ] +}, + "application/vnd.cups-raster": { + source: "iana" +}, + "application/vnd.cups-raw": { + source: "iana" +}, + "application/vnd.curl": { + source: "iana" +}, + "application/vnd.curl.car": { + source: "apache", + extensions: [ + "car" + ] +}, + "application/vnd.curl.pcurl": { + source: "apache", + extensions: [ + "pcurl" + ] +}, + "application/vnd.cyan.dean.root+xml": { + source: "iana", + compressible: true +}, + "application/vnd.cybank": { + source: "iana" +}, + "application/vnd.cyclonedx+json": { + source: "iana", + compressible: true +}, + "application/vnd.cyclonedx+xml": { + source: "iana", + compressible: true +}, + "application/vnd.d2l.coursepackage1p0+zip": { + source: "iana", + compressible: false +}, + "application/vnd.d3m-dataset": { + source: "iana" +}, + "application/vnd.d3m-problem": { + source: "iana" +}, + "application/vnd.dart": { + source: "iana", + compressible: true, + extensions: [ + "dart" + ] +}, + "application/vnd.data-vision.rdz": { + source: "iana", + extensions: [ + "rdz" + ] +}, + "application/vnd.datapackage+json": { + source: "iana", + compressible: true +}, + "application/vnd.dataresource+json": { + source: "iana", + compressible: true +}, + "application/vnd.dbf": { + source: "iana", + extensions: [ + "dbf" + ] +}, + "application/vnd.debian.binary-package": { + source: "iana" +}, + "application/vnd.dece.data": { + source: "iana", + extensions: [ + "uvf", + "uvvf", + "uvd", + "uvvd" + ] +}, + "application/vnd.dece.ttml+xml": { + source: "iana", + compressible: true, + extensions: [ + "uvt", + "uvvt" + ] +}, + "application/vnd.dece.unspecified": { + source: "iana", + extensions: [ + "uvx", + "uvvx" + ] +}, + "application/vnd.dece.zip": { + source: "iana", + extensions: [ + "uvz", + "uvvz" + ] +}, + "application/vnd.denovo.fcselayout-link": { + source: "iana", + extensions: [ + "fe_launch" + ] +}, + "application/vnd.desmume.movie": { + source: "iana" +}, + "application/vnd.dir-bi.plate-dl-nosuffix": { + source: "iana" +}, + "application/vnd.dm.delegation+xml": { + source: "iana", + compressible: true +}, + "application/vnd.dna": { + source: "iana", + extensions: [ + "dna" + ] +}, + "application/vnd.document+json": { + source: "iana", + compressible: true +}, + "application/vnd.dolby.mlp": { + source: "apache", + extensions: [ + "mlp" + ] +}, + "application/vnd.dolby.mobile.1": { + source: "iana" +}, + "application/vnd.dolby.mobile.2": { + source: "iana" +}, + "application/vnd.doremir.scorecloud-binary-document": { + source: "iana" +}, + "application/vnd.dpgraph": { + source: "iana", + extensions: [ + "dpg" + ] +}, + "application/vnd.dreamfactory": { + source: "iana", + extensions: [ + "dfac" + ] +}, + "application/vnd.drive+json": { + source: "iana", + compressible: true +}, + "application/vnd.ds-keypoint": { + source: "apache", + extensions: [ + "kpxx" + ] +}, + "application/vnd.dtg.local": { + source: "iana" +}, + "application/vnd.dtg.local.flash": { + source: "iana" +}, + "application/vnd.dtg.local.html": { + source: "iana" +}, + "application/vnd.dvb.ait": { + source: "iana", + extensions: [ + "ait" + ] +}, + "application/vnd.dvb.dvbisl+xml": { + source: "iana", + compressible: true +}, + "application/vnd.dvb.dvbj": { + source: "iana" +}, + "application/vnd.dvb.esgcontainer": { + source: "iana" +}, + "application/vnd.dvb.ipdcdftnotifaccess": { + source: "iana" +}, + "application/vnd.dvb.ipdcesgaccess": { + source: "iana" +}, + "application/vnd.dvb.ipdcesgaccess2": { + source: "iana" +}, + "application/vnd.dvb.ipdcesgpdd": { + source: "iana" +}, + "application/vnd.dvb.ipdcroaming": { + source: "iana" +}, + "application/vnd.dvb.iptv.alfec-base": { + source: "iana" +}, + "application/vnd.dvb.iptv.alfec-enhancement": { + source: "iana" +}, + "application/vnd.dvb.notif-aggregate-root+xml": { + source: "iana", + compressible: true +}, + "application/vnd.dvb.notif-container+xml": { + source: "iana", + compressible: true +}, + "application/vnd.dvb.notif-generic+xml": { + source: "iana", + compressible: true +}, + "application/vnd.dvb.notif-ia-msglist+xml": { + source: "iana", + compressible: true +}, + "application/vnd.dvb.notif-ia-registration-request+xml": { + source: "iana", + compressible: true +}, + "application/vnd.dvb.notif-ia-registration-response+xml": { + source: "iana", + compressible: true +}, + "application/vnd.dvb.notif-init+xml": { + source: "iana", + compressible: true +}, + "application/vnd.dvb.pfr": { + source: "iana" +}, + "application/vnd.dvb.service": { + source: "iana", + extensions: [ + "svc" + ] +}, + "application/vnd.dxr": { + source: "iana" +}, + "application/vnd.dynageo": { + source: "iana", + extensions: [ + "geo" + ] +}, + "application/vnd.dzr": { + source: "iana" +}, + "application/vnd.easykaraoke.cdgdownload": { + source: "iana" +}, + "application/vnd.ecdis-update": { + source: "iana" +}, + "application/vnd.ecip.rlp": { + source: "iana" +}, + "application/vnd.eclipse.ditto+json": { + source: "iana", + compressible: true +}, + "application/vnd.ecowin.chart": { + source: "iana", + extensions: [ + "mag" + ] +}, + "application/vnd.ecowin.filerequest": { + source: "iana" +}, + "application/vnd.ecowin.fileupdate": { + source: "iana" +}, + "application/vnd.ecowin.series": { + source: "iana" +}, + "application/vnd.ecowin.seriesrequest": { + source: "iana" +}, + "application/vnd.ecowin.seriesupdate": { + source: "iana" +}, + "application/vnd.efi.img": { + source: "iana" +}, + "application/vnd.efi.iso": { + source: "iana" +}, + "application/vnd.emclient.accessrequest+xml": { + source: "iana", + compressible: true +}, + "application/vnd.enliven": { + source: "iana", + extensions: [ + "nml" + ] +}, + "application/vnd.enphase.envoy": { + source: "iana" +}, + "application/vnd.eprints.data+xml": { + source: "iana", + compressible: true +}, + "application/vnd.epson.esf": { + source: "iana", + extensions: [ + "esf" + ] +}, + "application/vnd.epson.msf": { + source: "iana", + extensions: [ + "msf" + ] +}, + "application/vnd.epson.quickanime": { + source: "iana", + extensions: [ + "qam" + ] +}, + "application/vnd.epson.salt": { + source: "iana", + extensions: [ + "slt" + ] +}, + "application/vnd.epson.ssf": { + source: "iana", + extensions: [ + "ssf" + ] +}, + "application/vnd.ericsson.quickcall": { + source: "iana" +}, + "application/vnd.espass-espass+zip": { + source: "iana", + compressible: false +}, + "application/vnd.eszigno3+xml": { + source: "iana", + compressible: true, + extensions: [ + "es3", + "et3" + ] +}, + "application/vnd.etsi.aoc+xml": { + source: "iana", + compressible: true +}, + "application/vnd.etsi.asic-e+zip": { + source: "iana", + compressible: false +}, + "application/vnd.etsi.asic-s+zip": { + source: "iana", + compressible: false +}, + "application/vnd.etsi.cug+xml": { + source: "iana", + compressible: true +}, + "application/vnd.etsi.iptvcommand+xml": { + source: "iana", + compressible: true +}, + "application/vnd.etsi.iptvdiscovery+xml": { + source: "iana", + compressible: true +}, + "application/vnd.etsi.iptvprofile+xml": { + source: "iana", + compressible: true +}, + "application/vnd.etsi.iptvsad-bc+xml": { + source: "iana", + compressible: true +}, + "application/vnd.etsi.iptvsad-cod+xml": { + source: "iana", + compressible: true +}, + "application/vnd.etsi.iptvsad-npvr+xml": { + source: "iana", + compressible: true +}, + "application/vnd.etsi.iptvservice+xml": { + source: "iana", + compressible: true +}, + "application/vnd.etsi.iptvsync+xml": { + source: "iana", + compressible: true +}, + "application/vnd.etsi.iptvueprofile+xml": { + source: "iana", + compressible: true +}, + "application/vnd.etsi.mcid+xml": { + source: "iana", + compressible: true +}, + "application/vnd.etsi.mheg5": { + source: "iana" +}, + "application/vnd.etsi.overload-control-policy-dataset+xml": { + source: "iana", + compressible: true +}, + "application/vnd.etsi.pstn+xml": { + source: "iana", + compressible: true +}, + "application/vnd.etsi.sci+xml": { + source: "iana", + compressible: true +}, + "application/vnd.etsi.simservs+xml": { + source: "iana", + compressible: true +}, + "application/vnd.etsi.timestamp-token": { + source: "iana" +}, + "application/vnd.etsi.tsl+xml": { + source: "iana", + compressible: true +}, + "application/vnd.etsi.tsl.der": { + source: "iana" +}, + "application/vnd.eu.kasparian.car+json": { + source: "iana", + compressible: true +}, + "application/vnd.eudora.data": { + source: "iana" +}, + "application/vnd.evolv.ecig.profile": { + source: "iana" +}, + "application/vnd.evolv.ecig.settings": { + source: "iana" +}, + "application/vnd.evolv.ecig.theme": { + source: "iana" +}, + "application/vnd.exstream-empower+zip": { + source: "iana", + compressible: false +}, + "application/vnd.exstream-package": { + source: "iana" +}, + "application/vnd.ezpix-album": { + source: "iana", + extensions: [ + "ez2" + ] +}, + "application/vnd.ezpix-package": { + source: "iana", + extensions: [ + "ez3" + ] +}, + "application/vnd.f-secure.mobile": { + source: "iana" +}, + "application/vnd.familysearch.gedcom+zip": { + source: "iana", + compressible: false +}, + "application/vnd.fastcopy-disk-image": { + source: "iana" +}, + "application/vnd.fdf": { + source: "iana", + extensions: [ + "fdf" + ] +}, + "application/vnd.fdsn.mseed": { + source: "iana", + extensions: [ + "mseed" + ] +}, + "application/vnd.fdsn.seed": { + source: "iana", + extensions: [ + "seed", + "dataless" + ] +}, + "application/vnd.ffsns": { + source: "iana" +}, + "application/vnd.ficlab.flb+zip": { + source: "iana", + compressible: false +}, + "application/vnd.filmit.zfc": { + source: "iana" +}, + "application/vnd.fints": { + source: "iana" +}, + "application/vnd.firemonkeys.cloudcell": { + source: "iana" +}, + "application/vnd.flographit": { + source: "iana", + extensions: [ + "gph" + ] +}, + "application/vnd.fluxtime.clip": { + source: "iana", + extensions: [ + "ftc" + ] +}, + "application/vnd.font-fontforge-sfd": { + source: "iana" +}, + "application/vnd.framemaker": { + source: "iana", + extensions: [ + "fm", + "frame", + "maker", + "book" + ] +}, + "application/vnd.frogans.fnc": { + source: "iana", + extensions: [ + "fnc" + ] +}, + "application/vnd.frogans.ltf": { + source: "iana", + extensions: [ + "ltf" + ] +}, + "application/vnd.fsc.weblaunch": { + source: "iana", + extensions: [ + "fsc" + ] +}, + "application/vnd.fujifilm.fb.docuworks": { + source: "iana" +}, + "application/vnd.fujifilm.fb.docuworks.binder": { + source: "iana" +}, + "application/vnd.fujifilm.fb.docuworks.container": { + source: "iana" +}, + "application/vnd.fujifilm.fb.jfi+xml": { + source: "iana", + compressible: true +}, + "application/vnd.fujitsu.oasys": { + source: "iana", + extensions: [ + "oas" + ] +}, + "application/vnd.fujitsu.oasys2": { + source: "iana", + extensions: [ + "oa2" + ] +}, + "application/vnd.fujitsu.oasys3": { + source: "iana", + extensions: [ + "oa3" + ] +}, + "application/vnd.fujitsu.oasysgp": { + source: "iana", + extensions: [ + "fg5" + ] +}, + "application/vnd.fujitsu.oasysprs": { + source: "iana", + extensions: [ + "bh2" + ] +}, + "application/vnd.fujixerox.art-ex": { + source: "iana" +}, + "application/vnd.fujixerox.art4": { + source: "iana" +}, + "application/vnd.fujixerox.ddd": { + source: "iana", + extensions: [ + "ddd" + ] +}, + "application/vnd.fujixerox.docuworks": { + source: "iana", + extensions: [ + "xdw" + ] +}, + "application/vnd.fujixerox.docuworks.binder": { + source: "iana", + extensions: [ + "xbd" + ] +}, + "application/vnd.fujixerox.docuworks.container": { + source: "iana" +}, + "application/vnd.fujixerox.hbpl": { + source: "iana" +}, + "application/vnd.fut-misnet": { + source: "iana" +}, + "application/vnd.futoin+cbor": { + source: "iana" +}, + "application/vnd.futoin+json": { + source: "iana", + compressible: true +}, + "application/vnd.fuzzysheet": { + source: "iana", + extensions: [ + "fzs" + ] +}, + "application/vnd.genomatix.tuxedo": { + source: "iana", + extensions: [ + "txd" + ] +}, + "application/vnd.gentics.grd+json": { + source: "iana", + compressible: true +}, + "application/vnd.geo+json": { + source: "iana", + compressible: true +}, + "application/vnd.geocube+xml": { + source: "iana", + compressible: true +}, + "application/vnd.geogebra.file": { + source: "iana", + extensions: [ + "ggb" + ] +}, + "application/vnd.geogebra.slides": { + source: "iana" +}, + "application/vnd.geogebra.tool": { + source: "iana", + extensions: [ + "ggt" + ] +}, + "application/vnd.geometry-explorer": { + source: "iana", + extensions: [ + "gex", + "gre" + ] +}, + "application/vnd.geonext": { + source: "iana", + extensions: [ + "gxt" + ] +}, + "application/vnd.geoplan": { + source: "iana", + extensions: [ + "g2w" + ] +}, + "application/vnd.geospace": { + source: "iana", + extensions: [ + "g3w" + ] +}, + "application/vnd.gerber": { + source: "iana" +}, + "application/vnd.globalplatform.card-content-mgt": { + source: "iana" +}, + "application/vnd.globalplatform.card-content-mgt-response": { + source: "iana" +}, + "application/vnd.gmx": { + source: "iana", + extensions: [ + "gmx" + ] +}, + "application/vnd.google-apps.document": { + compressible: false, + extensions: [ + "gdoc" + ] +}, + "application/vnd.google-apps.presentation": { + compressible: false, + extensions: [ + "gslides" + ] +}, + "application/vnd.google-apps.spreadsheet": { + compressible: false, + extensions: [ + "gsheet" + ] +}, + "application/vnd.google-earth.kml+xml": { + source: "iana", + compressible: true, + extensions: [ + "kml" + ] +}, + "application/vnd.google-earth.kmz": { + source: "iana", + compressible: false, + extensions: [ + "kmz" + ] +}, + "application/vnd.gov.sk.e-form+xml": { + source: "iana", + compressible: true +}, + "application/vnd.gov.sk.e-form+zip": { + source: "iana", + compressible: false +}, + "application/vnd.gov.sk.xmldatacontainer+xml": { + source: "iana", + compressible: true +}, + "application/vnd.grafeq": { + source: "iana", + extensions: [ + "gqf", + "gqs" + ] +}, + "application/vnd.gridmp": { + source: "iana" +}, + "application/vnd.groove-account": { + source: "iana", + extensions: [ + "gac" + ] +}, + "application/vnd.groove-help": { + source: "iana", + extensions: [ + "ghf" + ] +}, + "application/vnd.groove-identity-message": { + source: "iana", + extensions: [ + "gim" + ] +}, + "application/vnd.groove-injector": { + source: "iana", + extensions: [ + "grv" + ] +}, + "application/vnd.groove-tool-message": { + source: "iana", + extensions: [ + "gtm" + ] +}, + "application/vnd.groove-tool-template": { + source: "iana", + extensions: [ + "tpl" + ] +}, + "application/vnd.groove-vcard": { + source: "iana", + extensions: [ + "vcg" + ] +}, + "application/vnd.hal+json": { + source: "iana", + compressible: true +}, + "application/vnd.hal+xml": { + source: "iana", + compressible: true, + extensions: [ + "hal" + ] +}, + "application/vnd.handheld-entertainment+xml": { + source: "iana", + compressible: true, + extensions: [ + "zmm" + ] +}, + "application/vnd.hbci": { + source: "iana", + extensions: [ + "hbci" + ] +}, + "application/vnd.hc+json": { + source: "iana", + compressible: true +}, + "application/vnd.hcl-bireports": { + source: "iana" +}, + "application/vnd.hdt": { + source: "iana" +}, + "application/vnd.heroku+json": { + source: "iana", + compressible: true +}, + "application/vnd.hhe.lesson-player": { + source: "iana", + extensions: [ + "les" + ] +}, + "application/vnd.hl7cda+xml": { + source: "iana", + charset: "UTF-8", + compressible: true +}, + "application/vnd.hl7v2+xml": { + source: "iana", + charset: "UTF-8", + compressible: true +}, + "application/vnd.hp-hpgl": { + source: "iana", + extensions: [ + "hpgl" + ] +}, + "application/vnd.hp-hpid": { + source: "iana", + extensions: [ + "hpid" + ] +}, + "application/vnd.hp-hps": { + source: "iana", + extensions: [ + "hps" + ] +}, + "application/vnd.hp-jlyt": { + source: "iana", + extensions: [ + "jlt" + ] +}, + "application/vnd.hp-pcl": { + source: "iana", + extensions: [ + "pcl" + ] +}, + "application/vnd.hp-pclxl": { + source: "iana", + extensions: [ + "pclxl" + ] +}, + "application/vnd.httphone": { + source: "iana" +}, + "application/vnd.hydrostatix.sof-data": { + source: "iana", + extensions: [ + "sfd-hdstx" + ] +}, + "application/vnd.hyper+json": { + source: "iana", + compressible: true +}, + "application/vnd.hyper-item+json": { + source: "iana", + compressible: true +}, + "application/vnd.hyperdrive+json": { + source: "iana", + compressible: true +}, + "application/vnd.hzn-3d-crossword": { + source: "iana" +}, + "application/vnd.ibm.afplinedata": { + source: "iana" +}, + "application/vnd.ibm.electronic-media": { + source: "iana" +}, + "application/vnd.ibm.minipay": { + source: "iana", + extensions: [ + "mpy" + ] +}, + "application/vnd.ibm.modcap": { + source: "iana", + extensions: [ + "afp", + "listafp", + "list3820" + ] +}, + "application/vnd.ibm.rights-management": { + source: "iana", + extensions: [ + "irm" + ] +}, + "application/vnd.ibm.secure-container": { + source: "iana", + extensions: [ + "sc" + ] +}, + "application/vnd.iccprofile": { + source: "iana", + extensions: [ + "icc", + "icm" + ] +}, + "application/vnd.ieee.1905": { + source: "iana" +}, + "application/vnd.igloader": { + source: "iana", + extensions: [ + "igl" + ] +}, + "application/vnd.imagemeter.folder+zip": { + source: "iana", + compressible: false +}, + "application/vnd.imagemeter.image+zip": { + source: "iana", + compressible: false +}, + "application/vnd.immervision-ivp": { + source: "iana", + extensions: [ + "ivp" + ] +}, + "application/vnd.immervision-ivu": { + source: "iana", + extensions: [ + "ivu" + ] +}, + "application/vnd.ims.imsccv1p1": { + source: "iana" +}, + "application/vnd.ims.imsccv1p2": { + source: "iana" +}, + "application/vnd.ims.imsccv1p3": { + source: "iana" +}, + "application/vnd.ims.lis.v2.result+json": { + source: "iana", + compressible: true +}, + "application/vnd.ims.lti.v2.toolconsumerprofile+json": { + source: "iana", + compressible: true +}, + "application/vnd.ims.lti.v2.toolproxy+json": { + source: "iana", + compressible: true +}, + "application/vnd.ims.lti.v2.toolproxy.id+json": { + source: "iana", + compressible: true +}, + "application/vnd.ims.lti.v2.toolsettings+json": { + source: "iana", + compressible: true +}, + "application/vnd.ims.lti.v2.toolsettings.simple+json": { + source: "iana", + compressible: true +}, + "application/vnd.informedcontrol.rms+xml": { + source: "iana", + compressible: true +}, + "application/vnd.informix-visionary": { + source: "iana" +}, + "application/vnd.infotech.project": { + source: "iana" +}, + "application/vnd.infotech.project+xml": { + source: "iana", + compressible: true +}, + "application/vnd.innopath.wamp.notification": { + source: "iana" +}, + "application/vnd.insors.igm": { + source: "iana", + extensions: [ + "igm" + ] +}, + "application/vnd.intercon.formnet": { + source: "iana", + extensions: [ + "xpw", + "xpx" + ] +}, + "application/vnd.intergeo": { + source: "iana", + extensions: [ + "i2g" + ] +}, + "application/vnd.intertrust.digibox": { + source: "iana" +}, + "application/vnd.intertrust.nncp": { + source: "iana" +}, + "application/vnd.intu.qbo": { + source: "iana", + extensions: [ + "qbo" + ] +}, + "application/vnd.intu.qfx": { + source: "iana", + extensions: [ + "qfx" + ] +}, + "application/vnd.iptc.g2.catalogitem+xml": { + source: "iana", + compressible: true +}, + "application/vnd.iptc.g2.conceptitem+xml": { + source: "iana", + compressible: true +}, + "application/vnd.iptc.g2.knowledgeitem+xml": { + source: "iana", + compressible: true +}, + "application/vnd.iptc.g2.newsitem+xml": { + source: "iana", + compressible: true +}, + "application/vnd.iptc.g2.newsmessage+xml": { + source: "iana", + compressible: true +}, + "application/vnd.iptc.g2.packageitem+xml": { + source: "iana", + compressible: true +}, + "application/vnd.iptc.g2.planningitem+xml": { + source: "iana", + compressible: true +}, + "application/vnd.ipunplugged.rcprofile": { + source: "iana", + extensions: [ + "rcprofile" + ] +}, + "application/vnd.irepository.package+xml": { + source: "iana", + compressible: true, + extensions: [ + "irp" + ] +}, + "application/vnd.is-xpr": { + source: "iana", + extensions: [ + "xpr" + ] +}, + "application/vnd.isac.fcs": { + source: "iana", + extensions: [ + "fcs" + ] +}, + "application/vnd.iso11783-10+zip": { + source: "iana", + compressible: false +}, + "application/vnd.jam": { + source: "iana", + extensions: [ + "jam" + ] +}, + "application/vnd.japannet-directory-service": { + source: "iana" +}, + "application/vnd.japannet-jpnstore-wakeup": { + source: "iana" +}, + "application/vnd.japannet-payment-wakeup": { + source: "iana" +}, + "application/vnd.japannet-registration": { + source: "iana" +}, + "application/vnd.japannet-registration-wakeup": { + source: "iana" +}, + "application/vnd.japannet-setstore-wakeup": { + source: "iana" +}, + "application/vnd.japannet-verification": { + source: "iana" +}, + "application/vnd.japannet-verification-wakeup": { + source: "iana" +}, + "application/vnd.jcp.javame.midlet-rms": { + source: "iana", + extensions: [ + "rms" + ] +}, + "application/vnd.jisp": { + source: "iana", + extensions: [ + "jisp" + ] +}, + "application/vnd.joost.joda-archive": { + source: "iana", + extensions: [ + "joda" + ] +}, + "application/vnd.jsk.isdn-ngn": { + source: "iana" +}, + "application/vnd.kahootz": { + source: "iana", + extensions: [ + "ktz", + "ktr" + ] +}, + "application/vnd.kde.karbon": { + source: "iana", + extensions: [ + "karbon" + ] +}, + "application/vnd.kde.kchart": { + source: "iana", + extensions: [ + "chrt" + ] +}, + "application/vnd.kde.kformula": { + source: "iana", + extensions: [ + "kfo" + ] +}, + "application/vnd.kde.kivio": { + source: "iana", + extensions: [ + "flw" + ] +}, + "application/vnd.kde.kontour": { + source: "iana", + extensions: [ + "kon" + ] +}, + "application/vnd.kde.kpresenter": { + source: "iana", + extensions: [ + "kpr", + "kpt" + ] +}, + "application/vnd.kde.kspread": { + source: "iana", + extensions: [ + "ksp" + ] +}, + "application/vnd.kde.kword": { + source: "iana", + extensions: [ + "kwd", + "kwt" + ] +}, + "application/vnd.kenameaapp": { + source: "iana", + extensions: [ + "htke" + ] +}, + "application/vnd.kidspiration": { + source: "iana", + extensions: [ + "kia" + ] +}, + "application/vnd.kinar": { + source: "iana", + extensions: [ + "kne", + "knp" + ] +}, + "application/vnd.koan": { + source: "iana", + extensions: [ + "skp", + "skd", + "skt", + "skm" + ] +}, + "application/vnd.kodak-descriptor": { + source: "iana", + extensions: [ + "sse" + ] +}, + "application/vnd.las": { + source: "iana" +}, + "application/vnd.las.las+json": { + source: "iana", + compressible: true +}, + "application/vnd.las.las+xml": { + source: "iana", + compressible: true, + extensions: [ + "lasxml" + ] +}, + "application/vnd.laszip": { + source: "iana" +}, + "application/vnd.leap+json": { + source: "iana", + compressible: true +}, + "application/vnd.liberty-request+xml": { + source: "iana", + compressible: true +}, + "application/vnd.llamagraphics.life-balance.desktop": { + source: "iana", + extensions: [ + "lbd" + ] +}, + "application/vnd.llamagraphics.life-balance.exchange+xml": { + source: "iana", + compressible: true, + extensions: [ + "lbe" + ] +}, + "application/vnd.logipipe.circuit+zip": { + source: "iana", + compressible: false +}, + "application/vnd.loom": { + source: "iana" +}, + "application/vnd.lotus-1-2-3": { + source: "iana", + extensions: [ + "123" + ] +}, + "application/vnd.lotus-approach": { + source: "iana", + extensions: [ + "apr" + ] +}, + "application/vnd.lotus-freelance": { + source: "iana", + extensions: [ + "pre" + ] +}, + "application/vnd.lotus-notes": { + source: "iana", + extensions: [ + "nsf" + ] +}, + "application/vnd.lotus-organizer": { + source: "iana", + extensions: [ + "org" + ] +}, + "application/vnd.lotus-screencam": { + source: "iana", + extensions: [ + "scm" + ] +}, + "application/vnd.lotus-wordpro": { + source: "iana", + extensions: [ + "lwp" + ] +}, + "application/vnd.macports.portpkg": { + source: "iana", + extensions: [ + "portpkg" + ] +}, + "application/vnd.mapbox-vector-tile": { + source: "iana", + extensions: [ + "mvt" + ] +}, + "application/vnd.marlin.drm.actiontoken+xml": { + source: "iana", + compressible: true +}, + "application/vnd.marlin.drm.conftoken+xml": { + source: "iana", + compressible: true +}, + "application/vnd.marlin.drm.license+xml": { + source: "iana", + compressible: true +}, + "application/vnd.marlin.drm.mdcf": { + source: "iana" +}, + "application/vnd.mason+json": { + source: "iana", + compressible: true +}, + "application/vnd.maxar.archive.3tz+zip": { + source: "iana", + compressible: false +}, + "application/vnd.maxmind.maxmind-db": { + source: "iana" +}, + "application/vnd.mcd": { + source: "iana", + extensions: [ + "mcd" + ] +}, + "application/vnd.medcalcdata": { + source: "iana", + extensions: [ + "mc1" + ] +}, + "application/vnd.mediastation.cdkey": { + source: "iana", + extensions: [ + "cdkey" + ] +}, + "application/vnd.meridian-slingshot": { + source: "iana" +}, + "application/vnd.mfer": { + source: "iana", + extensions: [ + "mwf" + ] +}, + "application/vnd.mfmp": { + source: "iana", + extensions: [ + "mfm" + ] +}, + "application/vnd.micro+json": { + source: "iana", + compressible: true +}, + "application/vnd.micrografx.flo": { + source: "iana", + extensions: [ + "flo" + ] +}, + "application/vnd.micrografx.igx": { + source: "iana", + extensions: [ + "igx" + ] +}, + "application/vnd.microsoft.portable-executable": { + source: "iana" +}, + "application/vnd.microsoft.windows.thumbnail-cache": { + source: "iana" +}, + "application/vnd.miele+json": { + source: "iana", + compressible: true +}, + "application/vnd.mif": { + source: "iana", + extensions: [ + "mif" + ] +}, + "application/vnd.minisoft-hp3000-save": { + source: "iana" +}, + "application/vnd.mitsubishi.misty-guard.trustweb": { + source: "iana" +}, + "application/vnd.mobius.daf": { + source: "iana", + extensions: [ + "daf" + ] +}, + "application/vnd.mobius.dis": { + source: "iana", + extensions: [ + "dis" + ] +}, + "application/vnd.mobius.mbk": { + source: "iana", + extensions: [ + "mbk" + ] +}, + "application/vnd.mobius.mqy": { + source: "iana", + extensions: [ + "mqy" + ] +}, + "application/vnd.mobius.msl": { + source: "iana", + extensions: [ + "msl" + ] +}, + "application/vnd.mobius.plc": { + source: "iana", + extensions: [ + "plc" + ] +}, + "application/vnd.mobius.txf": { + source: "iana", + extensions: [ + "txf" + ] +}, + "application/vnd.mophun.application": { + source: "iana", + extensions: [ + "mpn" + ] +}, + "application/vnd.mophun.certificate": { + source: "iana", + extensions: [ + "mpc" + ] +}, + "application/vnd.motorola.flexsuite": { + source: "iana" +}, + "application/vnd.motorola.flexsuite.adsi": { + source: "iana" +}, + "application/vnd.motorola.flexsuite.fis": { + source: "iana" +}, + "application/vnd.motorola.flexsuite.gotap": { + source: "iana" +}, + "application/vnd.motorola.flexsuite.kmr": { + source: "iana" +}, + "application/vnd.motorola.flexsuite.ttc": { + source: "iana" +}, + "application/vnd.motorola.flexsuite.wem": { + source: "iana" +}, + "application/vnd.motorola.iprm": { + source: "iana" +}, + "application/vnd.mozilla.xul+xml": { + source: "iana", + compressible: true, + extensions: [ + "xul" + ] +}, + "application/vnd.ms-3mfdocument": { + source: "iana" +}, + "application/vnd.ms-artgalry": { + source: "iana", + extensions: [ + "cil" + ] +}, + "application/vnd.ms-asf": { + source: "iana" +}, + "application/vnd.ms-cab-compressed": { + source: "iana", + extensions: [ + "cab" + ] +}, + "application/vnd.ms-color.iccprofile": { + source: "apache" +}, + "application/vnd.ms-excel": { + source: "iana", + compressible: false, + extensions: [ + "xls", + "xlm", + "xla", + "xlc", + "xlt", + "xlw" + ] +}, + "application/vnd.ms-excel.addin.macroenabled.12": { + source: "iana", + extensions: [ + "xlam" + ] +}, + "application/vnd.ms-excel.sheet.binary.macroenabled.12": { + source: "iana", + extensions: [ + "xlsb" + ] +}, + "application/vnd.ms-excel.sheet.macroenabled.12": { + source: "iana", + extensions: [ + "xlsm" + ] +}, + "application/vnd.ms-excel.template.macroenabled.12": { + source: "iana", + extensions: [ + "xltm" + ] +}, + "application/vnd.ms-fontobject": { + source: "iana", + compressible: true, + extensions: [ + "eot" + ] +}, + "application/vnd.ms-htmlhelp": { + source: "iana", + extensions: [ + "chm" + ] +}, + "application/vnd.ms-ims": { + source: "iana", + extensions: [ + "ims" + ] +}, + "application/vnd.ms-lrm": { + source: "iana", + extensions: [ + "lrm" + ] +}, + "application/vnd.ms-office.activex+xml": { + source: "iana", + compressible: true +}, + "application/vnd.ms-officetheme": { + source: "iana", + extensions: [ + "thmx" + ] +}, + "application/vnd.ms-opentype": { + source: "apache", + compressible: true +}, + "application/vnd.ms-outlook": { + compressible: false, + extensions: [ + "msg" + ] +}, + "application/vnd.ms-package.obfuscated-opentype": { + source: "apache" +}, + "application/vnd.ms-pki.seccat": { + source: "apache", + extensions: [ + "cat" + ] +}, + "application/vnd.ms-pki.stl": { + source: "apache", + extensions: [ + "stl" + ] +}, + "application/vnd.ms-playready.initiator+xml": { + source: "iana", + compressible: true +}, + "application/vnd.ms-powerpoint": { + source: "iana", + compressible: false, + extensions: [ + "ppt", + "pps", + "pot" + ] +}, + "application/vnd.ms-powerpoint.addin.macroenabled.12": { + source: "iana", + extensions: [ + "ppam" + ] +}, + "application/vnd.ms-powerpoint.presentation.macroenabled.12": { + source: "iana", + extensions: [ + "pptm" + ] +}, + "application/vnd.ms-powerpoint.slide.macroenabled.12": { + source: "iana", + extensions: [ + "sldm" + ] +}, + "application/vnd.ms-powerpoint.slideshow.macroenabled.12": { + source: "iana", + extensions: [ + "ppsm" + ] +}, + "application/vnd.ms-powerpoint.template.macroenabled.12": { + source: "iana", + extensions: [ + "potm" + ] +}, + "application/vnd.ms-printdevicecapabilities+xml": { + source: "iana", + compressible: true +}, + "application/vnd.ms-printing.printticket+xml": { + source: "apache", + compressible: true +}, + "application/vnd.ms-printschematicket+xml": { + source: "iana", + compressible: true +}, + "application/vnd.ms-project": { + source: "iana", + extensions: [ + "mpp", + "mpt" + ] +}, + "application/vnd.ms-tnef": { + source: "iana" +}, + "application/vnd.ms-windows.devicepairing": { + source: "iana" +}, + "application/vnd.ms-windows.nwprinting.oob": { + source: "iana" +}, + "application/vnd.ms-windows.printerpairing": { + source: "iana" +}, + "application/vnd.ms-windows.wsd.oob": { + source: "iana" +}, + "application/vnd.ms-wmdrm.lic-chlg-req": { + source: "iana" +}, + "application/vnd.ms-wmdrm.lic-resp": { + source: "iana" +}, + "application/vnd.ms-wmdrm.meter-chlg-req": { + source: "iana" +}, + "application/vnd.ms-wmdrm.meter-resp": { + source: "iana" +}, + "application/vnd.ms-word.document.macroenabled.12": { + source: "iana", + extensions: [ + "docm" + ] +}, + "application/vnd.ms-word.template.macroenabled.12": { + source: "iana", + extensions: [ + "dotm" + ] +}, + "application/vnd.ms-works": { + source: "iana", + extensions: [ + "wps", + "wks", + "wcm", + "wdb" + ] +}, + "application/vnd.ms-wpl": { + source: "iana", + extensions: [ + "wpl" + ] +}, + "application/vnd.ms-xpsdocument": { + source: "iana", + compressible: false, + extensions: [ + "xps" + ] +}, + "application/vnd.msa-disk-image": { + source: "iana" +}, + "application/vnd.mseq": { + source: "iana", + extensions: [ + "mseq" + ] +}, + "application/vnd.msign": { + source: "iana" +}, + "application/vnd.multiad.creator": { + source: "iana" +}, + "application/vnd.multiad.creator.cif": { + source: "iana" +}, + "application/vnd.music-niff": { + source: "iana" +}, + "application/vnd.musician": { + source: "iana", + extensions: [ + "mus" + ] +}, + "application/vnd.muvee.style": { + source: "iana", + extensions: [ + "msty" + ] +}, + "application/vnd.mynfc": { + source: "iana", + extensions: [ + "taglet" + ] +}, + "application/vnd.nacamar.ybrid+json": { + source: "iana", + compressible: true +}, + "application/vnd.ncd.control": { + source: "iana" +}, + "application/vnd.ncd.reference": { + source: "iana" +}, + "application/vnd.nearst.inv+json": { + source: "iana", + compressible: true +}, + "application/vnd.nebumind.line": { + source: "iana" +}, + "application/vnd.nervana": { + source: "iana" +}, + "application/vnd.netfpx": { + source: "iana" +}, + "application/vnd.neurolanguage.nlu": { + source: "iana", + extensions: [ + "nlu" + ] +}, + "application/vnd.nimn": { + source: "iana" +}, + "application/vnd.nintendo.nitro.rom": { + source: "iana" +}, + "application/vnd.nintendo.snes.rom": { + source: "iana" +}, + "application/vnd.nitf": { + source: "iana", + extensions: [ + "ntf", + "nitf" + ] +}, + "application/vnd.noblenet-directory": { + source: "iana", + extensions: [ + "nnd" + ] +}, + "application/vnd.noblenet-sealer": { + source: "iana", + extensions: [ + "nns" + ] +}, + "application/vnd.noblenet-web": { + source: "iana", + extensions: [ + "nnw" + ] +}, + "application/vnd.nokia.catalogs": { + source: "iana" +}, + "application/vnd.nokia.conml+wbxml": { + source: "iana" +}, + "application/vnd.nokia.conml+xml": { + source: "iana", + compressible: true +}, + "application/vnd.nokia.iptv.config+xml": { + source: "iana", + compressible: true +}, + "application/vnd.nokia.isds-radio-presets": { + source: "iana" +}, + "application/vnd.nokia.landmark+wbxml": { + source: "iana" +}, + "application/vnd.nokia.landmark+xml": { + source: "iana", + compressible: true +}, + "application/vnd.nokia.landmarkcollection+xml": { + source: "iana", + compressible: true +}, + "application/vnd.nokia.n-gage.ac+xml": { + source: "iana", + compressible: true, + extensions: [ + "ac" + ] +}, + "application/vnd.nokia.n-gage.data": { + source: "iana", + extensions: [ + "ngdat" + ] +}, + "application/vnd.nokia.n-gage.symbian.install": { + source: "iana", + extensions: [ + "n-gage" + ] +}, + "application/vnd.nokia.ncd": { + source: "iana" +}, + "application/vnd.nokia.pcd+wbxml": { + source: "iana" +}, + "application/vnd.nokia.pcd+xml": { + source: "iana", + compressible: true +}, + "application/vnd.nokia.radio-preset": { + source: "iana", + extensions: [ + "rpst" + ] +}, + "application/vnd.nokia.radio-presets": { + source: "iana", + extensions: [ + "rpss" + ] +}, + "application/vnd.novadigm.edm": { + source: "iana", + extensions: [ + "edm" + ] +}, + "application/vnd.novadigm.edx": { + source: "iana", + extensions: [ + "edx" + ] +}, + "application/vnd.novadigm.ext": { + source: "iana", + extensions: [ + "ext" + ] +}, + "application/vnd.ntt-local.content-share": { + source: "iana" +}, + "application/vnd.ntt-local.file-transfer": { + source: "iana" +}, + "application/vnd.ntt-local.ogw_remote-access": { + source: "iana" +}, + "application/vnd.ntt-local.sip-ta_remote": { + source: "iana" +}, + "application/vnd.ntt-local.sip-ta_tcp_stream": { + source: "iana" +}, + "application/vnd.oasis.opendocument.chart": { + source: "iana", + extensions: [ + "odc" + ] +}, + "application/vnd.oasis.opendocument.chart-template": { + source: "iana", + extensions: [ + "otc" + ] +}, + "application/vnd.oasis.opendocument.database": { + source: "iana", + extensions: [ + "odb" + ] +}, + "application/vnd.oasis.opendocument.formula": { + source: "iana", + extensions: [ + "odf" + ] +}, + "application/vnd.oasis.opendocument.formula-template": { + source: "iana", + extensions: [ + "odft" + ] +}, + "application/vnd.oasis.opendocument.graphics": { + source: "iana", + compressible: false, + extensions: [ + "odg" + ] +}, + "application/vnd.oasis.opendocument.graphics-template": { + source: "iana", + extensions: [ + "otg" + ] +}, + "application/vnd.oasis.opendocument.image": { + source: "iana", + extensions: [ + "odi" + ] +}, + "application/vnd.oasis.opendocument.image-template": { + source: "iana", + extensions: [ + "oti" + ] +}, + "application/vnd.oasis.opendocument.presentation": { + source: "iana", + compressible: false, + extensions: [ + "odp" + ] +}, + "application/vnd.oasis.opendocument.presentation-template": { + source: "iana", + extensions: [ + "otp" + ] +}, + "application/vnd.oasis.opendocument.spreadsheet": { + source: "iana", + compressible: false, + extensions: [ + "ods" + ] +}, + "application/vnd.oasis.opendocument.spreadsheet-template": { + source: "iana", + extensions: [ + "ots" + ] +}, + "application/vnd.oasis.opendocument.text": { + source: "iana", + compressible: false, + extensions: [ + "odt" + ] +}, + "application/vnd.oasis.opendocument.text-master": { + source: "iana", + extensions: [ + "odm" + ] +}, + "application/vnd.oasis.opendocument.text-template": { + source: "iana", + extensions: [ + "ott" + ] +}, + "application/vnd.oasis.opendocument.text-web": { + source: "iana", + extensions: [ + "oth" + ] +}, + "application/vnd.obn": { + source: "iana" +}, + "application/vnd.ocf+cbor": { + source: "iana" +}, + "application/vnd.oci.image.manifest.v1+json": { + source: "iana", + compressible: true +}, + "application/vnd.oftn.l10n+json": { + source: "iana", + compressible: true +}, + "application/vnd.oipf.contentaccessdownload+xml": { + source: "iana", + compressible: true +}, + "application/vnd.oipf.contentaccessstreaming+xml": { + source: "iana", + compressible: true +}, + "application/vnd.oipf.cspg-hexbinary": { + source: "iana" +}, + "application/vnd.oipf.dae.svg+xml": { + source: "iana", + compressible: true +}, + "application/vnd.oipf.dae.xhtml+xml": { + source: "iana", + compressible: true +}, + "application/vnd.oipf.mippvcontrolmessage+xml": { + source: "iana", + compressible: true +}, + "application/vnd.oipf.pae.gem": { + source: "iana" +}, + "application/vnd.oipf.spdiscovery+xml": { + source: "iana", + compressible: true +}, + "application/vnd.oipf.spdlist+xml": { + source: "iana", + compressible: true +}, + "application/vnd.oipf.ueprofile+xml": { + source: "iana", + compressible: true +}, + "application/vnd.oipf.userprofile+xml": { + source: "iana", + compressible: true +}, + "application/vnd.olpc-sugar": { + source: "iana", + extensions: [ + "xo" + ] +}, + "application/vnd.oma-scws-config": { + source: "iana" +}, + "application/vnd.oma-scws-http-request": { + source: "iana" +}, + "application/vnd.oma-scws-http-response": { + source: "iana" +}, + "application/vnd.oma.bcast.associated-procedure-parameter+xml": { + source: "iana", + compressible: true +}, + "application/vnd.oma.bcast.drm-trigger+xml": { + source: "iana", + compressible: true +}, + "application/vnd.oma.bcast.imd+xml": { + source: "iana", + compressible: true +}, + "application/vnd.oma.bcast.ltkm": { + source: "iana" +}, + "application/vnd.oma.bcast.notification+xml": { + source: "iana", + compressible: true +}, + "application/vnd.oma.bcast.provisioningtrigger": { + source: "iana" +}, + "application/vnd.oma.bcast.sgboot": { + source: "iana" +}, + "application/vnd.oma.bcast.sgdd+xml": { + source: "iana", + compressible: true +}, + "application/vnd.oma.bcast.sgdu": { + source: "iana" +}, + "application/vnd.oma.bcast.simple-symbol-container": { + source: "iana" +}, + "application/vnd.oma.bcast.smartcard-trigger+xml": { + source: "iana", + compressible: true +}, + "application/vnd.oma.bcast.sprov+xml": { + source: "iana", + compressible: true +}, + "application/vnd.oma.bcast.stkm": { + source: "iana" +}, + "application/vnd.oma.cab-address-book+xml": { + source: "iana", + compressible: true +}, + "application/vnd.oma.cab-feature-handler+xml": { + source: "iana", + compressible: true +}, + "application/vnd.oma.cab-pcc+xml": { + source: "iana", + compressible: true +}, + "application/vnd.oma.cab-subs-invite+xml": { + source: "iana", + compressible: true +}, + "application/vnd.oma.cab-user-prefs+xml": { + source: "iana", + compressible: true +}, + "application/vnd.oma.dcd": { + source: "iana" +}, + "application/vnd.oma.dcdc": { + source: "iana" +}, + "application/vnd.oma.dd2+xml": { + source: "iana", + compressible: true, + extensions: [ + "dd2" + ] +}, + "application/vnd.oma.drm.risd+xml": { + source: "iana", + compressible: true +}, + "application/vnd.oma.group-usage-list+xml": { + source: "iana", + compressible: true +}, + "application/vnd.oma.lwm2m+cbor": { + source: "iana" +}, + "application/vnd.oma.lwm2m+json": { + source: "iana", + compressible: true +}, + "application/vnd.oma.lwm2m+tlv": { + source: "iana" +}, + "application/vnd.oma.pal+xml": { + source: "iana", + compressible: true +}, + "application/vnd.oma.poc.detailed-progress-report+xml": { + source: "iana", + compressible: true +}, + "application/vnd.oma.poc.final-report+xml": { + source: "iana", + compressible: true +}, + "application/vnd.oma.poc.groups+xml": { + source: "iana", + compressible: true +}, + "application/vnd.oma.poc.invocation-descriptor+xml": { + source: "iana", + compressible: true +}, + "application/vnd.oma.poc.optimized-progress-report+xml": { + source: "iana", + compressible: true +}, + "application/vnd.oma.push": { + source: "iana" +}, + "application/vnd.oma.scidm.messages+xml": { + source: "iana", + compressible: true +}, + "application/vnd.oma.xcap-directory+xml": { + source: "iana", + compressible: true +}, + "application/vnd.omads-email+xml": { + source: "iana", + charset: "UTF-8", + compressible: true +}, + "application/vnd.omads-file+xml": { + source: "iana", + charset: "UTF-8", + compressible: true +}, + "application/vnd.omads-folder+xml": { + source: "iana", + charset: "UTF-8", + compressible: true +}, + "application/vnd.omaloc-supl-init": { + source: "iana" +}, + "application/vnd.onepager": { + source: "iana" +}, + "application/vnd.onepagertamp": { + source: "iana" +}, + "application/vnd.onepagertamx": { + source: "iana" +}, + "application/vnd.onepagertat": { + source: "iana" +}, + "application/vnd.onepagertatp": { + source: "iana" +}, + "application/vnd.onepagertatx": { + source: "iana" +}, + "application/vnd.openblox.game+xml": { + source: "iana", + compressible: true, + extensions: [ + "obgx" + ] +}, + "application/vnd.openblox.game-binary": { + source: "iana" +}, + "application/vnd.openeye.oeb": { + source: "iana" +}, + "application/vnd.openofficeorg.extension": { + source: "apache", + extensions: [ + "oxt" + ] +}, + "application/vnd.openstreetmap.data+xml": { + source: "iana", + compressible: true, + extensions: [ + "osm" + ] +}, + "application/vnd.opentimestamps.ots": { + source: "iana" +}, + "application/vnd.openxmlformats-officedocument.custom-properties+xml": { + source: "iana", + compressible: true +}, + "application/vnd.openxmlformats-officedocument.customxmlproperties+xml": { + source: "iana", + compressible: true +}, + "application/vnd.openxmlformats-officedocument.drawing+xml": { + source: "iana", + compressible: true +}, + "application/vnd.openxmlformats-officedocument.drawingml.chart+xml": { + source: "iana", + compressible: true +}, + "application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml": { + source: "iana", + compressible: true +}, + "application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml": { + source: "iana", + compressible: true +}, + "application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml": { + source: "iana", + compressible: true +}, + "application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml": { + source: "iana", + compressible: true +}, + "application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml": { + source: "iana", + compressible: true +}, + "application/vnd.openxmlformats-officedocument.extended-properties+xml": { + source: "iana", + compressible: true +}, + "application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml": { + source: "iana", + compressible: true +}, + "application/vnd.openxmlformats-officedocument.presentationml.comments+xml": { + source: "iana", + compressible: true +}, + "application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml": { + source: "iana", + compressible: true +}, + "application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml": { + source: "iana", + compressible: true +}, + "application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml": { + source: "iana", + compressible: true +}, + "application/vnd.openxmlformats-officedocument.presentationml.presentation": { + source: "iana", + compressible: false, + extensions: [ + "pptx" + ] +}, + "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml": { + source: "iana", + compressible: true +}, + "application/vnd.openxmlformats-officedocument.presentationml.presprops+xml": { + source: "iana", + compressible: true +}, + "application/vnd.openxmlformats-officedocument.presentationml.slide": { + source: "iana", + extensions: [ + "sldx" + ] +}, + "application/vnd.openxmlformats-officedocument.presentationml.slide+xml": { + source: "iana", + compressible: true +}, + "application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml": { + source: "iana", + compressible: true +}, + "application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml": { + source: "iana", + compressible: true +}, + "application/vnd.openxmlformats-officedocument.presentationml.slideshow": { + source: "iana", + extensions: [ + "ppsx" + ] +}, + "application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml": { + source: "iana", + compressible: true +}, + "application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml": { + source: "iana", + compressible: true +}, + "application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml": { + source: "iana", + compressible: true +}, + "application/vnd.openxmlformats-officedocument.presentationml.tags+xml": { + source: "iana", + compressible: true +}, + "application/vnd.openxmlformats-officedocument.presentationml.template": { + source: "iana", + extensions: [ + "potx" + ] +}, + "application/vnd.openxmlformats-officedocument.presentationml.template.main+xml": { + source: "iana", + compressible: true +}, + "application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml": { + source: "iana", + compressible: true +}, + "application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml": { + source: "iana", + compressible: true +}, + "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml": { + source: "iana", + compressible: true +}, + "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml": { + source: "iana", + compressible: true +}, + "application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml": { + source: "iana", + compressible: true +}, + "application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml": { + source: "iana", + compressible: true +}, + "application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml": { + source: "iana", + compressible: true +}, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml": { + source: "iana", + compressible: true +}, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml": { + source: "iana", + compressible: true +}, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml": { + source: "iana", + compressible: true +}, + "application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml": { + source: "iana", + compressible: true +}, + "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml": { + source: "iana", + compressible: true +}, + "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml": { + source: "iana", + compressible: true +}, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml": { + source: "iana", + compressible: true +}, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": { + source: "iana", + compressible: false, + extensions: [ + "xlsx" + ] +}, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml": { + source: "iana", + compressible: true +}, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml": { + source: "iana", + compressible: true +}, + "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml": { + source: "iana", + compressible: true +}, + "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml": { + source: "iana", + compressible: true +}, + "application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml": { + source: "iana", + compressible: true +}, + "application/vnd.openxmlformats-officedocument.spreadsheetml.template": { + source: "iana", + extensions: [ + "xltx" + ] +}, + "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml": { + source: "iana", + compressible: true +}, + "application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml": { + source: "iana", + compressible: true +}, + "application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml": { + source: "iana", + compressible: true +}, + "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml": { + source: "iana", + compressible: true +}, + "application/vnd.openxmlformats-officedocument.theme+xml": { + source: "iana", + compressible: true +}, + "application/vnd.openxmlformats-officedocument.themeoverride+xml": { + source: "iana", + compressible: true +}, + "application/vnd.openxmlformats-officedocument.vmldrawing": { + source: "iana" +}, + "application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml": { + source: "iana", + compressible: true +}, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document": { + source: "iana", + compressible: false, + extensions: [ + "docx" + ] +}, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml": { + source: "iana", + compressible: true +}, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml": { + source: "iana", + compressible: true +}, + "application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml": { + source: "iana", + compressible: true +}, + "application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml": { + source: "iana", + compressible: true +}, + "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml": { + source: "iana", + compressible: true +}, + "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml": { + source: "iana", + compressible: true +}, + "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml": { + source: "iana", + compressible: true +}, + "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml": { + source: "iana", + compressible: true +}, + "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml": { + source: "iana", + compressible: true +}, + "application/vnd.openxmlformats-officedocument.wordprocessingml.template": { + source: "iana", + extensions: [ + "dotx" + ] +}, + "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml": { + source: "iana", + compressible: true +}, + "application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml": { + source: "iana", + compressible: true +}, + "application/vnd.openxmlformats-package.core-properties+xml": { + source: "iana", + compressible: true +}, + "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml": { + source: "iana", + compressible: true +}, + "application/vnd.openxmlformats-package.relationships+xml": { + source: "iana", + compressible: true +}, + "application/vnd.oracle.resource+json": { + source: "iana", + compressible: true +}, + "application/vnd.orange.indata": { + source: "iana" +}, + "application/vnd.osa.netdeploy": { + source: "iana" +}, + "application/vnd.osgeo.mapguide.package": { + source: "iana", + extensions: [ + "mgp" + ] +}, + "application/vnd.osgi.bundle": { + source: "iana" +}, + "application/vnd.osgi.dp": { + source: "iana", + extensions: [ + "dp" + ] +}, + "application/vnd.osgi.subsystem": { + source: "iana", + extensions: [ + "esa" + ] +}, + "application/vnd.otps.ct-kip+xml": { + source: "iana", + compressible: true +}, + "application/vnd.oxli.countgraph": { + source: "iana" +}, + "application/vnd.pagerduty+json": { + source: "iana", + compressible: true +}, + "application/vnd.palm": { + source: "iana", + extensions: [ + "pdb", + "pqa", + "oprc" + ] +}, + "application/vnd.panoply": { + source: "iana" +}, + "application/vnd.paos.xml": { + source: "iana" +}, + "application/vnd.patentdive": { + source: "iana" +}, + "application/vnd.patientecommsdoc": { + source: "iana" +}, + "application/vnd.pawaafile": { + source: "iana", + extensions: [ + "paw" + ] +}, + "application/vnd.pcos": { + source: "iana" +}, + "application/vnd.pg.format": { + source: "iana", + extensions: [ + "str" + ] +}, + "application/vnd.pg.osasli": { + source: "iana", + extensions: [ + "ei6" + ] +}, + "application/vnd.piaccess.application-licence": { + source: "iana" +}, + "application/vnd.picsel": { + source: "iana", + extensions: [ + "efif" + ] +}, + "application/vnd.pmi.widget": { + source: "iana", + extensions: [ + "wg" + ] +}, + "application/vnd.poc.group-advertisement+xml": { + source: "iana", + compressible: true +}, + "application/vnd.pocketlearn": { + source: "iana", + extensions: [ + "plf" + ] +}, + "application/vnd.powerbuilder6": { + source: "iana", + extensions: [ + "pbd" + ] +}, + "application/vnd.powerbuilder6-s": { + source: "iana" +}, + "application/vnd.powerbuilder7": { + source: "iana" +}, + "application/vnd.powerbuilder7-s": { + source: "iana" +}, + "application/vnd.powerbuilder75": { + source: "iana" +}, + "application/vnd.powerbuilder75-s": { + source: "iana" +}, + "application/vnd.preminet": { + source: "iana" +}, + "application/vnd.previewsystems.box": { + source: "iana", + extensions: [ + "box" + ] +}, + "application/vnd.proteus.magazine": { + source: "iana", + extensions: [ + "mgz" + ] +}, + "application/vnd.psfs": { + source: "iana" +}, + "application/vnd.publishare-delta-tree": { + source: "iana", + extensions: [ + "qps" + ] +}, + "application/vnd.pvi.ptid1": { + source: "iana", + extensions: [ + "ptid" + ] +}, + "application/vnd.pwg-multiplexed": { + source: "iana" +}, + "application/vnd.pwg-xhtml-print+xml": { + source: "iana", + compressible: true +}, + "application/vnd.qualcomm.brew-app-res": { + source: "iana" +}, + "application/vnd.quarantainenet": { + source: "iana" +}, + "application/vnd.quark.quarkxpress": { + source: "iana", + extensions: [ + "qxd", + "qxt", + "qwd", + "qwt", + "qxl", + "qxb" + ] +}, + "application/vnd.quobject-quoxdocument": { + source: "iana" +}, + "application/vnd.radisys.moml+xml": { + source: "iana", + compressible: true +}, + "application/vnd.radisys.msml+xml": { + source: "iana", + compressible: true +}, + "application/vnd.radisys.msml-audit+xml": { + source: "iana", + compressible: true +}, + "application/vnd.radisys.msml-audit-conf+xml": { + source: "iana", + compressible: true +}, + "application/vnd.radisys.msml-audit-conn+xml": { + source: "iana", + compressible: true +}, + "application/vnd.radisys.msml-audit-dialog+xml": { + source: "iana", + compressible: true +}, + "application/vnd.radisys.msml-audit-stream+xml": { + source: "iana", + compressible: true +}, + "application/vnd.radisys.msml-conf+xml": { + source: "iana", + compressible: true +}, + "application/vnd.radisys.msml-dialog+xml": { + source: "iana", + compressible: true +}, + "application/vnd.radisys.msml-dialog-base+xml": { + source: "iana", + compressible: true +}, + "application/vnd.radisys.msml-dialog-fax-detect+xml": { + source: "iana", + compressible: true +}, + "application/vnd.radisys.msml-dialog-fax-sendrecv+xml": { + source: "iana", + compressible: true +}, + "application/vnd.radisys.msml-dialog-group+xml": { + source: "iana", + compressible: true +}, + "application/vnd.radisys.msml-dialog-speech+xml": { + source: "iana", + compressible: true +}, + "application/vnd.radisys.msml-dialog-transform+xml": { + source: "iana", + compressible: true +}, + "application/vnd.rainstor.data": { + source: "iana" +}, + "application/vnd.rapid": { + source: "iana" +}, + "application/vnd.rar": { + source: "iana", + extensions: [ + "rar" + ] +}, + "application/vnd.realvnc.bed": { + source: "iana", + extensions: [ + "bed" + ] +}, + "application/vnd.recordare.musicxml": { + source: "iana", + extensions: [ + "mxl" + ] +}, + "application/vnd.recordare.musicxml+xml": { + source: "iana", + compressible: true, + extensions: [ + "musicxml" + ] +}, + "application/vnd.renlearn.rlprint": { + source: "iana" +}, + "application/vnd.resilient.logic": { + source: "iana" +}, + "application/vnd.restful+json": { + source: "iana", + compressible: true +}, + "application/vnd.rig.cryptonote": { + source: "iana", + extensions: [ + "cryptonote" + ] +}, + "application/vnd.rim.cod": { + source: "apache", + extensions: [ + "cod" + ] +}, + "application/vnd.rn-realmedia": { + source: "apache", + extensions: [ + "rm" + ] +}, + "application/vnd.rn-realmedia-vbr": { + source: "apache", + extensions: [ + "rmvb" + ] +}, + "application/vnd.route66.link66+xml": { + source: "iana", + compressible: true, + extensions: [ + "link66" + ] +}, + "application/vnd.rs-274x": { + source: "iana" +}, + "application/vnd.ruckus.download": { + source: "iana" +}, + "application/vnd.s3sms": { + source: "iana" +}, + "application/vnd.sailingtracker.track": { + source: "iana", + extensions: [ + "st" + ] +}, + "application/vnd.sar": { + source: "iana" +}, + "application/vnd.sbm.cid": { + source: "iana" +}, + "application/vnd.sbm.mid2": { + source: "iana" +}, + "application/vnd.scribus": { + source: "iana" +}, + "application/vnd.sealed.3df": { + source: "iana" +}, + "application/vnd.sealed.csf": { + source: "iana" +}, + "application/vnd.sealed.doc": { + source: "iana" +}, + "application/vnd.sealed.eml": { + source: "iana" +}, + "application/vnd.sealed.mht": { + source: "iana" +}, + "application/vnd.sealed.net": { + source: "iana" +}, + "application/vnd.sealed.ppt": { + source: "iana" +}, + "application/vnd.sealed.tiff": { + source: "iana" +}, + "application/vnd.sealed.xls": { + source: "iana" +}, + "application/vnd.sealedmedia.softseal.html": { + source: "iana" +}, + "application/vnd.sealedmedia.softseal.pdf": { + source: "iana" +}, + "application/vnd.seemail": { + source: "iana", + extensions: [ + "see" + ] +}, + "application/vnd.seis+json": { + source: "iana", + compressible: true +}, + "application/vnd.sema": { + source: "iana", + extensions: [ + "sema" + ] +}, + "application/vnd.semd": { + source: "iana", + extensions: [ + "semd" + ] +}, + "application/vnd.semf": { + source: "iana", + extensions: [ + "semf" + ] +}, + "application/vnd.shade-save-file": { + source: "iana" +}, + "application/vnd.shana.informed.formdata": { + source: "iana", + extensions: [ + "ifm" + ] +}, + "application/vnd.shana.informed.formtemplate": { + source: "iana", + extensions: [ + "itp" + ] +}, + "application/vnd.shana.informed.interchange": { + source: "iana", + extensions: [ + "iif" + ] +}, + "application/vnd.shana.informed.package": { + source: "iana", + extensions: [ + "ipk" + ] +}, + "application/vnd.shootproof+json": { + source: "iana", + compressible: true +}, + "application/vnd.shopkick+json": { + source: "iana", + compressible: true +}, + "application/vnd.shp": { + source: "iana" +}, + "application/vnd.shx": { + source: "iana" +}, + "application/vnd.sigrok.session": { + source: "iana" +}, + "application/vnd.simtech-mindmapper": { + source: "iana", + extensions: [ + "twd", + "twds" + ] +}, + "application/vnd.siren+json": { + source: "iana", + compressible: true +}, + "application/vnd.smaf": { + source: "iana", + extensions: [ + "mmf" + ] +}, + "application/vnd.smart.notebook": { + source: "iana" +}, + "application/vnd.smart.teacher": { + source: "iana", + extensions: [ + "teacher" + ] +}, + "application/vnd.snesdev-page-table": { + source: "iana" +}, + "application/vnd.software602.filler.form+xml": { + source: "iana", + compressible: true, + extensions: [ + "fo" + ] +}, + "application/vnd.software602.filler.form-xml-zip": { + source: "iana" +}, + "application/vnd.solent.sdkm+xml": { + source: "iana", + compressible: true, + extensions: [ + "sdkm", + "sdkd" + ] +}, + "application/vnd.spotfire.dxp": { + source: "iana", + extensions: [ + "dxp" + ] +}, + "application/vnd.spotfire.sfs": { + source: "iana", + extensions: [ + "sfs" + ] +}, + "application/vnd.sqlite3": { + source: "iana" +}, + "application/vnd.sss-cod": { + source: "iana" +}, + "application/vnd.sss-dtf": { + source: "iana" +}, + "application/vnd.sss-ntf": { + source: "iana" +}, + "application/vnd.stardivision.calc": { + source: "apache", + extensions: [ + "sdc" + ] +}, + "application/vnd.stardivision.draw": { + source: "apache", + extensions: [ + "sda" + ] +}, + "application/vnd.stardivision.impress": { + source: "apache", + extensions: [ + "sdd" + ] +}, + "application/vnd.stardivision.math": { + source: "apache", + extensions: [ + "smf" + ] +}, + "application/vnd.stardivision.writer": { + source: "apache", + extensions: [ + "sdw", + "vor" + ] +}, + "application/vnd.stardivision.writer-global": { + source: "apache", + extensions: [ + "sgl" + ] +}, + "application/vnd.stepmania.package": { + source: "iana", + extensions: [ + "smzip" + ] +}, + "application/vnd.stepmania.stepchart": { + source: "iana", + extensions: [ + "sm" + ] +}, + "application/vnd.street-stream": { + source: "iana" +}, + "application/vnd.sun.wadl+xml": { + source: "iana", + compressible: true, + extensions: [ + "wadl" + ] +}, + "application/vnd.sun.xml.calc": { + source: "apache", + extensions: [ + "sxc" + ] +}, + "application/vnd.sun.xml.calc.template": { + source: "apache", + extensions: [ + "stc" + ] +}, + "application/vnd.sun.xml.draw": { + source: "apache", + extensions: [ + "sxd" + ] +}, + "application/vnd.sun.xml.draw.template": { + source: "apache", + extensions: [ + "std" + ] +}, + "application/vnd.sun.xml.impress": { + source: "apache", + extensions: [ + "sxi" + ] +}, + "application/vnd.sun.xml.impress.template": { + source: "apache", + extensions: [ + "sti" + ] +}, + "application/vnd.sun.xml.math": { + source: "apache", + extensions: [ + "sxm" + ] +}, + "application/vnd.sun.xml.writer": { + source: "apache", + extensions: [ + "sxw" + ] +}, + "application/vnd.sun.xml.writer.global": { + source: "apache", + extensions: [ + "sxg" + ] +}, + "application/vnd.sun.xml.writer.template": { + source: "apache", + extensions: [ + "stw" + ] +}, + "application/vnd.sus-calendar": { + source: "iana", + extensions: [ + "sus", + "susp" + ] +}, + "application/vnd.svd": { + source: "iana", + extensions: [ + "svd" + ] +}, + "application/vnd.swiftview-ics": { + source: "iana" +}, + "application/vnd.sycle+xml": { + source: "iana", + compressible: true +}, + "application/vnd.syft+json": { + source: "iana", + compressible: true +}, + "application/vnd.symbian.install": { + source: "apache", + extensions: [ + "sis", + "sisx" + ] +}, + "application/vnd.syncml+xml": { + source: "iana", + charset: "UTF-8", + compressible: true, + extensions: [ + "xsm" + ] +}, + "application/vnd.syncml.dm+wbxml": { + source: "iana", + charset: "UTF-8", + extensions: [ + "bdm" + ] +}, + "application/vnd.syncml.dm+xml": { + source: "iana", + charset: "UTF-8", + compressible: true, + extensions: [ + "xdm" + ] +}, + "application/vnd.syncml.dm.notification": { + source: "iana" +}, + "application/vnd.syncml.dmddf+wbxml": { + source: "iana" +}, + "application/vnd.syncml.dmddf+xml": { + source: "iana", + charset: "UTF-8", + compressible: true, + extensions: [ + "ddf" + ] +}, + "application/vnd.syncml.dmtnds+wbxml": { + source: "iana" +}, + "application/vnd.syncml.dmtnds+xml": { + source: "iana", + charset: "UTF-8", + compressible: true +}, + "application/vnd.syncml.ds.notification": { + source: "iana" +}, + "application/vnd.tableschema+json": { + source: "iana", + compressible: true +}, + "application/vnd.tao.intent-module-archive": { + source: "iana", + extensions: [ + "tao" + ] +}, + "application/vnd.tcpdump.pcap": { + source: "iana", + extensions: [ + "pcap", + "cap", + "dmp" + ] +}, + "application/vnd.think-cell.ppttc+json": { + source: "iana", + compressible: true +}, + "application/vnd.tmd.mediaflex.api+xml": { + source: "iana", + compressible: true +}, + "application/vnd.tml": { + source: "iana" +}, + "application/vnd.tmobile-livetv": { + source: "iana", + extensions: [ + "tmo" + ] +}, + "application/vnd.tri.onesource": { + source: "iana" +}, + "application/vnd.trid.tpt": { + source: "iana", + extensions: [ + "tpt" + ] +}, + "application/vnd.triscape.mxs": { + source: "iana", + extensions: [ + "mxs" + ] +}, + "application/vnd.trueapp": { + source: "iana", + extensions: [ + "tra" + ] +}, + "application/vnd.truedoc": { + source: "iana" +}, + "application/vnd.ubisoft.webplayer": { + source: "iana" +}, + "application/vnd.ufdl": { + source: "iana", + extensions: [ + "ufd", + "ufdl" + ] +}, + "application/vnd.uiq.theme": { + source: "iana", + extensions: [ + "utz" + ] +}, + "application/vnd.umajin": { + source: "iana", + extensions: [ + "umj" + ] +}, + "application/vnd.unity": { + source: "iana", + extensions: [ + "unityweb" + ] +}, + "application/vnd.uoml+xml": { + source: "iana", + compressible: true, + extensions: [ + "uoml" + ] +}, + "application/vnd.uplanet.alert": { + source: "iana" +}, + "application/vnd.uplanet.alert-wbxml": { + source: "iana" +}, + "application/vnd.uplanet.bearer-choice": { + source: "iana" +}, + "application/vnd.uplanet.bearer-choice-wbxml": { + source: "iana" +}, + "application/vnd.uplanet.cacheop": { + source: "iana" +}, + "application/vnd.uplanet.cacheop-wbxml": { + source: "iana" +}, + "application/vnd.uplanet.channel": { + source: "iana" +}, + "application/vnd.uplanet.channel-wbxml": { + source: "iana" +}, + "application/vnd.uplanet.list": { + source: "iana" +}, + "application/vnd.uplanet.list-wbxml": { + source: "iana" +}, + "application/vnd.uplanet.listcmd": { + source: "iana" +}, + "application/vnd.uplanet.listcmd-wbxml": { + source: "iana" +}, + "application/vnd.uplanet.signal": { + source: "iana" +}, + "application/vnd.uri-map": { + source: "iana" +}, + "application/vnd.valve.source.material": { + source: "iana" +}, + "application/vnd.vcx": { + source: "iana", + extensions: [ + "vcx" + ] +}, + "application/vnd.vd-study": { + source: "iana" +}, + "application/vnd.vectorworks": { + source: "iana" +}, + "application/vnd.vel+json": { + source: "iana", + compressible: true +}, + "application/vnd.verimatrix.vcas": { + source: "iana" +}, + "application/vnd.veritone.aion+json": { + source: "iana", + compressible: true +}, + "application/vnd.veryant.thin": { + source: "iana" +}, + "application/vnd.ves.encrypted": { + source: "iana" +}, + "application/vnd.vidsoft.vidconference": { + source: "iana" +}, + "application/vnd.visio": { + source: "iana", + extensions: [ + "vsd", + "vst", + "vss", + "vsw" + ] +}, + "application/vnd.visionary": { + source: "iana", + extensions: [ + "vis" + ] +}, + "application/vnd.vividence.scriptfile": { + source: "iana" +}, + "application/vnd.vsf": { + source: "iana", + extensions: [ + "vsf" + ] +}, + "application/vnd.wap.sic": { + source: "iana" +}, + "application/vnd.wap.slc": { + source: "iana" +}, + "application/vnd.wap.wbxml": { + source: "iana", + charset: "UTF-8", + extensions: [ + "wbxml" + ] +}, + "application/vnd.wap.wmlc": { + source: "iana", + extensions: [ + "wmlc" + ] +}, + "application/vnd.wap.wmlscriptc": { + source: "iana", + extensions: [ + "wmlsc" + ] +}, + "application/vnd.webturbo": { + source: "iana", + extensions: [ + "wtb" + ] +}, + "application/vnd.wfa.dpp": { + source: "iana" +}, + "application/vnd.wfa.p2p": { + source: "iana" +}, + "application/vnd.wfa.wsc": { + source: "iana" +}, + "application/vnd.windows.devicepairing": { + source: "iana" +}, + "application/vnd.wmc": { + source: "iana" +}, + "application/vnd.wmf.bootstrap": { + source: "iana" +}, + "application/vnd.wolfram.mathematica": { + source: "iana" +}, + "application/vnd.wolfram.mathematica.package": { + source: "iana" +}, + "application/vnd.wolfram.player": { + source: "iana", + extensions: [ + "nbp" + ] +}, + "application/vnd.wordperfect": { + source: "iana", + extensions: [ + "wpd" + ] +}, + "application/vnd.wqd": { + source: "iana", + extensions: [ + "wqd" + ] +}, + "application/vnd.wrq-hp3000-labelled": { + source: "iana" +}, + "application/vnd.wt.stf": { + source: "iana", + extensions: [ + "stf" + ] +}, + "application/vnd.wv.csp+wbxml": { + source: "iana" +}, + "application/vnd.wv.csp+xml": { + source: "iana", + compressible: true +}, + "application/vnd.wv.ssp+xml": { + source: "iana", + compressible: true +}, + "application/vnd.xacml+json": { + source: "iana", + compressible: true +}, + "application/vnd.xara": { + source: "iana", + extensions: [ + "xar" + ] +}, + "application/vnd.xfdl": { + source: "iana", + extensions: [ + "xfdl" + ] +}, + "application/vnd.xfdl.webform": { + source: "iana" +}, + "application/vnd.xmi+xml": { + source: "iana", + compressible: true +}, + "application/vnd.xmpie.cpkg": { + source: "iana" +}, + "application/vnd.xmpie.dpkg": { + source: "iana" +}, + "application/vnd.xmpie.plan": { + source: "iana" +}, + "application/vnd.xmpie.ppkg": { + source: "iana" +}, + "application/vnd.xmpie.xlim": { + source: "iana" +}, + "application/vnd.yamaha.hv-dic": { + source: "iana", + extensions: [ + "hvd" + ] +}, + "application/vnd.yamaha.hv-script": { + source: "iana", + extensions: [ + "hvs" + ] +}, + "application/vnd.yamaha.hv-voice": { + source: "iana", + extensions: [ + "hvp" + ] +}, + "application/vnd.yamaha.openscoreformat": { + source: "iana", + extensions: [ + "osf" + ] +}, + "application/vnd.yamaha.openscoreformat.osfpvg+xml": { + source: "iana", + compressible: true, + extensions: [ + "osfpvg" + ] +}, + "application/vnd.yamaha.remote-setup": { + source: "iana" +}, + "application/vnd.yamaha.smaf-audio": { + source: "iana", + extensions: [ + "saf" + ] +}, + "application/vnd.yamaha.smaf-phrase": { + source: "iana", + extensions: [ + "spf" + ] +}, + "application/vnd.yamaha.through-ngn": { + source: "iana" +}, + "application/vnd.yamaha.tunnel-udpencap": { + source: "iana" +}, + "application/vnd.yaoweme": { + source: "iana" +}, + "application/vnd.yellowriver-custom-menu": { + source: "iana", + extensions: [ + "cmp" + ] +}, + "application/vnd.youtube.yt": { + source: "iana" +}, + "application/vnd.zul": { + source: "iana", + extensions: [ + "zir", + "zirz" + ] +}, + "application/vnd.zzazz.deck+xml": { + source: "iana", + compressible: true, + extensions: [ + "zaz" + ] +}, + "application/voicexml+xml": { + source: "iana", + compressible: true, + extensions: [ + "vxml" + ] +}, + "application/voucher-cms+json": { + source: "iana", + compressible: true +}, + "application/vq-rtcpxr": { + source: "iana" +}, + "application/wasm": { + source: "iana", + compressible: true, + extensions: [ + "wasm" + ] +}, + "application/watcherinfo+xml": { + source: "iana", + compressible: true, + extensions: [ + "wif" + ] +}, + "application/webpush-options+json": { + source: "iana", + compressible: true +}, + "application/whoispp-query": { + source: "iana" +}, + "application/whoispp-response": { + source: "iana" +}, + "application/widget": { + source: "iana", + extensions: [ + "wgt" + ] +}, + "application/winhlp": { + source: "apache", + extensions: [ + "hlp" + ] +}, + "application/wita": { + source: "iana" +}, + "application/wordperfect5.1": { + source: "iana" +}, + "application/wsdl+xml": { + source: "iana", + compressible: true, + extensions: [ + "wsdl" + ] +}, + "application/wspolicy+xml": { + source: "iana", + compressible: true, + extensions: [ + "wspolicy" + ] +}, + "application/x-7z-compressed": { + source: "apache", + compressible: false, + extensions: [ + "7z" + ] +}, + "application/x-abiword": { + source: "apache", + extensions: [ + "abw" + ] +}, + "application/x-ace-compressed": { + source: "apache", + extensions: [ + "ace" + ] +}, + "application/x-amf": { + source: "apache" +}, + "application/x-apple-diskimage": { + source: "apache", + extensions: [ + "dmg" + ] +}, + "application/x-arj": { + compressible: false, + extensions: [ + "arj" + ] +}, + "application/x-authorware-bin": { + source: "apache", + extensions: [ + "aab", + "x32", + "u32", + "vox" + ] +}, + "application/x-authorware-map": { + source: "apache", + extensions: [ + "aam" + ] +}, + "application/x-authorware-seg": { + source: "apache", + extensions: [ + "aas" + ] +}, + "application/x-bcpio": { + source: "apache", + extensions: [ + "bcpio" + ] +}, + "application/x-bdoc": { + compressible: false, + extensions: [ + "bdoc" + ] +}, + "application/x-bittorrent": { + source: "apache", + extensions: [ + "torrent" + ] +}, + "application/x-blorb": { + source: "apache", + extensions: [ + "blb", + "blorb" + ] +}, + "application/x-bzip": { + source: "apache", + compressible: false, + extensions: [ + "bz" + ] +}, + "application/x-bzip2": { + source: "apache", + compressible: false, + extensions: [ + "bz2", + "boz" + ] +}, + "application/x-cbr": { + source: "apache", + extensions: [ + "cbr", + "cba", + "cbt", + "cbz", + "cb7" + ] +}, + "application/x-cdlink": { + source: "apache", + extensions: [ + "vcd" + ] +}, + "application/x-cfs-compressed": { + source: "apache", + extensions: [ + "cfs" + ] +}, + "application/x-chat": { + source: "apache", + extensions: [ + "chat" + ] +}, + "application/x-chess-pgn": { + source: "apache", + extensions: [ + "pgn" + ] +}, + "application/x-chrome-extension": { + extensions: [ + "crx" + ] +}, + "application/x-cocoa": { + source: "nginx", + extensions: [ + "cco" + ] +}, + "application/x-compress": { + source: "apache" +}, + "application/x-conference": { + source: "apache", + extensions: [ + "nsc" + ] +}, + "application/x-cpio": { + source: "apache", + extensions: [ + "cpio" + ] +}, + "application/x-csh": { + source: "apache", + extensions: [ + "csh" + ] +}, + "application/x-deb": { + compressible: false +}, + "application/x-debian-package": { + source: "apache", + extensions: [ + "deb", + "udeb" + ] +}, + "application/x-dgc-compressed": { + source: "apache", + extensions: [ + "dgc" + ] +}, + "application/x-director": { + source: "apache", + extensions: [ + "dir", + "dcr", + "dxr", + "cst", + "cct", + "cxt", + "w3d", + "fgd", + "swa" + ] +}, + "application/x-doom": { + source: "apache", + extensions: [ + "wad" + ] +}, + "application/x-dtbncx+xml": { + source: "apache", + compressible: true, + extensions: [ + "ncx" + ] +}, + "application/x-dtbook+xml": { + source: "apache", + compressible: true, + extensions: [ + "dtb" + ] +}, + "application/x-dtbresource+xml": { + source: "apache", + compressible: true, + extensions: [ + "res" + ] +}, + "application/x-dvi": { + source: "apache", + compressible: false, + extensions: [ + "dvi" + ] +}, + "application/x-envoy": { + source: "apache", + extensions: [ + "evy" + ] +}, + "application/x-eva": { + source: "apache", + extensions: [ + "eva" + ] +}, + "application/x-font-bdf": { + source: "apache", + extensions: [ + "bdf" + ] +}, + "application/x-font-dos": { + source: "apache" +}, + "application/x-font-framemaker": { + source: "apache" +}, + "application/x-font-ghostscript": { + source: "apache", + extensions: [ + "gsf" + ] +}, + "application/x-font-libgrx": { + source: "apache" +}, + "application/x-font-linux-psf": { + source: "apache", + extensions: [ + "psf" + ] +}, + "application/x-font-pcf": { + source: "apache", + extensions: [ + "pcf" + ] +}, + "application/x-font-snf": { + source: "apache", + extensions: [ + "snf" + ] +}, + "application/x-font-speedo": { + source: "apache" +}, + "application/x-font-sunos-news": { + source: "apache" +}, + "application/x-font-type1": { + source: "apache", + extensions: [ + "pfa", + "pfb", + "pfm", + "afm" + ] +}, + "application/x-font-vfont": { + source: "apache" +}, + "application/x-freearc": { + source: "apache", + extensions: [ + "arc" + ] +}, + "application/x-futuresplash": { + source: "apache", + extensions: [ + "spl" + ] +}, + "application/x-gca-compressed": { + source: "apache", + extensions: [ + "gca" + ] +}, + "application/x-glulx": { + source: "apache", + extensions: [ + "ulx" + ] +}, + "application/x-gnumeric": { + source: "apache", + extensions: [ + "gnumeric" + ] +}, + "application/x-gramps-xml": { + source: "apache", + extensions: [ + "gramps" + ] +}, + "application/x-gtar": { + source: "apache", + extensions: [ + "gtar" + ] +}, + "application/x-gzip": { + source: "apache" +}, + "application/x-hdf": { + source: "apache", + extensions: [ + "hdf" + ] +}, + "application/x-httpd-php": { + compressible: true, + extensions: [ + "php" + ] +}, + "application/x-install-instructions": { + source: "apache", + extensions: [ + "install" + ] +}, + "application/x-iso9660-image": { + source: "apache", + extensions: [ + "iso" + ] +}, + "application/x-iwork-keynote-sffkey": { + extensions: [ + "key" + ] +}, + "application/x-iwork-numbers-sffnumbers": { + extensions: [ + "numbers" + ] +}, + "application/x-iwork-pages-sffpages": { + extensions: [ + "pages" + ] +}, + "application/x-java-archive-diff": { + source: "nginx", + extensions: [ + "jardiff" + ] +}, + "application/x-java-jnlp-file": { + source: "apache", + compressible: false, + extensions: [ + "jnlp" + ] +}, + "application/x-javascript": { + compressible: true +}, + "application/x-keepass2": { + extensions: [ + "kdbx" + ] +}, + "application/x-latex": { + source: "apache", + compressible: false, + extensions: [ + "latex" + ] +}, + "application/x-lua-bytecode": { + extensions: [ + "luac" + ] +}, + "application/x-lzh-compressed": { + source: "apache", + extensions: [ + "lzh", + "lha" + ] +}, + "application/x-makeself": { + source: "nginx", + extensions: [ + "run" + ] +}, + "application/x-mie": { + source: "apache", + extensions: [ + "mie" + ] +}, + "application/x-mobipocket-ebook": { + source: "apache", + extensions: [ + "prc", + "mobi" + ] +}, + "application/x-mpegurl": { + compressible: false +}, + "application/x-ms-application": { + source: "apache", + extensions: [ + "application" + ] +}, + "application/x-ms-shortcut": { + source: "apache", + extensions: [ + "lnk" + ] +}, + "application/x-ms-wmd": { + source: "apache", + extensions: [ + "wmd" + ] +}, + "application/x-ms-wmz": { + source: "apache", + extensions: [ + "wmz" + ] +}, + "application/x-ms-xbap": { + source: "apache", + extensions: [ + "xbap" + ] +}, + "application/x-msaccess": { + source: "apache", + extensions: [ + "mdb" + ] +}, + "application/x-msbinder": { + source: "apache", + extensions: [ + "obd" + ] +}, + "application/x-mscardfile": { + source: "apache", + extensions: [ + "crd" + ] +}, + "application/x-msclip": { + source: "apache", + extensions: [ + "clp" + ] +}, + "application/x-msdos-program": { + extensions: [ + "exe" + ] +}, + "application/x-msdownload": { + source: "apache", + extensions: [ + "exe", + "dll", + "com", + "bat", + "msi" + ] +}, + "application/x-msmediaview": { + source: "apache", + extensions: [ + "mvb", + "m13", + "m14" + ] +}, + "application/x-msmetafile": { + source: "apache", + extensions: [ + "wmf", + "wmz", + "emf", + "emz" + ] +}, + "application/x-msmoney": { + source: "apache", + extensions: [ + "mny" + ] +}, + "application/x-mspublisher": { + source: "apache", + extensions: [ + "pub" + ] +}, + "application/x-msschedule": { + source: "apache", + extensions: [ + "scd" + ] +}, + "application/x-msterminal": { + source: "apache", + extensions: [ + "trm" + ] +}, + "application/x-mswrite": { + source: "apache", + extensions: [ + "wri" + ] +}, + "application/x-netcdf": { + source: "apache", + extensions: [ + "nc", + "cdf" + ] +}, + "application/x-ns-proxy-autoconfig": { + compressible: true, + extensions: [ + "pac" + ] +}, + "application/x-nzb": { + source: "apache", + extensions: [ + "nzb" + ] +}, + "application/x-perl": { + source: "nginx", + extensions: [ + "pl", + "pm" + ] +}, + "application/x-pilot": { + source: "nginx", + extensions: [ + "prc", + "pdb" + ] +}, + "application/x-pkcs12": { + source: "apache", + compressible: false, + extensions: [ + "p12", + "pfx" + ] +}, + "application/x-pkcs7-certificates": { + source: "apache", + extensions: [ + "p7b", + "spc" + ] +}, + "application/x-pkcs7-certreqresp": { + source: "apache", + extensions: [ + "p7r" + ] +}, + "application/x-pki-message": { + source: "iana" +}, + "application/x-rar-compressed": { + source: "apache", + compressible: false, + extensions: [ + "rar" + ] +}, + "application/x-redhat-package-manager": { + source: "nginx", + extensions: [ + "rpm" + ] +}, + "application/x-research-info-systems": { + source: "apache", + extensions: [ + "ris" + ] +}, + "application/x-sea": { + source: "nginx", + extensions: [ + "sea" + ] +}, + "application/x-sh": { + source: "apache", + compressible: true, + extensions: [ + "sh" + ] +}, + "application/x-shar": { + source: "apache", + extensions: [ + "shar" + ] +}, + "application/x-shockwave-flash": { + source: "apache", + compressible: false, + extensions: [ + "swf" + ] +}, + "application/x-silverlight-app": { + source: "apache", + extensions: [ + "xap" + ] +}, + "application/x-sql": { + source: "apache", + extensions: [ + "sql" + ] +}, + "application/x-stuffit": { + source: "apache", + compressible: false, + extensions: [ + "sit" + ] +}, + "application/x-stuffitx": { + source: "apache", + extensions: [ + "sitx" + ] +}, + "application/x-subrip": { + source: "apache", + extensions: [ + "srt" + ] +}, + "application/x-sv4cpio": { + source: "apache", + extensions: [ + "sv4cpio" + ] +}, + "application/x-sv4crc": { + source: "apache", + extensions: [ + "sv4crc" + ] +}, + "application/x-t3vm-image": { + source: "apache", + extensions: [ + "t3" + ] +}, + "application/x-tads": { + source: "apache", + extensions: [ + "gam" + ] +}, + "application/x-tar": { + source: "apache", + compressible: true, + extensions: [ + "tar" + ] +}, + "application/x-tcl": { + source: "apache", + extensions: [ + "tcl", + "tk" + ] +}, + "application/x-tex": { + source: "apache", + extensions: [ + "tex" + ] +}, + "application/x-tex-tfm": { + source: "apache", + extensions: [ + "tfm" + ] +}, + "application/x-texinfo": { + source: "apache", + extensions: [ + "texinfo", + "texi" + ] +}, + "application/x-tgif": { + source: "apache", + extensions: [ + "obj" + ] +}, + "application/x-ustar": { + source: "apache", + extensions: [ + "ustar" + ] +}, + "application/x-virtualbox-hdd": { + compressible: true, + extensions: [ + "hdd" + ] +}, + "application/x-virtualbox-ova": { + compressible: true, + extensions: [ + "ova" + ] +}, + "application/x-virtualbox-ovf": { + compressible: true, + extensions: [ + "ovf" + ] +}, + "application/x-virtualbox-vbox": { + compressible: true, + extensions: [ + "vbox" + ] +}, + "application/x-virtualbox-vbox-extpack": { + compressible: false, + extensions: [ + "vbox-extpack" + ] +}, + "application/x-virtualbox-vdi": { + compressible: true, + extensions: [ + "vdi" + ] +}, + "application/x-virtualbox-vhd": { + compressible: true, + extensions: [ + "vhd" + ] +}, + "application/x-virtualbox-vmdk": { + compressible: true, + extensions: [ + "vmdk" + ] +}, + "application/x-wais-source": { + source: "apache", + extensions: [ + "src" + ] +}, + "application/x-web-app-manifest+json": { + compressible: true, + extensions: [ + "webapp" + ] +}, + "application/x-www-form-urlencoded": { + source: "iana", + compressible: true +}, + "application/x-x509-ca-cert": { + source: "iana", + extensions: [ + "der", + "crt", + "pem" + ] +}, + "application/x-x509-ca-ra-cert": { + source: "iana" +}, + "application/x-x509-next-ca-cert": { + source: "iana" +}, + "application/x-xfig": { + source: "apache", + extensions: [ + "fig" + ] +}, + "application/x-xliff+xml": { + source: "apache", + compressible: true, + extensions: [ + "xlf" + ] +}, + "application/x-xpinstall": { + source: "apache", + compressible: false, + extensions: [ + "xpi" + ] +}, + "application/x-xz": { + source: "apache", + extensions: [ + "xz" + ] +}, + "application/x-zmachine": { + source: "apache", + extensions: [ + "z1", + "z2", + "z3", + "z4", + "z5", + "z6", + "z7", + "z8" + ] +}, + "application/x400-bp": { + source: "iana" +}, + "application/xacml+xml": { + source: "iana", + compressible: true +}, + "application/xaml+xml": { + source: "apache", + compressible: true, + extensions: [ + "xaml" + ] +}, + "application/xcap-att+xml": { + source: "iana", + compressible: true, + extensions: [ + "xav" + ] +}, + "application/xcap-caps+xml": { + source: "iana", + compressible: true, + extensions: [ + "xca" + ] +}, + "application/xcap-diff+xml": { + source: "iana", + compressible: true, + extensions: [ + "xdf" + ] +}, + "application/xcap-el+xml": { + source: "iana", + compressible: true, + extensions: [ + "xel" + ] +}, + "application/xcap-error+xml": { + source: "iana", + compressible: true +}, + "application/xcap-ns+xml": { + source: "iana", + compressible: true, + extensions: [ + "xns" + ] +}, + "application/xcon-conference-info+xml": { + source: "iana", + compressible: true +}, + "application/xcon-conference-info-diff+xml": { + source: "iana", + compressible: true +}, + "application/xenc+xml": { + source: "iana", + compressible: true, + extensions: [ + "xenc" + ] +}, + "application/xhtml+xml": { + source: "iana", + compressible: true, + extensions: [ + "xhtml", + "xht" + ] +}, + "application/xhtml-voice+xml": { + source: "apache", + compressible: true +}, + "application/xliff+xml": { + source: "iana", + compressible: true, + extensions: [ + "xlf" + ] +}, + "application/xml": { + source: "iana", + compressible: true, + extensions: [ + "xml", + "xsl", + "xsd", + "rng" + ] +}, + "application/xml-dtd": { + source: "iana", + compressible: true, + extensions: [ + "dtd" + ] +}, + "application/xml-external-parsed-entity": { + source: "iana" +}, + "application/xml-patch+xml": { + source: "iana", + compressible: true +}, + "application/xmpp+xml": { + source: "iana", + compressible: true +}, + "application/xop+xml": { + source: "iana", + compressible: true, + extensions: [ + "xop" + ] +}, + "application/xproc+xml": { + source: "apache", + compressible: true, + extensions: [ + "xpl" + ] +}, + "application/xslt+xml": { + source: "iana", + compressible: true, + extensions: [ + "xsl", + "xslt" + ] +}, + "application/xspf+xml": { + source: "apache", + compressible: true, + extensions: [ + "xspf" + ] +}, + "application/xv+xml": { + source: "iana", + compressible: true, + extensions: [ + "mxml", + "xhvml", + "xvml", + "xvm" + ] +}, + "application/yang": { + source: "iana", + extensions: [ + "yang" + ] +}, + "application/yang-data+json": { + source: "iana", + compressible: true +}, + "application/yang-data+xml": { + source: "iana", + compressible: true +}, + "application/yang-patch+json": { + source: "iana", + compressible: true +}, + "application/yang-patch+xml": { + source: "iana", + compressible: true +}, + "application/yin+xml": { + source: "iana", + compressible: true, + extensions: [ + "yin" + ] +}, + "application/zip": { + source: "iana", + compressible: false, + extensions: [ + "zip" + ] +}, + "application/zlib": { + source: "iana" +}, + "application/zstd": { + source: "iana" +}, + "audio/1d-interleaved-parityfec": { + source: "iana" +}, + "audio/32kadpcm": { + source: "iana" +}, + "audio/3gpp": { + source: "iana", + compressible: false, + extensions: [ + "3gpp" + ] +}, + "audio/3gpp2": { + source: "iana" +}, + "audio/aac": { + source: "iana" +}, + "audio/ac3": { + source: "iana" +}, + "audio/adpcm": { + source: "apache", + extensions: [ + "adp" + ] +}, + "audio/amr": { + source: "iana", + extensions: [ + "amr" + ] +}, + "audio/amr-wb": { + source: "iana" +}, + "audio/amr-wb+": { + source: "iana" +}, + "audio/aptx": { + source: "iana" +}, + "audio/asc": { + source: "iana" +}, + "audio/atrac-advanced-lossless": { + source: "iana" +}, + "audio/atrac-x": { + source: "iana" +}, + "audio/atrac3": { + source: "iana" +}, + "audio/basic": { + source: "iana", + compressible: false, + extensions: [ + "au", + "snd" + ] +}, + "audio/bv16": { + source: "iana" +}, + "audio/bv32": { + source: "iana" +}, + "audio/clearmode": { + source: "iana" +}, + "audio/cn": { + source: "iana" +}, + "audio/dat12": { + source: "iana" +}, + "audio/dls": { + source: "iana" +}, + "audio/dsr-es201108": { + source: "iana" +}, + "audio/dsr-es202050": { + source: "iana" +}, + "audio/dsr-es202211": { + source: "iana" +}, + "audio/dsr-es202212": { + source: "iana" +}, + "audio/dv": { + source: "iana" +}, + "audio/dvi4": { + source: "iana" +}, + "audio/eac3": { + source: "iana" +}, + "audio/encaprtp": { + source: "iana" +}, + "audio/evrc": { + source: "iana" +}, + "audio/evrc-qcp": { + source: "iana" +}, + "audio/evrc0": { + source: "iana" +}, + "audio/evrc1": { + source: "iana" +}, + "audio/evrcb": { + source: "iana" +}, + "audio/evrcb0": { + source: "iana" +}, + "audio/evrcb1": { + source: "iana" +}, + "audio/evrcnw": { + source: "iana" +}, + "audio/evrcnw0": { + source: "iana" +}, + "audio/evrcnw1": { + source: "iana" +}, + "audio/evrcwb": { + source: "iana" +}, + "audio/evrcwb0": { + source: "iana" +}, + "audio/evrcwb1": { + source: "iana" +}, + "audio/evs": { + source: "iana" +}, + "audio/flexfec": { + source: "iana" +}, + "audio/fwdred": { + source: "iana" +}, + "audio/g711-0": { + source: "iana" +}, + "audio/g719": { + source: "iana" +}, + "audio/g722": { + source: "iana" +}, + "audio/g7221": { + source: "iana" +}, + "audio/g723": { + source: "iana" +}, + "audio/g726-16": { + source: "iana" +}, + "audio/g726-24": { + source: "iana" +}, + "audio/g726-32": { + source: "iana" +}, + "audio/g726-40": { + source: "iana" +}, + "audio/g728": { + source: "iana" +}, + "audio/g729": { + source: "iana" +}, + "audio/g7291": { + source: "iana" +}, + "audio/g729d": { + source: "iana" +}, + "audio/g729e": { + source: "iana" +}, + "audio/gsm": { + source: "iana" +}, + "audio/gsm-efr": { + source: "iana" +}, + "audio/gsm-hr-08": { + source: "iana" +}, + "audio/ilbc": { + source: "iana" +}, + "audio/ip-mr_v2.5": { + source: "iana" +}, + "audio/isac": { + source: "apache" +}, + "audio/l16": { + source: "iana" +}, + "audio/l20": { + source: "iana" +}, + "audio/l24": { + source: "iana", + compressible: false +}, + "audio/l8": { + source: "iana" +}, + "audio/lpc": { + source: "iana" +}, + "audio/melp": { + source: "iana" +}, + "audio/melp1200": { + source: "iana" +}, + "audio/melp2400": { + source: "iana" +}, + "audio/melp600": { + source: "iana" +}, + "audio/mhas": { + source: "iana" +}, + "audio/midi": { + source: "apache", + extensions: [ + "mid", + "midi", + "kar", + "rmi" + ] +}, + "audio/mobile-xmf": { + source: "iana", + extensions: [ + "mxmf" + ] +}, + "audio/mp3": { + compressible: false, + extensions: [ + "mp3" + ] +}, + "audio/mp4": { + source: "iana", + compressible: false, + extensions: [ + "m4a", + "mp4a" + ] +}, + "audio/mp4a-latm": { + source: "iana" +}, + "audio/mpa": { + source: "iana" +}, + "audio/mpa-robust": { + source: "iana" +}, + "audio/mpeg": { + source: "iana", + compressible: false, + extensions: [ + "mpga", + "mp2", + "mp2a", + "mp3", + "m2a", + "m3a" + ] +}, + "audio/mpeg4-generic": { + source: "iana" +}, + "audio/musepack": { + source: "apache" +}, + "audio/ogg": { + source: "iana", + compressible: false, + extensions: [ + "oga", + "ogg", + "spx", + "opus" + ] +}, + "audio/opus": { + source: "iana" +}, + "audio/parityfec": { + source: "iana" +}, + "audio/pcma": { + source: "iana" +}, + "audio/pcma-wb": { + source: "iana" +}, + "audio/pcmu": { + source: "iana" +}, + "audio/pcmu-wb": { + source: "iana" +}, + "audio/prs.sid": { + source: "iana" +}, + "audio/qcelp": { + source: "iana" +}, + "audio/raptorfec": { + source: "iana" +}, + "audio/red": { + source: "iana" +}, + "audio/rtp-enc-aescm128": { + source: "iana" +}, + "audio/rtp-midi": { + source: "iana" +}, + "audio/rtploopback": { + source: "iana" +}, + "audio/rtx": { + source: "iana" +}, + "audio/s3m": { + source: "apache", + extensions: [ + "s3m" + ] +}, + "audio/scip": { + source: "iana" +}, + "audio/silk": { + source: "apache", + extensions: [ + "sil" + ] +}, + "audio/smv": { + source: "iana" +}, + "audio/smv-qcp": { + source: "iana" +}, + "audio/smv0": { + source: "iana" +}, + "audio/sofa": { + source: "iana" +}, + "audio/sp-midi": { + source: "iana" +}, + "audio/speex": { + source: "iana" +}, + "audio/t140c": { + source: "iana" +}, + "audio/t38": { + source: "iana" +}, + "audio/telephone-event": { + source: "iana" +}, + "audio/tetra_acelp": { + source: "iana" +}, + "audio/tetra_acelp_bb": { + source: "iana" +}, + "audio/tone": { + source: "iana" +}, + "audio/tsvcis": { + source: "iana" +}, + "audio/uemclip": { + source: "iana" +}, + "audio/ulpfec": { + source: "iana" +}, + "audio/usac": { + source: "iana" +}, + "audio/vdvi": { + source: "iana" +}, + "audio/vmr-wb": { + source: "iana" +}, + "audio/vnd.3gpp.iufp": { + source: "iana" +}, + "audio/vnd.4sb": { + source: "iana" +}, + "audio/vnd.audiokoz": { + source: "iana" +}, + "audio/vnd.celp": { + source: "iana" +}, + "audio/vnd.cisco.nse": { + source: "iana" +}, + "audio/vnd.cmles.radio-events": { + source: "iana" +}, + "audio/vnd.cns.anp1": { + source: "iana" +}, + "audio/vnd.cns.inf1": { + source: "iana" +}, + "audio/vnd.dece.audio": { + source: "iana", + extensions: [ + "uva", + "uvva" + ] +}, + "audio/vnd.digital-winds": { + source: "iana", + extensions: [ + "eol" + ] +}, + "audio/vnd.dlna.adts": { + source: "iana" +}, + "audio/vnd.dolby.heaac.1": { + source: "iana" +}, + "audio/vnd.dolby.heaac.2": { + source: "iana" +}, + "audio/vnd.dolby.mlp": { + source: "iana" +}, + "audio/vnd.dolby.mps": { + source: "iana" +}, + "audio/vnd.dolby.pl2": { + source: "iana" +}, + "audio/vnd.dolby.pl2x": { + source: "iana" +}, + "audio/vnd.dolby.pl2z": { + source: "iana" +}, + "audio/vnd.dolby.pulse.1": { + source: "iana" +}, + "audio/vnd.dra": { + source: "iana", + extensions: [ + "dra" + ] +}, + "audio/vnd.dts": { + source: "iana", + extensions: [ + "dts" + ] +}, + "audio/vnd.dts.hd": { + source: "iana", + extensions: [ + "dtshd" + ] +}, + "audio/vnd.dts.uhd": { + source: "iana" +}, + "audio/vnd.dvb.file": { + source: "iana" +}, + "audio/vnd.everad.plj": { + source: "iana" +}, + "audio/vnd.hns.audio": { + source: "iana" +}, + "audio/vnd.lucent.voice": { + source: "iana", + extensions: [ + "lvp" + ] +}, + "audio/vnd.ms-playready.media.pya": { + source: "iana", + extensions: [ + "pya" + ] +}, + "audio/vnd.nokia.mobile-xmf": { + source: "iana" +}, + "audio/vnd.nortel.vbk": { + source: "iana" +}, + "audio/vnd.nuera.ecelp4800": { + source: "iana", + extensions: [ + "ecelp4800" + ] +}, + "audio/vnd.nuera.ecelp7470": { + source: "iana", + extensions: [ + "ecelp7470" + ] +}, + "audio/vnd.nuera.ecelp9600": { + source: "iana", + extensions: [ + "ecelp9600" + ] +}, + "audio/vnd.octel.sbc": { + source: "iana" +}, + "audio/vnd.presonus.multitrack": { + source: "iana" +}, + "audio/vnd.qcelp": { + source: "iana" +}, + "audio/vnd.rhetorex.32kadpcm": { + source: "iana" +}, + "audio/vnd.rip": { + source: "iana", + extensions: [ + "rip" + ] +}, + "audio/vnd.rn-realaudio": { + compressible: false +}, + "audio/vnd.sealedmedia.softseal.mpeg": { + source: "iana" +}, + "audio/vnd.vmx.cvsd": { + source: "iana" +}, + "audio/vnd.wave": { + compressible: false +}, + "audio/vorbis": { + source: "iana", + compressible: false +}, + "audio/vorbis-config": { + source: "iana" +}, + "audio/wav": { + compressible: false, + extensions: [ + "wav" + ] +}, + "audio/wave": { + compressible: false, + extensions: [ + "wav" + ] +}, + "audio/webm": { + source: "apache", + compressible: false, + extensions: [ + "weba" + ] +}, + "audio/x-aac": { + source: "apache", + compressible: false, + extensions: [ + "aac" + ] +}, + "audio/x-aiff": { + source: "apache", + extensions: [ + "aif", + "aiff", + "aifc" + ] +}, + "audio/x-caf": { + source: "apache", + compressible: false, + extensions: [ + "caf" + ] +}, + "audio/x-flac": { + source: "apache", + extensions: [ + "flac" + ] +}, + "audio/x-m4a": { + source: "nginx", + extensions: [ + "m4a" + ] +}, + "audio/x-matroska": { + source: "apache", + extensions: [ + "mka" + ] +}, + "audio/x-mpegurl": { + source: "apache", + extensions: [ + "m3u" + ] +}, + "audio/x-ms-wax": { + source: "apache", + extensions: [ + "wax" + ] +}, + "audio/x-ms-wma": { + source: "apache", + extensions: [ + "wma" + ] +}, + "audio/x-pn-realaudio": { + source: "apache", + extensions: [ + "ram", + "ra" + ] +}, + "audio/x-pn-realaudio-plugin": { + source: "apache", + extensions: [ + "rmp" + ] +}, + "audio/x-realaudio": { + source: "nginx", + extensions: [ + "ra" + ] +}, + "audio/x-tta": { + source: "apache" +}, + "audio/x-wav": { + source: "apache", + extensions: [ + "wav" + ] +}, + "audio/xm": { + source: "apache", + extensions: [ + "xm" + ] +}, + "chemical/x-cdx": { + source: "apache", + extensions: [ + "cdx" + ] +}, + "chemical/x-cif": { + source: "apache", + extensions: [ + "cif" + ] +}, + "chemical/x-cmdf": { + source: "apache", + extensions: [ + "cmdf" + ] +}, + "chemical/x-cml": { + source: "apache", + extensions: [ + "cml" + ] +}, + "chemical/x-csml": { + source: "apache", + extensions: [ + "csml" + ] +}, + "chemical/x-pdb": { + source: "apache" +}, + "chemical/x-xyz": { + source: "apache", + extensions: [ + "xyz" + ] +}, + "font/collection": { + source: "iana", + extensions: [ + "ttc" + ] +}, + "font/otf": { + source: "iana", + compressible: true, + extensions: [ + "otf" + ] +}, + "font/sfnt": { + source: "iana" +}, + "font/ttf": { + source: "iana", + compressible: true, + extensions: [ + "ttf" + ] +}, + "font/woff": { + source: "iana", + extensions: [ + "woff" + ] +}, + "font/woff2": { + source: "iana", + extensions: [ + "woff2" + ] +}, + "image/aces": { + source: "iana", + extensions: [ + "exr" + ] +}, + "image/apng": { + compressible: false, + extensions: [ + "apng" + ] +}, + "image/avci": { + source: "iana", + extensions: [ + "avci" + ] +}, + "image/avcs": { + source: "iana", + extensions: [ + "avcs" + ] +}, + "image/avif": { + source: "iana", + compressible: false, + extensions: [ + "avif" + ] +}, + "image/bmp": { + source: "iana", + compressible: true, + extensions: [ + "bmp" + ] +}, + "image/cgm": { + source: "iana", + extensions: [ + "cgm" + ] +}, + "image/dicom-rle": { + source: "iana", + extensions: [ + "drle" + ] +}, + "image/emf": { + source: "iana", + extensions: [ + "emf" + ] +}, + "image/fits": { + source: "iana", + extensions: [ + "fits" + ] +}, + "image/g3fax": { + source: "iana", + extensions: [ + "g3" + ] +}, + "image/gif": { + source: "iana", + compressible: false, + extensions: [ + "gif" + ] +}, + "image/heic": { + source: "iana", + extensions: [ + "heic" + ] +}, + "image/heic-sequence": { + source: "iana", + extensions: [ + "heics" + ] +}, + "image/heif": { + source: "iana", + extensions: [ + "heif" + ] +}, + "image/heif-sequence": { + source: "iana", + extensions: [ + "heifs" + ] +}, + "image/hej2k": { + source: "iana", + extensions: [ + "hej2" + ] +}, + "image/hsj2": { + source: "iana", + extensions: [ + "hsj2" + ] +}, + "image/ief": { + source: "iana", + extensions: [ + "ief" + ] +}, + "image/jls": { + source: "iana", + extensions: [ + "jls" + ] +}, + "image/jp2": { + source: "iana", + compressible: false, + extensions: [ + "jp2", + "jpg2" + ] +}, + "image/jpeg": { + source: "iana", + compressible: false, + extensions: [ + "jpeg", + "jpg", + "jpe" + ] +}, + "image/jph": { + source: "iana", + extensions: [ + "jph" + ] +}, + "image/jphc": { + source: "iana", + extensions: [ + "jhc" + ] +}, + "image/jpm": { + source: "iana", + compressible: false, + extensions: [ + "jpm" + ] +}, + "image/jpx": { + source: "iana", + compressible: false, + extensions: [ + "jpx", + "jpf" + ] +}, + "image/jxr": { + source: "iana", + extensions: [ + "jxr" + ] +}, + "image/jxra": { + source: "iana", + extensions: [ + "jxra" + ] +}, + "image/jxrs": { + source: "iana", + extensions: [ + "jxrs" + ] +}, + "image/jxs": { + source: "iana", + extensions: [ + "jxs" + ] +}, + "image/jxsc": { + source: "iana", + extensions: [ + "jxsc" + ] +}, + "image/jxsi": { + source: "iana", + extensions: [ + "jxsi" + ] +}, + "image/jxss": { + source: "iana", + extensions: [ + "jxss" + ] +}, + "image/ktx": { + source: "iana", + extensions: [ + "ktx" + ] +}, + "image/ktx2": { + source: "iana", + extensions: [ + "ktx2" + ] +}, + "image/naplps": { + source: "iana" +}, + "image/pjpeg": { + compressible: false +}, + "image/png": { + source: "iana", + compressible: false, + extensions: [ + "png" + ] +}, + "image/prs.btif": { + source: "iana", + extensions: [ + "btif" + ] +}, + "image/prs.pti": { + source: "iana", + extensions: [ + "pti" + ] +}, + "image/pwg-raster": { + source: "iana" +}, + "image/sgi": { + source: "apache", + extensions: [ + "sgi" + ] +}, + "image/svg+xml": { + source: "iana", + compressible: true, + extensions: [ + "svg", + "svgz" + ] +}, + "image/t38": { + source: "iana", + extensions: [ + "t38" + ] +}, + "image/tiff": { + source: "iana", + compressible: false, + extensions: [ + "tif", + "tiff" + ] +}, + "image/tiff-fx": { + source: "iana", + extensions: [ + "tfx" + ] +}, + "image/vnd.adobe.photoshop": { + source: "iana", + compressible: true, + extensions: [ + "psd" + ] +}, + "image/vnd.airzip.accelerator.azv": { + source: "iana", + extensions: [ + "azv" + ] +}, + "image/vnd.cns.inf2": { + source: "iana" +}, + "image/vnd.dece.graphic": { + source: "iana", + extensions: [ + "uvi", + "uvvi", + "uvg", + "uvvg" + ] +}, + "image/vnd.djvu": { + source: "iana", + extensions: [ + "djvu", + "djv" + ] +}, + "image/vnd.dvb.subtitle": { + source: "iana", + extensions: [ + "sub" + ] +}, + "image/vnd.dwg": { + source: "iana", + extensions: [ + "dwg" + ] +}, + "image/vnd.dxf": { + source: "iana", + extensions: [ + "dxf" + ] +}, + "image/vnd.fastbidsheet": { + source: "iana", + extensions: [ + "fbs" + ] +}, + "image/vnd.fpx": { + source: "iana", + extensions: [ + "fpx" + ] +}, + "image/vnd.fst": { + source: "iana", + extensions: [ + "fst" + ] +}, + "image/vnd.fujixerox.edmics-mmr": { + source: "iana", + extensions: [ + "mmr" + ] +}, + "image/vnd.fujixerox.edmics-rlc": { + source: "iana", + extensions: [ + "rlc" + ] +}, + "image/vnd.globalgraphics.pgb": { + source: "iana" +}, + "image/vnd.microsoft.icon": { + source: "iana", + compressible: true, + extensions: [ + "ico" + ] +}, + "image/vnd.mix": { + source: "iana" +}, + "image/vnd.mozilla.apng": { + source: "iana" +}, + "image/vnd.ms-dds": { + compressible: true, + extensions: [ + "dds" + ] +}, + "image/vnd.ms-modi": { + source: "iana", + extensions: [ + "mdi" + ] +}, + "image/vnd.ms-photo": { + source: "apache", + extensions: [ + "wdp" + ] +}, + "image/vnd.net-fpx": { + source: "iana", + extensions: [ + "npx" + ] +}, + "image/vnd.pco.b16": { + source: "iana", + extensions: [ + "b16" + ] +}, + "image/vnd.radiance": { + source: "iana" +}, + "image/vnd.sealed.png": { + source: "iana" +}, + "image/vnd.sealedmedia.softseal.gif": { + source: "iana" +}, + "image/vnd.sealedmedia.softseal.jpg": { + source: "iana" +}, + "image/vnd.svf": { + source: "iana" +}, + "image/vnd.tencent.tap": { + source: "iana", + extensions: [ + "tap" + ] +}, + "image/vnd.valve.source.texture": { + source: "iana", + extensions: [ + "vtf" + ] +}, + "image/vnd.wap.wbmp": { + source: "iana", + extensions: [ + "wbmp" + ] +}, + "image/vnd.xiff": { + source: "iana", + extensions: [ + "xif" + ] +}, + "image/vnd.zbrush.pcx": { + source: "iana", + extensions: [ + "pcx" + ] +}, + "image/webp": { + source: "apache", + extensions: [ + "webp" + ] +}, + "image/wmf": { + source: "iana", + extensions: [ + "wmf" + ] +}, + "image/x-3ds": { + source: "apache", + extensions: [ + "3ds" + ] +}, + "image/x-cmu-raster": { + source: "apache", + extensions: [ + "ras" + ] +}, + "image/x-cmx": { + source: "apache", + extensions: [ + "cmx" + ] +}, + "image/x-freehand": { + source: "apache", + extensions: [ + "fh", + "fhc", + "fh4", + "fh5", + "fh7" + ] +}, + "image/x-icon": { + source: "apache", + compressible: true, + extensions: [ + "ico" + ] +}, + "image/x-jng": { + source: "nginx", + extensions: [ + "jng" + ] +}, + "image/x-mrsid-image": { + source: "apache", + extensions: [ + "sid" + ] +}, + "image/x-ms-bmp": { + source: "nginx", + compressible: true, + extensions: [ + "bmp" + ] +}, + "image/x-pcx": { + source: "apache", + extensions: [ + "pcx" + ] +}, + "image/x-pict": { + source: "apache", + extensions: [ + "pic", + "pct" + ] +}, + "image/x-portable-anymap": { + source: "apache", + extensions: [ + "pnm" + ] +}, + "image/x-portable-bitmap": { + source: "apache", + extensions: [ + "pbm" + ] +}, + "image/x-portable-graymap": { + source: "apache", + extensions: [ + "pgm" + ] +}, + "image/x-portable-pixmap": { + source: "apache", + extensions: [ + "ppm" + ] +}, + "image/x-rgb": { + source: "apache", + extensions: [ + "rgb" + ] +}, + "image/x-tga": { + source: "apache", + extensions: [ + "tga" + ] +}, + "image/x-xbitmap": { + source: "apache", + extensions: [ + "xbm" + ] +}, + "image/x-xcf": { + compressible: false +}, + "image/x-xpixmap": { + source: "apache", + extensions: [ + "xpm" + ] +}, + "image/x-xwindowdump": { + source: "apache", + extensions: [ + "xwd" + ] +}, + "message/cpim": { + source: "iana" +}, + "message/delivery-status": { + source: "iana" +}, + "message/disposition-notification": { + source: "iana", + extensions: [ + "disposition-notification" + ] +}, + "message/external-body": { + source: "iana" +}, + "message/feedback-report": { + source: "iana" +}, + "message/global": { + source: "iana", + extensions: [ + "u8msg" + ] +}, + "message/global-delivery-status": { + source: "iana", + extensions: [ + "u8dsn" + ] +}, + "message/global-disposition-notification": { + source: "iana", + extensions: [ + "u8mdn" + ] +}, + "message/global-headers": { + source: "iana", + extensions: [ + "u8hdr" + ] +}, + "message/http": { + source: "iana", + compressible: false +}, + "message/imdn+xml": { + source: "iana", + compressible: true +}, + "message/news": { + source: "iana" +}, + "message/partial": { + source: "iana", + compressible: false +}, + "message/rfc822": { + source: "iana", + compressible: true, + extensions: [ + "eml", + "mime" + ] +}, + "message/s-http": { + source: "iana" +}, + "message/sip": { + source: "iana" +}, + "message/sipfrag": { + source: "iana" +}, + "message/tracking-status": { + source: "iana" +}, + "message/vnd.si.simp": { + source: "iana" +}, + "message/vnd.wfa.wsc": { + source: "iana", + extensions: [ + "wsc" + ] +}, + "model/3mf": { + source: "iana", + extensions: [ + "3mf" + ] +}, + "model/e57": { + source: "iana" +}, + "model/gltf+json": { + source: "iana", + compressible: true, + extensions: [ + "gltf" + ] +}, + "model/gltf-binary": { + source: "iana", + compressible: true, + extensions: [ + "glb" + ] +}, + "model/iges": { + source: "iana", + compressible: false, + extensions: [ + "igs", + "iges" + ] +}, + "model/mesh": { + source: "iana", + compressible: false, + extensions: [ + "msh", + "mesh", + "silo" + ] +}, + "model/mtl": { + source: "iana", + extensions: [ + "mtl" + ] +}, + "model/obj": { + source: "iana", + extensions: [ + "obj" + ] +}, + "model/step": { + source: "iana" +}, + "model/step+xml": { + source: "iana", + compressible: true, + extensions: [ + "stpx" + ] +}, + "model/step+zip": { + source: "iana", + compressible: false, + extensions: [ + "stpz" + ] +}, + "model/step-xml+zip": { + source: "iana", + compressible: false, + extensions: [ + "stpxz" + ] +}, + "model/stl": { + source: "iana", + extensions: [ + "stl" + ] +}, + "model/vnd.collada+xml": { + source: "iana", + compressible: true, + extensions: [ + "dae" + ] +}, + "model/vnd.dwf": { + source: "iana", + extensions: [ + "dwf" + ] +}, + "model/vnd.flatland.3dml": { + source: "iana" +}, + "model/vnd.gdl": { + source: "iana", + extensions: [ + "gdl" + ] +}, + "model/vnd.gs-gdl": { + source: "apache" +}, + "model/vnd.gs.gdl": { + source: "iana" +}, + "model/vnd.gtw": { + source: "iana", + extensions: [ + "gtw" + ] +}, + "model/vnd.moml+xml": { + source: "iana", + compressible: true +}, + "model/vnd.mts": { + source: "iana", + extensions: [ + "mts" + ] +}, + "model/vnd.opengex": { + source: "iana", + extensions: [ + "ogex" + ] +}, + "model/vnd.parasolid.transmit.binary": { + source: "iana", + extensions: [ + "x_b" + ] +}, + "model/vnd.parasolid.transmit.text": { + source: "iana", + extensions: [ + "x_t" + ] +}, + "model/vnd.pytha.pyox": { + source: "iana" +}, + "model/vnd.rosette.annotated-data-model": { + source: "iana" +}, + "model/vnd.sap.vds": { + source: "iana", + extensions: [ + "vds" + ] +}, + "model/vnd.usdz+zip": { + source: "iana", + compressible: false, + extensions: [ + "usdz" + ] +}, + "model/vnd.valve.source.compiled-map": { + source: "iana", + extensions: [ + "bsp" + ] +}, + "model/vnd.vtu": { + source: "iana", + extensions: [ + "vtu" + ] +}, + "model/vrml": { + source: "iana", + compressible: false, + extensions: [ + "wrl", + "vrml" + ] +}, + "model/x3d+binary": { + source: "apache", + compressible: false, + extensions: [ + "x3db", + "x3dbz" + ] +}, + "model/x3d+fastinfoset": { + source: "iana", + extensions: [ + "x3db" + ] +}, + "model/x3d+vrml": { + source: "apache", + compressible: false, + extensions: [ + "x3dv", + "x3dvz" + ] +}, + "model/x3d+xml": { + source: "iana", + compressible: true, + extensions: [ + "x3d", + "x3dz" + ] +}, + "model/x3d-vrml": { + source: "iana", + extensions: [ + "x3dv" + ] +}, + "multipart/alternative": { + source: "iana", + compressible: false +}, + "multipart/appledouble": { + source: "iana" +}, + "multipart/byteranges": { + source: "iana" +}, + "multipart/digest": { + source: "iana" +}, + "multipart/encrypted": { + source: "iana", + compressible: false +}, + "multipart/form-data": { + source: "iana", + compressible: false +}, + "multipart/header-set": { + source: "iana" +}, + "multipart/mixed": { + source: "iana" +}, + "multipart/multilingual": { + source: "iana" +}, + "multipart/parallel": { + source: "iana" +}, + "multipart/related": { + source: "iana", + compressible: false +}, + "multipart/report": { + source: "iana" +}, + "multipart/signed": { + source: "iana", + compressible: false +}, + "multipart/vnd.bint.med-plus": { + source: "iana" +}, + "multipart/voice-message": { + source: "iana" +}, + "multipart/x-mixed-replace": { + source: "iana" +}, + "text/1d-interleaved-parityfec": { + source: "iana" +}, + "text/cache-manifest": { + source: "iana", + compressible: true, + extensions: [ + "appcache", + "manifest" + ] +}, + "text/calendar": { + source: "iana", + extensions: [ + "ics", + "ifb" + ] +}, + "text/calender": { + compressible: true +}, + "text/cmd": { + compressible: true +}, + "text/coffeescript": { + extensions: [ + "coffee", + "litcoffee" + ] +}, + "text/cql": { + source: "iana" +}, + "text/cql-expression": { + source: "iana" +}, + "text/cql-identifier": { + source: "iana" +}, + "text/css": { + source: "iana", + charset: "UTF-8", + compressible: true, + extensions: [ + "css" + ] +}, + "text/csv": { + source: "iana", + compressible: true, + extensions: [ + "csv" + ] +}, + "text/csv-schema": { + source: "iana" +}, + "text/directory": { + source: "iana" +}, + "text/dns": { + source: "iana" +}, + "text/ecmascript": { + source: "iana" +}, + "text/encaprtp": { + source: "iana" +}, + "text/enriched": { + source: "iana" +}, + "text/fhirpath": { + source: "iana" +}, + "text/flexfec": { + source: "iana" +}, + "text/fwdred": { + source: "iana" +}, + "text/gff3": { + source: "iana" +}, + "text/grammar-ref-list": { + source: "iana" +}, + "text/html": { + source: "iana", + compressible: true, + extensions: [ + "html", + "htm", + "shtml" + ] +}, + "text/jade": { + extensions: [ + "jade" + ] +}, + "text/javascript": { + source: "iana", + compressible: true +}, + "text/jcr-cnd": { + source: "iana" +}, + "text/jsx": { + compressible: true, + extensions: [ + "jsx" + ] +}, + "text/less": { + compressible: true, + extensions: [ + "less" + ] +}, + "text/markdown": { + source: "iana", + compressible: true, + extensions: [ + "markdown", + "md" + ] +}, + "text/mathml": { + source: "nginx", + extensions: [ + "mml" + ] +}, + "text/mdx": { + compressible: true, + extensions: [ + "mdx" + ] +}, + "text/mizar": { + source: "iana" +}, + "text/n3": { + source: "iana", + charset: "UTF-8", + compressible: true, + extensions: [ + "n3" + ] +}, + "text/parameters": { + source: "iana", + charset: "UTF-8" +}, + "text/parityfec": { + source: "iana" +}, + "text/plain": { + source: "iana", + compressible: true, + extensions: [ + "txt", + "text", + "conf", + "def", + "list", + "log", + "in", + "ini" + ] +}, + "text/provenance-notation": { + source: "iana", + charset: "UTF-8" +}, + "text/prs.fallenstein.rst": { + source: "iana" +}, + "text/prs.lines.tag": { + source: "iana", + extensions: [ + "dsc" + ] +}, + "text/prs.prop.logic": { + source: "iana" +}, + "text/raptorfec": { + source: "iana" +}, + "text/red": { + source: "iana" +}, + "text/rfc822-headers": { + source: "iana" +}, + "text/richtext": { + source: "iana", + compressible: true, + extensions: [ + "rtx" + ] +}, + "text/rtf": { + source: "iana", + compressible: true, + extensions: [ + "rtf" + ] +}, + "text/rtp-enc-aescm128": { + source: "iana" +}, + "text/rtploopback": { + source: "iana" +}, + "text/rtx": { + source: "iana" +}, + "text/sgml": { + source: "iana", + extensions: [ + "sgml", + "sgm" + ] +}, + "text/shaclc": { + source: "iana" +}, + "text/shex": { + source: "iana", + extensions: [ + "shex" + ] +}, + "text/slim": { + extensions: [ + "slim", + "slm" + ] +}, + "text/spdx": { + source: "iana", + extensions: [ + "spdx" + ] +}, + "text/strings": { + source: "iana" +}, + "text/stylus": { + extensions: [ + "stylus", + "styl" + ] +}, + "text/t140": { + source: "iana" +}, + "text/tab-separated-values": { + source: "iana", + compressible: true, + extensions: [ + "tsv" + ] +}, + "text/troff": { + source: "iana", + extensions: [ + "t", + "tr", + "roff", + "man", + "me", + "ms" + ] +}, + "text/turtle": { + source: "iana", + charset: "UTF-8", + extensions: [ + "ttl" + ] +}, + "text/ulpfec": { + source: "iana" +}, + "text/uri-list": { + source: "iana", + compressible: true, + extensions: [ + "uri", + "uris", + "urls" + ] +}, + "text/vcard": { + source: "iana", + compressible: true, + extensions: [ + "vcard" + ] +}, + "text/vnd.a": { + source: "iana" +}, + "text/vnd.abc": { + source: "iana" +}, + "text/vnd.ascii-art": { + source: "iana" +}, + "text/vnd.curl": { + source: "iana", + extensions: [ + "curl" + ] +}, + "text/vnd.curl.dcurl": { + source: "apache", + extensions: [ + "dcurl" + ] +}, + "text/vnd.curl.mcurl": { + source: "apache", + extensions: [ + "mcurl" + ] +}, + "text/vnd.curl.scurl": { + source: "apache", + extensions: [ + "scurl" + ] +}, + "text/vnd.debian.copyright": { + source: "iana", + charset: "UTF-8" +}, + "text/vnd.dmclientscript": { + source: "iana" +}, + "text/vnd.dvb.subtitle": { + source: "iana", + extensions: [ + "sub" + ] +}, + "text/vnd.esmertec.theme-descriptor": { + source: "iana", + charset: "UTF-8" +}, + "text/vnd.familysearch.gedcom": { + source: "iana", + extensions: [ + "ged" + ] +}, + "text/vnd.ficlab.flt": { + source: "iana" +}, + "text/vnd.fly": { + source: "iana", + extensions: [ + "fly" + ] +}, + "text/vnd.fmi.flexstor": { + source: "iana", + extensions: [ + "flx" + ] +}, + "text/vnd.gml": { + source: "iana" +}, + "text/vnd.graphviz": { + source: "iana", + extensions: [ + "gv" + ] +}, + "text/vnd.hans": { + source: "iana" +}, + "text/vnd.hgl": { + source: "iana" +}, + "text/vnd.in3d.3dml": { + source: "iana", + extensions: [ + "3dml" + ] +}, + "text/vnd.in3d.spot": { + source: "iana", + extensions: [ + "spot" + ] +}, + "text/vnd.iptc.newsml": { + source: "iana" +}, + "text/vnd.iptc.nitf": { + source: "iana" +}, + "text/vnd.latex-z": { + source: "iana" +}, + "text/vnd.motorola.reflex": { + source: "iana" +}, + "text/vnd.ms-mediapackage": { + source: "iana" +}, + "text/vnd.net2phone.commcenter.command": { + source: "iana" +}, + "text/vnd.radisys.msml-basic-layout": { + source: "iana" +}, + "text/vnd.senx.warpscript": { + source: "iana" +}, + "text/vnd.si.uricatalogue": { + source: "iana" +}, + "text/vnd.sosi": { + source: "iana" +}, + "text/vnd.sun.j2me.app-descriptor": { + source: "iana", + charset: "UTF-8", + extensions: [ + "jad" + ] +}, + "text/vnd.trolltech.linguist": { + source: "iana", + charset: "UTF-8" +}, + "text/vnd.wap.si": { + source: "iana" +}, + "text/vnd.wap.sl": { + source: "iana" +}, + "text/vnd.wap.wml": { + source: "iana", + extensions: [ + "wml" + ] +}, + "text/vnd.wap.wmlscript": { + source: "iana", + extensions: [ + "wmls" + ] +}, + "text/vtt": { + source: "iana", + charset: "UTF-8", + compressible: true, + extensions: [ + "vtt" + ] +}, + "text/x-asm": { + source: "apache", + extensions: [ + "s", + "asm" + ] +}, + "text/x-c": { + source: "apache", + extensions: [ + "c", + "cc", + "cxx", + "cpp", + "h", + "hh", + "dic" + ] +}, + "text/x-component": { + source: "nginx", + extensions: [ + "htc" + ] +}, + "text/x-fortran": { + source: "apache", + extensions: [ + "f", + "for", + "f77", + "f90" + ] +}, + "text/x-gwt-rpc": { + compressible: true +}, + "text/x-handlebars-template": { + extensions: [ + "hbs" + ] +}, + "text/x-java-source": { + source: "apache", + extensions: [ + "java" + ] +}, + "text/x-jquery-tmpl": { + compressible: true +}, + "text/x-lua": { + extensions: [ + "lua" + ] +}, + "text/x-markdown": { + compressible: true, + extensions: [ + "mkd" + ] +}, + "text/x-nfo": { + source: "apache", + extensions: [ + "nfo" + ] +}, + "text/x-opml": { + source: "apache", + extensions: [ + "opml" + ] +}, + "text/x-org": { + compressible: true, + extensions: [ + "org" + ] +}, + "text/x-pascal": { + source: "apache", + extensions: [ + "p", + "pas" + ] +}, + "text/x-processing": { + compressible: true, + extensions: [ + "pde" + ] +}, + "text/x-sass": { + extensions: [ + "sass" + ] +}, + "text/x-scss": { + extensions: [ + "scss" + ] +}, + "text/x-setext": { + source: "apache", + extensions: [ + "etx" + ] +}, + "text/x-sfv": { + source: "apache", + extensions: [ + "sfv" + ] +}, + "text/x-suse-ymp": { + compressible: true, + extensions: [ + "ymp" + ] +}, + "text/x-uuencode": { + source: "apache", + extensions: [ + "uu" + ] +}, + "text/x-vcalendar": { + source: "apache", + extensions: [ + "vcs" + ] +}, + "text/x-vcard": { + source: "apache", + extensions: [ + "vcf" + ] +}, + "text/xml": { + source: "iana", + compressible: true, + extensions: [ + "xml" + ] +}, + "text/xml-external-parsed-entity": { + source: "iana" +}, + "text/yaml": { + compressible: true, + extensions: [ + "yaml", + "yml" + ] +}, + "video/1d-interleaved-parityfec": { + source: "iana" +}, + "video/3gpp": { + source: "iana", + extensions: [ + "3gp", + "3gpp" + ] +}, + "video/3gpp-tt": { + source: "iana" +}, + "video/3gpp2": { + source: "iana", + extensions: [ + "3g2" + ] +}, + "video/av1": { + source: "iana" +}, + "video/bmpeg": { + source: "iana" +}, + "video/bt656": { + source: "iana" +}, + "video/celb": { + source: "iana" +}, + "video/dv": { + source: "iana" +}, + "video/encaprtp": { + source: "iana" +}, + "video/ffv1": { + source: "iana" +}, + "video/flexfec": { + source: "iana" +}, + "video/h261": { + source: "iana", + extensions: [ + "h261" + ] +}, + "video/h263": { + source: "iana", + extensions: [ + "h263" + ] +}, + "video/h263-1998": { + source: "iana" +}, + "video/h263-2000": { + source: "iana" +}, + "video/h264": { + source: "iana", + extensions: [ + "h264" + ] +}, + "video/h264-rcdo": { + source: "iana" +}, + "video/h264-svc": { + source: "iana" +}, + "video/h265": { + source: "iana" +}, + "video/iso.segment": { + source: "iana", + extensions: [ + "m4s" + ] +}, + "video/jpeg": { + source: "iana", + extensions: [ + "jpgv" + ] +}, + "video/jpeg2000": { + source: "iana" +}, + "video/jpm": { + source: "apache", + extensions: [ + "jpm", + "jpgm" + ] +}, + "video/jxsv": { + source: "iana" +}, + "video/mj2": { + source: "iana", + extensions: [ + "mj2", + "mjp2" + ] +}, + "video/mp1s": { + source: "iana" +}, + "video/mp2p": { + source: "iana" +}, + "video/mp2t": { + source: "iana", + extensions: [ + "ts" + ] +}, + "video/mp4": { + source: "iana", + compressible: false, + extensions: [ + "mp4", + "mp4v", + "mpg4" + ] +}, + "video/mp4v-es": { + source: "iana" +}, + "video/mpeg": { + source: "iana", + compressible: false, + extensions: [ + "mpeg", + "mpg", + "mpe", + "m1v", + "m2v" + ] +}, + "video/mpeg4-generic": { + source: "iana" +}, + "video/mpv": { + source: "iana" +}, + "video/nv": { + source: "iana" +}, + "video/ogg": { + source: "iana", + compressible: false, + extensions: [ + "ogv" + ] +}, + "video/parityfec": { + source: "iana" +}, + "video/pointer": { + source: "iana" +}, + "video/quicktime": { + source: "iana", + compressible: false, + extensions: [ + "qt", + "mov" + ] +}, + "video/raptorfec": { + source: "iana" +}, + "video/raw": { + source: "iana" +}, + "video/rtp-enc-aescm128": { + source: "iana" +}, + "video/rtploopback": { + source: "iana" +}, + "video/rtx": { + source: "iana" +}, + "video/scip": { + source: "iana" +}, + "video/smpte291": { + source: "iana" +}, + "video/smpte292m": { + source: "iana" +}, + "video/ulpfec": { + source: "iana" +}, + "video/vc1": { + source: "iana" +}, + "video/vc2": { + source: "iana" +}, + "video/vnd.cctv": { + source: "iana" +}, + "video/vnd.dece.hd": { + source: "iana", + extensions: [ + "uvh", + "uvvh" + ] +}, + "video/vnd.dece.mobile": { + source: "iana", + extensions: [ + "uvm", + "uvvm" + ] +}, + "video/vnd.dece.mp4": { + source: "iana" +}, + "video/vnd.dece.pd": { + source: "iana", + extensions: [ + "uvp", + "uvvp" + ] +}, + "video/vnd.dece.sd": { + source: "iana", + extensions: [ + "uvs", + "uvvs" + ] +}, + "video/vnd.dece.video": { + source: "iana", + extensions: [ + "uvv", + "uvvv" + ] +}, + "video/vnd.directv.mpeg": { + source: "iana" +}, + "video/vnd.directv.mpeg-tts": { + source: "iana" +}, + "video/vnd.dlna.mpeg-tts": { + source: "iana" +}, + "video/vnd.dvb.file": { + source: "iana", + extensions: [ + "dvb" + ] +}, + "video/vnd.fvt": { + source: "iana", + extensions: [ + "fvt" + ] +}, + "video/vnd.hns.video": { + source: "iana" +}, + "video/vnd.iptvforum.1dparityfec-1010": { + source: "iana" +}, + "video/vnd.iptvforum.1dparityfec-2005": { + source: "iana" +}, + "video/vnd.iptvforum.2dparityfec-1010": { + source: "iana" +}, + "video/vnd.iptvforum.2dparityfec-2005": { + source: "iana" +}, + "video/vnd.iptvforum.ttsavc": { + source: "iana" +}, + "video/vnd.iptvforum.ttsmpeg2": { + source: "iana" +}, + "video/vnd.motorola.video": { + source: "iana" +}, + "video/vnd.motorola.videop": { + source: "iana" +}, + "video/vnd.mpegurl": { + source: "iana", + extensions: [ + "mxu", + "m4u" + ] +}, + "video/vnd.ms-playready.media.pyv": { + source: "iana", + extensions: [ + "pyv" + ] +}, + "video/vnd.nokia.interleaved-multimedia": { + source: "iana" +}, + "video/vnd.nokia.mp4vr": { + source: "iana" +}, + "video/vnd.nokia.videovoip": { + source: "iana" +}, + "video/vnd.objectvideo": { + source: "iana" +}, + "video/vnd.radgamettools.bink": { + source: "iana" +}, + "video/vnd.radgamettools.smacker": { + source: "iana" +}, + "video/vnd.sealed.mpeg1": { + source: "iana" +}, + "video/vnd.sealed.mpeg4": { + source: "iana" +}, + "video/vnd.sealed.swf": { + source: "iana" +}, + "video/vnd.sealedmedia.softseal.mov": { + source: "iana" +}, + "video/vnd.uvvu.mp4": { + source: "iana", + extensions: [ + "uvu", + "uvvu" + ] +}, + "video/vnd.vivo": { + source: "iana", + extensions: [ + "viv" + ] +}, + "video/vnd.youtube.yt": { + source: "iana" +}, + "video/vp8": { + source: "iana" +}, + "video/vp9": { + source: "iana" +}, + "video/webm": { + source: "apache", + compressible: false, + extensions: [ + "webm" + ] +}, + "video/x-f4v": { + source: "apache", + extensions: [ + "f4v" + ] +}, + "video/x-fli": { + source: "apache", + extensions: [ + "fli" + ] +}, + "video/x-flv": { + source: "apache", + compressible: false, + extensions: [ + "flv" + ] +}, + "video/x-m4v": { + source: "apache", + extensions: [ + "m4v" + ] +}, + "video/x-matroska": { + source: "apache", + compressible: false, + extensions: [ + "mkv", + "mk3d", + "mks" + ] +}, + "video/x-mng": { + source: "apache", + extensions: [ + "mng" + ] +}, + "video/x-ms-asf": { + source: "apache", + extensions: [ + "asf", + "asx" + ] +}, + "video/x-ms-vob": { + source: "apache", + extensions: [ + "vob" + ] +}, + "video/x-ms-wm": { + source: "apache", + extensions: [ + "wm" + ] +}, + "video/x-ms-wmv": { + source: "apache", + compressible: false, + extensions: [ + "wmv" + ] +}, + "video/x-ms-wmx": { + source: "apache", + extensions: [ + "wmx" + ] +}, + "video/x-ms-wvx": { + source: "apache", + extensions: [ + "wvx" + ] +}, + "video/x-msvideo": { + source: "apache", + extensions: [ + "avi" + ] +}, + "video/x-sgi-movie": { + source: "apache", + extensions: [ + "movie" + ] +}, + "video/x-smv": { + source: "apache", + extensions: [ + "smv" + ] +}, + "x-conference/x-cooltalk": { + source: "apache", + extensions: [ + "ice" + ] +}, + "x-shader/x-fragment": { + compressible: true +}, + "x-shader/x-vertex": { + compressible: true +} +}; + +/*! + * mime-db + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015-2022 Douglas Christopher Wilson + * MIT Licensed + */ + +/** + * Module exports. + */ + +var mimeDb = require$$0$4; + +/*! + * mime-types + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +(function (exports) { + + /** + * Module dependencies. + * @private + */ + + var db = mimeDb; + var extname = require$$0$b.extname; + + /** + * Module variables. + * @private + */ + + var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/; + var TEXT_TYPE_REGEXP = /^text\//i; + + /** + * Module exports. + * @public + */ + + exports.charset = charset; + exports.charsets = { lookup: charset }; + exports.contentType = contentType; + exports.extension = extension; + exports.extensions = Object.create(null); + exports.lookup = lookup; + exports.types = Object.create(null); + + // Populate the extensions/types maps + populateMaps(exports.extensions, exports.types); + + /** + * Get the default charset for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ + + function charset (type) { + if (!type || typeof type !== 'string') { + return false + } + + // TODO: use media-typer + var match = EXTRACT_TYPE_REGEXP.exec(type); + var mime = match && db[match[1].toLowerCase()]; + + if (mime && mime.charset) { + return mime.charset + } + + // default text/* to utf-8 + if (match && TEXT_TYPE_REGEXP.test(match[1])) { + return 'UTF-8' + } + + return false + } + + /** + * Create a full Content-Type header given a MIME type or extension. + * + * @param {string} str + * @return {boolean|string} + */ + + function contentType (str) { + // TODO: should this even be in this module? + if (!str || typeof str !== 'string') { + return false + } + + var mime = str.indexOf('/') === -1 + ? exports.lookup(str) + : str; + + if (!mime) { + return false + } + + // TODO: use content-type or other module + if (mime.indexOf('charset') === -1) { + var charset = exports.charset(mime); + if (charset) mime += '; charset=' + charset.toLowerCase(); + } + + return mime + } + + /** + * Get the default extension for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ + + function extension (type) { + if (!type || typeof type !== 'string') { + return false + } + + // TODO: use media-typer + var match = EXTRACT_TYPE_REGEXP.exec(type); + + // get extensions + var exts = match && exports.extensions[match[1].toLowerCase()]; + + if (!exts || !exts.length) { + return false + } + + return exts[0] + } + + /** + * Lookup the MIME type for a file path/extension. + * + * @param {string} path + * @return {boolean|string} + */ + + function lookup (path) { + if (!path || typeof path !== 'string') { + return false + } + + // get the extension ("ext" or ".ext" or full path) + var extension = extname('x.' + path) + .toLowerCase() + .substr(1); + + if (!extension) { + return false + } + + return exports.types[extension] || false + } + + /** + * Populate the extensions and types maps. + * @private + */ + + function populateMaps (extensions, types) { + // source preference (least -> most) + var preference = ['nginx', 'apache', undefined, 'iana']; + + Object.keys(db).forEach(function forEachMimeType (type) { + var mime = db[type]; + var exts = mime.extensions; + + if (!exts || !exts.length) { + return + } + + // mime -> extensions + extensions[type] = exts; + + // extension -> mime + for (var i = 0; i < exts.length; i++) { + var extension = exts[i]; + + if (types[extension]) { + var from = preference.indexOf(db[types[extension]].source); + var to = preference.indexOf(mime.source); + + if (types[extension] !== 'application/octet-stream' && + (from > to || (from === to && types[extension].substr(0, 12) === 'application/'))) { + // skip the remapping + continue + } + } + + // set the extension -> mime + types[extension] = type; + } + }); + } +} (mimeTypes)); + +var mime = /*@__PURE__*/getDefaultExportFromCjs(mimeTypes); + +class APIError extends Error { + constructor(res) { + let err; + // Special handling to for fetch `res` arguments where `res.error` will contain our API error + // response. + if (typeof res === 'object') { + if (typeof res?.error === 'object') { + err = res.error; + } + else { + err = res; + } + } + else { + err = res; + } + super(err); + this.name = 'APIError'; + if (typeof err === 'object') { + this.code = err.error; + // If we returned help info in the API, show it otherwise don't render out multiple empty + // lines as we sometimes throw `Error('non-api custom error message')` instances and catch + // them with this class. + if (err?.help) { + this.message = [err.message, '', err.help].join('\n'); + } + else { + this.message = err.message; + } + this.name = 'APIError'; + } + else { + this.code = err; + this.message = err; + } + } +} + +var dist$3 = {}; + +var src$5 = {}; + +(function (exports) { + var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + Object.defineProperty(exports, "__esModule", { value: true }); + const fs_1 = require$$0$8; + const debug_1 = __importDefault(srcExports); + const log = debug_1.default('@kwsites/file-exists'); + function check(path, isFile, isDirectory) { + log(`checking %s`, path); + try { + const stat = fs_1.statSync(path); + if (stat.isFile() && isFile) { + log(`[OK] path represents a file`); + return true; + } + if (stat.isDirectory() && isDirectory) { + log(`[OK] path represents a directory`); + return true; + } + log(`[FAIL] path represents something other than a file or directory`); + return false; + } + catch (e) { + if (e.code === 'ENOENT') { + log(`[FAIL] path is not accessible: %o`, e); + return false; + } + log(`[FATAL] %o`, e); + throw e; + } + } + /** + * Synchronous validation of a path existing either as a file or as a directory. + * + * @param {string} path The path to check + * @param {number} type One or both of the exported numeric constants + */ + function exists(path, type = exports.READABLE) { + return check(path, (type & exports.FILE) > 0, (type & exports.FOLDER) > 0); + } + exports.exists = exists; + /** + * Constant representing a file + */ + exports.FILE = 1; + /** + * Constant representing a folder + */ + exports.FOLDER = 2; + /** + * Constant representing either a file or a folder + */ + exports.READABLE = exports.FILE + exports.FOLDER; + +} (src$5)); + +(function (exports) { + function __export(m) { + for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; + } + Object.defineProperty(exports, "__esModule", { value: true }); + __export(src$5); + +} (dist$3)); + +var dist$2 = {}; + +Object.defineProperty(dist$2, "__esModule", { value: true }); +var createDeferred = dist$2.createDeferred = deferred_1 = dist$2.deferred = void 0; +/** + * Creates a new `DeferredPromise` + * + * ```typescript + import {deferred} from '@kwsites/promise-deferred`; + ``` + */ +function deferred() { + let done; + let fail; + let status = 'pending'; + const promise = new Promise((_done, _fail) => { + done = _done; + fail = _fail; + }); + return { + promise, + done(result) { + if (status === 'pending') { + status = 'resolved'; + done(result); + } + }, + fail(error) { + if (status === 'pending') { + status = 'rejected'; + fail(error); + } + }, + get fulfilled() { + return status !== 'pending'; + }, + get status() { + return status; + }, + }; +} +var deferred_1 = dist$2.deferred = deferred; +/** + * Alias of the exported `deferred` function, to help consumers wanting to use `deferred` as the + * local variable name rather than the factory import name, without needing to rename on import. + * + * ```typescript + import {createDeferred} from '@kwsites/promise-deferred`; + ``` + */ +createDeferred = dist$2.createDeferred = deferred; +/** + * Default export allows use as: + * + * ```typescript + import deferred from '@kwsites/promise-deferred`; + ``` + */ +dist$2.default = deferred; + +var __defProp = Object.defineProperty; +var __defProps = Object.defineProperties; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropDescs = Object.getOwnPropertyDescriptors; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getOwnPropSymbols = Object.getOwnPropertySymbols; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __propIsEnum = Object.prototype.propertyIsEnumerable; +var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __spreadValues = (a, b) => { + for (var prop in b || (b = {})) + if (__hasOwnProp.call(b, prop)) + __defNormalProp(a, prop, b[prop]); + if (__getOwnPropSymbols) + for (var prop of __getOwnPropSymbols(b)) { + if (__propIsEnum.call(b, prop)) + __defNormalProp(a, prop, b[prop]); + } + return a; +}; +var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b)); +var __markAsModule = (target) => __defProp(target, "__esModule", { value: true }); +var __esm = (fn, res) => function __init() { + return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; +}; +var __commonJS = (cb, mod) => function __require() { + return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; +}; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __reExport = (target, module, copyDefault, desc) => { + if (module && typeof module === "object" || typeof module === "function") { + for (let key of __getOwnPropNames(module)) + if (!__hasOwnProp.call(target, key) && (copyDefault || key !== "default")) + __defProp(target, key, { get: () => module[key], enumerable: !(desc = __getOwnPropDesc(module, key)) || desc.enumerable }); + } + return target; +}; +var __toCommonJS = /* @__PURE__ */ ((cache2) => { + return (module, temp) => { + return cache2 && cache2.get(module) || (temp = __reExport(__markAsModule({}), module, 1), cache2 && cache2.set(module, temp), temp); + }; +})(typeof WeakMap !== "undefined" ? /* @__PURE__ */ new WeakMap() : 0); +var __async = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; +function isPathSpec(path) { + return path instanceof String && cache.has(path); +} +function toPaths(pathSpec) { + return cache.get(pathSpec) || []; +} +var cache; +var init_pathspec = __esm({ + "src/lib/args/pathspec.ts"() { + cache = /* @__PURE__ */ new WeakMap(); + } +}); + +// src/lib/errors/git-error.ts +var GitError; +var init_git_error = __esm({ + "src/lib/errors/git-error.ts"() { + GitError = class extends Error { + constructor(task, message) { + super(message); + this.task = task; + Object.setPrototypeOf(this, new.target.prototype); + } + }; + } +}); + +// src/lib/errors/git-response-error.ts +var GitResponseError; +var init_git_response_error = __esm({ + "src/lib/errors/git-response-error.ts"() { + init_git_error(); + GitResponseError = class extends GitError { + constructor(git, message) { + super(void 0, message || String(git)); + this.git = git; + } + }; + } +}); + +// src/lib/errors/task-configuration-error.ts +var TaskConfigurationError; +var init_task_configuration_error = __esm({ + "src/lib/errors/task-configuration-error.ts"() { + init_git_error(); + TaskConfigurationError = class extends GitError { + constructor(message) { + super(void 0, message); + } + }; + } +}); +function asFunction(source) { + return typeof source === "function" ? source : NOOP; +} +function isUserFunction(source) { + return typeof source === "function" && source !== NOOP; +} +function splitOn(input, char) { + const index = input.indexOf(char); + if (index <= 0) { + return [input, ""]; + } + return [input.substr(0, index), input.substr(index + 1)]; +} +function first$1(input, offset = 0) { + return isArrayLike$c(input) && input.length > offset ? input[offset] : void 0; +} +function last$2(input, offset = 0) { + if (isArrayLike$c(input) && input.length > offset) { + return input[input.length - 1 - offset]; + } +} +function isArrayLike$c(input) { + return !!(input && typeof input.length === "number"); +} +function toLinesWithContent(input = "", trimmed2 = true, separator = "\n") { + return input.split(separator).reduce((output, line) => { + const lineContent = trimmed2 ? line.trim() : line; + if (lineContent) { + output.push(lineContent); + } + return output; + }, []); +} +function forEachLineWithContent(input, callback) { + return toLinesWithContent(input, true).map((line) => callback(line)); +} +function folderExists(path) { + return dist$3.exists(path, dist$3.FOLDER); +} +function append$1(target, item) { + if (Array.isArray(target)) { + if (!target.includes(item)) { + target.push(item); + } + } else { + target.add(item); + } + return item; +} +function including(target, item) { + if (Array.isArray(target) && !target.includes(item)) { + target.push(item); + } + return target; +} +function remove$1(target, item) { + if (Array.isArray(target)) { + const index = target.indexOf(item); + if (index >= 0) { + target.splice(index, 1); + } + } else { + target.delete(item); + } + return item; +} +function asArray(source) { + return Array.isArray(source) ? source : [source]; +} +function asStringArray(source) { + return asArray(source).map(String); +} +function asNumber(source, onNaN = 0) { + if (source == null) { + return onNaN; + } + const num = parseInt(source, 10); + return isNaN(num) ? onNaN : num; +} +function prefixedArray(input, prefix) { + const output = []; + for (let i = 0, max = input.length; i < max; i++) { + output.push(prefix, input[i]); + } + return output; +} +function bufferToString(input) { + return (Array.isArray(input) ? Buffer.concat(input) : input).toString("utf-8"); +} +function pick(source, properties) { + return Object.assign({}, ...properties.map((property) => property in source ? { [property]: source[property] } : {})); +} +function delay(duration = 0) { + return new Promise((done) => setTimeout(done, duration)); +} +var NULL$1, NOOP, objectToString$3; +var init_util = __esm({ + "src/lib/utils/util.ts"() { + NULL$1 = "\0"; + NOOP = () => { + }; + objectToString$3 = Object.prototype.toString.call.bind(Object.prototype.toString); + } +}); + +// src/lib/utils/argument-filters.ts +function filterType(input, filter, def) { + if (filter(input)) { + return input; + } + return arguments.length > 2 ? def : void 0; +} +function filterPrimitives(input, omit) { + const type = isPathSpec(input) ? "string" : typeof input; + return /number|string|boolean/.test(type) && (!omit || !omit.includes(type)); +} +function filterPlainObject(input) { + return !!input && objectToString$3(input) === "[object Object]"; +} +function filterFunction(input) { + return typeof input === "function"; +} +var filterArray, filterString, filterStringArray, filterStringOrStringArray, filterHasLength; +var init_argument_filters = __esm({ + "src/lib/utils/argument-filters.ts"() { + init_util(); + init_pathspec(); + filterArray = (input) => { + return Array.isArray(input); + }; + filterString = (input) => { + return typeof input === "string"; + }; + filterStringArray = (input) => { + return Array.isArray(input) && input.every(filterString); + }; + filterStringOrStringArray = (input) => { + return filterString(input) || Array.isArray(input) && input.every(filterString); + }; + filterHasLength = (input) => { + if (input == null || "number|boolean|function".includes(typeof input)) { + return false; + } + return Array.isArray(input) || typeof input === "string" || typeof input.length === "number"; + }; + } +}); + +// src/lib/utils/exit-codes.ts +var ExitCodes; +var init_exit_codes = __esm({ + "src/lib/utils/exit-codes.ts"() { + ExitCodes = /* @__PURE__ */ ((ExitCodes2) => { + ExitCodes2[ExitCodes2["SUCCESS"] = 0] = "SUCCESS"; + ExitCodes2[ExitCodes2["ERROR"] = 1] = "ERROR"; + ExitCodes2[ExitCodes2["NOT_FOUND"] = -2] = "NOT_FOUND"; + ExitCodes2[ExitCodes2["UNCLEAN"] = 128] = "UNCLEAN"; + return ExitCodes2; + })(ExitCodes || {}); + } +}); + +// src/lib/utils/git-output-streams.ts +var GitOutputStreams; +var init_git_output_streams = __esm({ + "src/lib/utils/git-output-streams.ts"() { + GitOutputStreams = class { + constructor(stdOut, stdErr) { + this.stdOut = stdOut; + this.stdErr = stdErr; + } + asStrings() { + return new GitOutputStreams(this.stdOut.toString("utf8"), this.stdErr.toString("utf8")); + } + }; + } +}); + +// src/lib/utils/line-parser.ts +var LineParser, RemoteLineParser; +var init_line_parser = __esm({ + "src/lib/utils/line-parser.ts"() { + LineParser = class { + constructor(regExp, useMatches) { + this.matches = []; + this.parse = (line, target) => { + this.resetMatches(); + if (!this._regExp.every((reg, index) => this.addMatch(reg, index, line(index)))) { + return false; + } + return this.useMatches(target, this.prepareMatches()) !== false; + }; + this._regExp = Array.isArray(regExp) ? regExp : [regExp]; + if (useMatches) { + this.useMatches = useMatches; + } + } + useMatches(target, match) { + throw new Error(`LineParser:useMatches not implemented`); + } + resetMatches() { + this.matches.length = 0; + } + prepareMatches() { + return this.matches; + } + addMatch(reg, index, line) { + const matched = line && reg.exec(line); + if (matched) { + this.pushMatch(index, matched); + } + return !!matched; + } + pushMatch(_index, matched) { + this.matches.push(...matched.slice(1)); + } + }; + RemoteLineParser = class extends LineParser { + addMatch(reg, index, line) { + return /^remote:\s/.test(String(line)) && super.addMatch(reg, index, line); + } + pushMatch(index, matched) { + if (index > 0 || matched.length > 1) { + super.pushMatch(index, matched); + } + } + }; + } +}); + +// src/lib/utils/simple-git-options.ts +function createInstanceConfig(...options) { + const baseDir = process.cwd(); + const config = Object.assign(__spreadValues({ baseDir }, defaultOptions$2), ...options.filter((o) => typeof o === "object" && o)); + config.baseDir = config.baseDir || baseDir; + config.trimmed = config.trimmed === true; + return config; +} +var defaultOptions$2; +var init_simple_git_options = __esm({ + "src/lib/utils/simple-git-options.ts"() { + defaultOptions$2 = { + binary: "git", + maxConcurrentProcesses: 5, + config: [], + trimmed: false + }; + } +}); + +// src/lib/utils/task-options.ts +function appendTaskOptions(options, commands = []) { + if (!filterPlainObject(options)) { + return commands; + } + return Object.keys(options).reduce((commands2, key) => { + const value = options[key]; + if (isPathSpec(value)) { + commands2.push(value); + } else if (filterPrimitives(value, ["boolean"])) { + commands2.push(key + "=" + value); + } else { + commands2.push(key); + } + return commands2; + }, commands); +} +function getTrailingOptions(args, initialPrimitive = 0, objectOnly = false) { + const command = []; + for (let i = 0, max = initialPrimitive < 0 ? args.length : initialPrimitive; i < max; i++) { + if ("string|number".includes(typeof args[i])) { + command.push(String(args[i])); + } + } + appendTaskOptions(trailingOptionsArgument(args), command); + if (!objectOnly) { + command.push(...trailingArrayArgument(args)); + } + return command; +} +function trailingArrayArgument(args) { + const hasTrailingCallback = typeof last$2(args) === "function"; + return filterType(last$2(args, hasTrailingCallback ? 1 : 0), filterArray, []); +} +function trailingOptionsArgument(args) { + const hasTrailingCallback = filterFunction(last$2(args)); + return filterType(last$2(args, hasTrailingCallback ? 1 : 0), filterPlainObject); +} +function trailingFunctionArgument(args, includeNoop = true) { + const callback = asFunction(last$2(args)); + return includeNoop || isUserFunction(callback) ? callback : void 0; +} +var init_task_options = __esm({ + "src/lib/utils/task-options.ts"() { + init_argument_filters(); + init_util(); + init_pathspec(); + } +}); + +// src/lib/utils/task-parser.ts +function callTaskParser(parser3, streams) { + return parser3(streams.stdOut, streams.stdErr); +} +function parseStringResponse(result, parsers12, texts, trim = true) { + asArray(texts).forEach((text) => { + for (let lines = toLinesWithContent(text, trim), i = 0, max = lines.length; i < max; i++) { + const line = (offset = 0) => { + if (i + offset >= max) { + return; + } + return lines[i + offset]; + }; + parsers12.some(({ parse }) => parse(line, result)); + } + }); + return result; +} +var init_task_parser = __esm({ + "src/lib/utils/task-parser.ts"() { + init_util(); + } +}); + +// src/lib/utils/index.ts +var utils_exports = {}; +__export(utils_exports, { + ExitCodes: () => ExitCodes, + GitOutputStreams: () => GitOutputStreams, + LineParser: () => LineParser, + NOOP: () => NOOP, + NULL: () => NULL$1, + RemoteLineParser: () => RemoteLineParser, + append: () => append$1, + appendTaskOptions: () => appendTaskOptions, + asArray: () => asArray, + asFunction: () => asFunction, + asNumber: () => asNumber, + asStringArray: () => asStringArray, + bufferToString: () => bufferToString, + callTaskParser: () => callTaskParser, + createInstanceConfig: () => createInstanceConfig, + delay: () => delay, + filterArray: () => filterArray, + filterFunction: () => filterFunction, + filterHasLength: () => filterHasLength, + filterPlainObject: () => filterPlainObject, + filterPrimitives: () => filterPrimitives, + filterString: () => filterString, + filterStringArray: () => filterStringArray, + filterStringOrStringArray: () => filterStringOrStringArray, + filterType: () => filterType, + first: () => first$1, + folderExists: () => folderExists, + forEachLineWithContent: () => forEachLineWithContent, + getTrailingOptions: () => getTrailingOptions, + including: () => including, + isUserFunction: () => isUserFunction, + last: () => last$2, + objectToString: () => objectToString$3, + parseStringResponse: () => parseStringResponse, + pick: () => pick, + prefixedArray: () => prefixedArray, + remove: () => remove$1, + splitOn: () => splitOn, + toLinesWithContent: () => toLinesWithContent, + trailingFunctionArgument: () => trailingFunctionArgument, + trailingOptionsArgument: () => trailingOptionsArgument +}); +var init_utils = __esm({ + "src/lib/utils/index.ts"() { + init_argument_filters(); + init_exit_codes(); + init_git_output_streams(); + init_line_parser(); + init_simple_git_options(); + init_task_options(); + init_task_parser(); + init_util(); + } +}); + +// src/lib/tasks/check-is-repo.ts +var check_is_repo_exports = {}; +__export(check_is_repo_exports, { + CheckRepoActions: () => CheckRepoActions, + checkIsBareRepoTask: () => checkIsBareRepoTask, + checkIsRepoRootTask: () => checkIsRepoRootTask, + checkIsRepoTask: () => checkIsRepoTask +}); +function checkIsRepoTask(action) { + switch (action) { + case "bare" /* BARE */: + return checkIsBareRepoTask(); + case "root" /* IS_REPO_ROOT */: + return checkIsRepoRootTask(); + } + const commands = ["rev-parse", "--is-inside-work-tree"]; + return { + commands, + format: "utf-8", + onError, + parser + }; +} +function checkIsRepoRootTask() { + const commands = ["rev-parse", "--git-dir"]; + return { + commands, + format: "utf-8", + onError, + parser(path) { + return /^\.(git)?$/.test(path.trim()); + } + }; +} +function checkIsBareRepoTask() { + const commands = ["rev-parse", "--is-bare-repository"]; + return { + commands, + format: "utf-8", + onError, + parser + }; +} +function isNotRepoMessage(error) { + return /(Not a git repository|Kein Git-Repository)/i.test(String(error)); +} +var CheckRepoActions, onError, parser; +var init_check_is_repo = __esm({ + "src/lib/tasks/check-is-repo.ts"() { + init_utils(); + CheckRepoActions = /* @__PURE__ */ ((CheckRepoActions2) => { + CheckRepoActions2["BARE"] = "bare"; + CheckRepoActions2["IN_TREE"] = "tree"; + CheckRepoActions2["IS_REPO_ROOT"] = "root"; + return CheckRepoActions2; + })(CheckRepoActions || {}); + onError = ({ exitCode }, error, done, fail) => { + if (exitCode === 128 /* UNCLEAN */ && isNotRepoMessage(error)) { + return done(Buffer.from("false")); + } + fail(error); + }; + parser = (text) => { + return text.trim() === "true"; + }; + } +}); + +// src/lib/responses/CleanSummary.ts +function cleanSummaryParser(dryRun, text) { + const summary = new CleanResponse(dryRun); + const regexp = dryRun ? dryRunRemovalRegexp : removalRegexp; + toLinesWithContent(text).forEach((line) => { + const removed = line.replace(regexp, ""); + summary.paths.push(removed); + (isFolderRegexp.test(removed) ? summary.folders : summary.files).push(removed); + }); + return summary; +} +var CleanResponse, removalRegexp, dryRunRemovalRegexp, isFolderRegexp; +var init_CleanSummary = __esm({ + "src/lib/responses/CleanSummary.ts"() { + init_utils(); + CleanResponse = class { + constructor(dryRun) { + this.dryRun = dryRun; + this.paths = []; + this.files = []; + this.folders = []; + } + }; + removalRegexp = /^[a-z]+\s*/i; + dryRunRemovalRegexp = /^[a-z]+\s+[a-z]+\s*/i; + isFolderRegexp = /\/$/; + } +}); + +// src/lib/tasks/task.ts +var task_exports = {}; +__export(task_exports, { + EMPTY_COMMANDS: () => EMPTY_COMMANDS, + adhocExecTask: () => adhocExecTask, + configurationErrorTask: () => configurationErrorTask, + isBufferTask: () => isBufferTask, + isEmptyTask: () => isEmptyTask, + straightThroughBufferTask: () => straightThroughBufferTask, + straightThroughStringTask: () => straightThroughStringTask +}); +function adhocExecTask(parser3) { + return { + commands: EMPTY_COMMANDS, + format: "empty", + parser: parser3 + }; +} +function configurationErrorTask(error) { + return { + commands: EMPTY_COMMANDS, + format: "empty", + parser() { + throw typeof error === "string" ? new TaskConfigurationError(error) : error; + } + }; +} +function straightThroughStringTask(commands, trimmed2 = false) { + return { + commands, + format: "utf-8", + parser(text) { + return trimmed2 ? String(text).trim() : text; + } + }; +} +function straightThroughBufferTask(commands) { + return { + commands, + format: "buffer", + parser(buffer) { + return buffer; + } + }; +} +function isBufferTask(task) { + return task.format === "buffer"; +} +function isEmptyTask(task) { + return task.format === "empty" || !task.commands.length; +} +var EMPTY_COMMANDS; +var init_task = __esm({ + "src/lib/tasks/task.ts"() { + init_task_configuration_error(); + EMPTY_COMMANDS = []; + } +}); + +// src/lib/tasks/clean.ts +var clean_exports = {}; +__export(clean_exports, { + CONFIG_ERROR_INTERACTIVE_MODE: () => CONFIG_ERROR_INTERACTIVE_MODE, + CONFIG_ERROR_MODE_REQUIRED: () => CONFIG_ERROR_MODE_REQUIRED, + CONFIG_ERROR_UNKNOWN_OPTION: () => CONFIG_ERROR_UNKNOWN_OPTION, + CleanOptions: () => CleanOptions, + cleanTask: () => cleanTask, + cleanWithOptionsTask: () => cleanWithOptionsTask, + isCleanOptionsArray: () => isCleanOptionsArray +}); +function cleanWithOptionsTask(mode, customArgs) { + const { cleanMode, options, valid } = getCleanOptions(mode); + if (!cleanMode) { + return configurationErrorTask(CONFIG_ERROR_MODE_REQUIRED); + } + if (!valid.options) { + return configurationErrorTask(CONFIG_ERROR_UNKNOWN_OPTION + JSON.stringify(mode)); + } + options.push(...customArgs); + if (options.some(isInteractiveMode)) { + return configurationErrorTask(CONFIG_ERROR_INTERACTIVE_MODE); + } + return cleanTask(cleanMode, options); +} +function cleanTask(mode, customArgs) { + const commands = ["clean", `-${mode}`, ...customArgs]; + return { + commands, + format: "utf-8", + parser(text) { + return cleanSummaryParser(mode === "n" /* DRY_RUN */, text); + } + }; +} +function isCleanOptionsArray(input) { + return Array.isArray(input) && input.every((test) => CleanOptionValues.has(test)); +} +function getCleanOptions(input) { + let cleanMode; + let options = []; + let valid = { cleanMode: false, options: true }; + input.replace(/[^a-z]i/g, "").split("").forEach((char) => { + if (isCleanMode(char)) { + cleanMode = char; + valid.cleanMode = true; + } else { + valid.options = valid.options && isKnownOption(options[options.length] = `-${char}`); + } + }); + return { + cleanMode, + options, + valid + }; +} +function isCleanMode(cleanMode) { + return cleanMode === "f" /* FORCE */ || cleanMode === "n" /* DRY_RUN */; +} +function isKnownOption(option) { + return /^-[a-z]$/i.test(option) && CleanOptionValues.has(option.charAt(1)); +} +function isInteractiveMode(option) { + if (/^-[^\-]/.test(option)) { + return option.indexOf("i") > 0; + } + return option === "--interactive"; +} +var CONFIG_ERROR_INTERACTIVE_MODE, CONFIG_ERROR_MODE_REQUIRED, CONFIG_ERROR_UNKNOWN_OPTION, CleanOptions, CleanOptionValues; +var init_clean = __esm({ + "src/lib/tasks/clean.ts"() { + init_CleanSummary(); + init_utils(); + init_task(); + CONFIG_ERROR_INTERACTIVE_MODE = "Git clean interactive mode is not supported"; + CONFIG_ERROR_MODE_REQUIRED = 'Git clean mode parameter ("n" or "f") is required'; + CONFIG_ERROR_UNKNOWN_OPTION = "Git clean unknown option found in: "; + CleanOptions = /* @__PURE__ */ ((CleanOptions2) => { + CleanOptions2["DRY_RUN"] = "n"; + CleanOptions2["FORCE"] = "f"; + CleanOptions2["IGNORED_INCLUDED"] = "x"; + CleanOptions2["IGNORED_ONLY"] = "X"; + CleanOptions2["EXCLUDING"] = "e"; + CleanOptions2["QUIET"] = "q"; + CleanOptions2["RECURSIVE"] = "d"; + return CleanOptions2; + })(CleanOptions || {}); + CleanOptionValues = /* @__PURE__ */ new Set([ + "i", + ...asStringArray(Object.values(CleanOptions)) + ]); + } +}); + +// src/lib/responses/ConfigList.ts +function configListParser(text) { + const config = new ConfigList(); + for (const item of configParser(text)) { + config.addValue(item.file, String(item.key), item.value); + } + return config; +} +function configGetParser(text, key) { + let value = null; + const values = []; + const scopes = /* @__PURE__ */ new Map(); + for (const item of configParser(text, key)) { + if (item.key !== key) { + continue; + } + values.push(value = item.value); + if (!scopes.has(item.file)) { + scopes.set(item.file, []); + } + scopes.get(item.file).push(value); + } + return { + key, + paths: Array.from(scopes.keys()), + scopes, + value, + values + }; +} +function configFilePath(filePath) { + return filePath.replace(/^(file):/, ""); +} +function* configParser(text, requestedKey = null) { + const lines = text.split("\0"); + for (let i = 0, max = lines.length - 1; i < max; ) { + const file = configFilePath(lines[i++]); + let value = lines[i++]; + let key = requestedKey; + if (value.includes("\n")) { + const line = splitOn(value, "\n"); + key = line[0]; + value = line[1]; + } + yield { file, key, value }; + } +} +var ConfigList; +var init_ConfigList = __esm({ + "src/lib/responses/ConfigList.ts"() { + init_utils(); + ConfigList = class { + constructor() { + this.files = []; + this.values = /* @__PURE__ */ Object.create(null); + } + get all() { + if (!this._all) { + this._all = this.files.reduce((all, file) => { + return Object.assign(all, this.values[file]); + }, {}); + } + return this._all; + } + addFile(file) { + if (!(file in this.values)) { + const latest = last$2(this.files); + this.values[file] = latest ? Object.create(this.values[latest]) : {}; + this.files.push(file); + } + return this.values[file]; + } + addValue(file, key, value) { + const values = this.addFile(file); + if (!values.hasOwnProperty(key)) { + values[key] = value; + } else if (Array.isArray(values[key])) { + values[key].push(value); + } else { + values[key] = [values[key], value]; + } + this._all = void 0; + } + }; + } +}); + +// src/lib/tasks/config.ts +function asConfigScope(scope, fallback) { + if (typeof scope === "string" && GitConfigScope.hasOwnProperty(scope)) { + return scope; + } + return fallback; +} +function addConfigTask(key, value, append2, scope) { + const commands = ["config", `--${scope}`]; + if (append2) { + commands.push("--add"); + } + commands.push(key, value); + return { + commands, + format: "utf-8", + parser(text) { + return text; + } + }; +} +function getConfigTask(key, scope) { + const commands = ["config", "--null", "--show-origin", "--get-all", key]; + if (scope) { + commands.splice(1, 0, `--${scope}`); + } + return { + commands, + format: "utf-8", + parser(text) { + return configGetParser(text, key); + } + }; +} +function listConfigTask(scope) { + const commands = ["config", "--list", "--show-origin", "--null"]; + if (scope) { + commands.push(`--${scope}`); + } + return { + commands, + format: "utf-8", + parser(text) { + return configListParser(text); + } + }; +} +function config_default() { + return { + addConfig(key, value, ...rest) { + return this._runTask(addConfigTask(key, value, rest[0] === true, asConfigScope(rest[1], "local" /* local */)), trailingFunctionArgument(arguments)); + }, + getConfig(key, scope) { + return this._runTask(getConfigTask(key, asConfigScope(scope, void 0)), trailingFunctionArgument(arguments)); + }, + listConfig(...rest) { + return this._runTask(listConfigTask(asConfigScope(rest[0], void 0)), trailingFunctionArgument(arguments)); + } + }; +} +var GitConfigScope; +var init_config = __esm({ + "src/lib/tasks/config.ts"() { + init_ConfigList(); + init_utils(); + GitConfigScope = /* @__PURE__ */ ((GitConfigScope2) => { + GitConfigScope2["system"] = "system"; + GitConfigScope2["global"] = "global"; + GitConfigScope2["local"] = "local"; + GitConfigScope2["worktree"] = "worktree"; + return GitConfigScope2; + })(GitConfigScope || {}); + } +}); + +// src/lib/tasks/grep.ts +function grepQueryBuilder(...params) { + return new GrepQuery().param(...params); +} +function parseGrep(grep) { + const paths = /* @__PURE__ */ new Set(); + const results = {}; + forEachLineWithContent(grep, (input) => { + const [path, line, preview] = input.split(NULL$1); + paths.add(path); + (results[path] = results[path] || []).push({ + line: asNumber(line), + path, + preview + }); + }); + return { + paths, + results + }; +} +function grep_default() { + return { + grep(searchTerm) { + const then = trailingFunctionArgument(arguments); + const options = getTrailingOptions(arguments); + for (const option of disallowedOptions) { + if (options.includes(option)) { + return this._runTask(configurationErrorTask(`git.grep: use of "${option}" is not supported.`), then); + } + } + if (typeof searchTerm === "string") { + searchTerm = grepQueryBuilder().param(searchTerm); + } + const commands = ["grep", "--null", "-n", "--full-name", ...options, ...searchTerm]; + return this._runTask({ + commands, + format: "utf-8", + parser(stdOut) { + return parseGrep(stdOut); + } + }, then); + } + }; +} +var disallowedOptions, Query, _a, GrepQuery; +var init_grep = __esm({ + "src/lib/tasks/grep.ts"() { + init_utils(); + init_task(); + disallowedOptions = ["-h"]; + Query = Symbol("grepQuery"); + GrepQuery = class { + constructor() { + this[_a] = []; + } + *[(_a = Query, Symbol.iterator)]() { + for (const query of this[Query]) { + yield query; + } + } + and(...and) { + and.length && this[Query].push("--and", "(", ...prefixedArray(and, "-e"), ")"); + return this; + } + param(...param) { + this[Query].push(...prefixedArray(param, "-e")); + return this; + } + }; + } +}); + +// src/lib/tasks/reset.ts +var reset_exports = {}; +__export(reset_exports, { + ResetMode: () => ResetMode, + getResetMode: () => getResetMode, + resetTask: () => resetTask +}); +function resetTask(mode, customArgs) { + const commands = ["reset"]; + if (isValidResetMode(mode)) { + commands.push(`--${mode}`); + } + commands.push(...customArgs); + return straightThroughStringTask(commands); +} +function getResetMode(mode) { + if (isValidResetMode(mode)) { + return mode; + } + switch (typeof mode) { + case "string": + case "undefined": + return "soft" /* SOFT */; + } + return; +} +function isValidResetMode(mode) { + return ResetModes.includes(mode); +} +var ResetMode, ResetModes; +var init_reset = __esm({ + "src/lib/tasks/reset.ts"() { + init_task(); + ResetMode = /* @__PURE__ */ ((ResetMode2) => { + ResetMode2["MIXED"] = "mixed"; + ResetMode2["SOFT"] = "soft"; + ResetMode2["HARD"] = "hard"; + ResetMode2["MERGE"] = "merge"; + ResetMode2["KEEP"] = "keep"; + return ResetMode2; + })(ResetMode || {}); + ResetModes = Array.from(Object.values(ResetMode)); + } +}); +function createLog() { + return debug$1("simple-git"); +} +function prefixedLogger(to, prefix, forward) { + if (!prefix || !String(prefix).replace(/\s*/, "")) { + return !forward ? to : (message, ...args) => { + to(message, ...args); + forward(message, ...args); + }; + } + return (message, ...args) => { + to(`%s ${message}`, prefix, ...args); + if (forward) { + forward(message, ...args); + } + }; +} +function childLoggerName(name, childDebugger, { namespace: parentNamespace }) { + if (typeof name === "string") { + return name; + } + const childNamespace = childDebugger && childDebugger.namespace || ""; + if (childNamespace.startsWith(parentNamespace)) { + return childNamespace.substr(parentNamespace.length + 1); + } + return childNamespace || parentNamespace; +} +function createLogger(label, verbose, initialStep, infoDebugger = createLog()) { + const labelPrefix = label && `[${label}]` || ""; + const spawned = []; + const debugDebugger = typeof verbose === "string" ? infoDebugger.extend(verbose) : verbose; + const key = childLoggerName(filterType(verbose, filterString), debugDebugger, infoDebugger); + return step(initialStep); + function sibling(name, initial) { + return append$1(spawned, createLogger(label, key.replace(/^[^:]+/, name), initial, infoDebugger)); + } + function step(phase) { + const stepPrefix = phase && `[${phase}]` || ""; + const debug2 = debugDebugger && prefixedLogger(debugDebugger, stepPrefix) || NOOP; + const info = prefixedLogger(infoDebugger, `${labelPrefix} ${stepPrefix}`, debug2); + return Object.assign(debugDebugger ? debug2 : info, { + label, + sibling, + info, + step + }); + } +} +var init_git_logger = __esm({ + "src/lib/git-logger.ts"() { + init_utils(); + debug$1.formatters.L = (value) => String(filterHasLength(value) ? value.length : "-"); + debug$1.formatters.B = (value) => { + if (Buffer.isBuffer(value)) { + return value.toString("utf8"); + } + return objectToString$3(value); + }; + } +}); + +// src/lib/runners/tasks-pending-queue.ts +var _TasksPendingQueue, TasksPendingQueue; +var init_tasks_pending_queue = __esm({ + "src/lib/runners/tasks-pending-queue.ts"() { + init_git_error(); + init_git_logger(); + _TasksPendingQueue = class { + constructor(logLabel = "GitExecutor") { + this.logLabel = logLabel; + this._queue = /* @__PURE__ */ new Map(); + } + withProgress(task) { + return this._queue.get(task); + } + createProgress(task) { + const name = _TasksPendingQueue.getName(task.commands[0]); + const logger = createLogger(this.logLabel, name); + return { + task, + logger, + name + }; + } + push(task) { + const progress = this.createProgress(task); + progress.logger("Adding task to the queue, commands = %o", task.commands); + this._queue.set(task, progress); + return progress; + } + fatal(err) { + for (const [task, { logger }] of Array.from(this._queue.entries())) { + if (task === err.task) { + logger.info(`Failed %o`, err); + logger(`Fatal exception, any as-yet un-started tasks run through this executor will not be attempted`); + } else { + logger.info(`A fatal exception occurred in a previous task, the queue has been purged: %o`, err.message); + } + this.complete(task); + } + if (this._queue.size !== 0) { + throw new Error(`Queue size should be zero after fatal: ${this._queue.size}`); + } + } + complete(task) { + const progress = this.withProgress(task); + if (progress) { + this._queue.delete(task); + } + } + attempt(task) { + const progress = this.withProgress(task); + if (!progress) { + throw new GitError(void 0, "TasksPendingQueue: attempt called for an unknown task"); + } + progress.logger("Starting task"); + return progress; + } + static getName(name = "empty") { + return `task:${name}:${++_TasksPendingQueue.counter}`; + } + }; + TasksPendingQueue = _TasksPendingQueue; + TasksPendingQueue.counter = 0; + } +}); +function pluginContext(task, commands) { + return { + method: first$1(task.commands) || "", + commands + }; +} +function onErrorReceived(target, logger) { + return (err) => { + logger(`[ERROR] child process exception %o`, err); + target.push(Buffer.from(String(err.stack), "ascii")); + }; +} +function onDataReceived(target, name, logger, output) { + return (buffer) => { + logger(`%s received %L bytes`, name, buffer); + output(`%B`, buffer); + target.push(buffer); + }; +} +var GitExecutorChain; +var init_git_executor_chain = __esm({ + "src/lib/runners/git-executor-chain.ts"() { + init_git_error(); + init_task(); + init_utils(); + init_tasks_pending_queue(); + GitExecutorChain = class { + constructor(_executor, _scheduler, _plugins) { + this._executor = _executor; + this._scheduler = _scheduler; + this._plugins = _plugins; + this._chain = Promise.resolve(); + this._queue = new TasksPendingQueue(); + } + get binary() { + return this._executor.binary; + } + get cwd() { + return this._cwd || this._executor.cwd; + } + set cwd(cwd) { + this._cwd = cwd; + } + get env() { + return this._executor.env; + } + get outputHandler() { + return this._executor.outputHandler; + } + chain() { + return this; + } + push(task) { + this._queue.push(task); + return this._chain = this._chain.then(() => this.attemptTask(task)); + } + attemptTask(task) { + return __async(this, null, function* () { + const onScheduleComplete = yield this._scheduler.next(); + const onQueueComplete = () => this._queue.complete(task); + try { + const { logger } = this._queue.attempt(task); + return yield isEmptyTask(task) ? this.attemptEmptyTask(task, logger) : this.attemptRemoteTask(task, logger); + } catch (e) { + throw this.onFatalException(task, e); + } finally { + onQueueComplete(); + onScheduleComplete(); + } + }); + } + onFatalException(task, e) { + const gitError = e instanceof GitError ? Object.assign(e, { task }) : new GitError(task, e && String(e)); + this._chain = Promise.resolve(); + this._queue.fatal(gitError); + return gitError; + } + attemptRemoteTask(task, logger) { + return __async(this, null, function* () { + const args = this._plugins.exec("spawn.args", [...task.commands], pluginContext(task, task.commands)); + const raw = yield this.gitResponse(task, this.binary, args, this.outputHandler, logger.step("SPAWN")); + const outputStreams = yield this.handleTaskData(task, args, raw, logger.step("HANDLE")); + logger(`passing response to task's parser as a %s`, task.format); + if (isBufferTask(task)) { + return callTaskParser(task.parser, outputStreams); + } + return callTaskParser(task.parser, outputStreams.asStrings()); + }); + } + attemptEmptyTask(task, logger) { + return __async(this, null, function* () { + logger(`empty task bypassing child process to call to task's parser`); + return task.parser(this); + }); + } + handleTaskData(task, args, result, logger) { + const { exitCode, rejection, stdOut, stdErr } = result; + return new Promise((done, fail) => { + logger(`Preparing to handle process response exitCode=%d stdOut=`, exitCode); + const { error } = this._plugins.exec("task.error", { error: rejection }, __spreadValues(__spreadValues({}, pluginContext(task, args)), result)); + if (error && task.onError) { + logger.info(`exitCode=%s handling with custom error handler`); + return task.onError(result, error, (newStdOut) => { + logger.info(`custom error handler treated as success`); + logger(`custom error returned a %s`, objectToString$3(newStdOut)); + done(new GitOutputStreams(Array.isArray(newStdOut) ? Buffer.concat(newStdOut) : newStdOut, Buffer.concat(stdErr))); + }, fail); + } + if (error) { + logger.info(`handling as error: exitCode=%s stdErr=%s rejection=%o`, exitCode, stdErr.length, rejection); + return fail(error); + } + logger.info(`retrieving task output complete`); + done(new GitOutputStreams(Buffer.concat(stdOut), Buffer.concat(stdErr))); + }); + } + gitResponse(task, command, args, outputHandler, logger) { + return __async(this, null, function* () { + const outputLogger = logger.sibling("output"); + const spawnOptions = this._plugins.exec("spawn.options", { + cwd: this.cwd, + env: this.env, + windowsHide: true + }, pluginContext(task, task.commands)); + return new Promise((done) => { + const stdOut = []; + const stdErr = []; + logger.info(`%s %o`, command, args); + logger("%O", spawnOptions); + let rejection = this._beforeSpawn(task, args); + if (rejection) { + return done({ + stdOut, + stdErr, + exitCode: 9901, + rejection + }); + } + this._plugins.exec("spawn.before", void 0, __spreadProps(__spreadValues({}, pluginContext(task, args)), { + kill(reason) { + rejection = reason || rejection; + } + })); + const spawned = require$$0$h.spawn(command, args, spawnOptions); + spawned.stdout.on("data", onDataReceived(stdOut, "stdOut", logger, outputLogger.step("stdOut"))); + spawned.stderr.on("data", onDataReceived(stdErr, "stdErr", logger, outputLogger.step("stdErr"))); + spawned.on("error", onErrorReceived(stdErr, logger)); + if (outputHandler) { + logger(`Passing child process stdOut/stdErr to custom outputHandler`); + outputHandler(command, spawned.stdout, spawned.stderr, [...args]); + } + this._plugins.exec("spawn.after", void 0, __spreadProps(__spreadValues({}, pluginContext(task, args)), { + spawned, + close(exitCode, reason) { + done({ + stdOut, + stdErr, + exitCode, + rejection: rejection || reason + }); + }, + kill(reason) { + if (spawned.killed) { + return; + } + rejection = reason; + spawned.kill("SIGINT"); + } + })); + }); + }); + } + _beforeSpawn(task, args) { + let rejection; + this._plugins.exec("spawn.before", void 0, __spreadProps(__spreadValues({}, pluginContext(task, args)), { + kill(reason) { + rejection = reason || rejection; + } + })); + return rejection; + } + }; + } +}); + +// src/lib/runners/git-executor.ts +var git_executor_exports = {}; +__export(git_executor_exports, { + GitExecutor: () => GitExecutor +}); +var GitExecutor; +var init_git_executor = __esm({ + "src/lib/runners/git-executor.ts"() { + init_git_executor_chain(); + GitExecutor = class { + constructor(binary = "git", cwd, _scheduler, _plugins) { + this.binary = binary; + this.cwd = cwd; + this._scheduler = _scheduler; + this._plugins = _plugins; + this._chain = new GitExecutorChain(this, this._scheduler, this._plugins); + } + chain() { + return new GitExecutorChain(this, this._scheduler, this._plugins); + } + push(task) { + return this._chain.push(task); + } + }; + } +}); + +// src/lib/task-callback.ts +function taskCallback(task, response, callback = NOOP) { + const onSuccess = (data) => { + callback(null, data); + }; + const onError2 = (err) => { + if ((err == null ? void 0 : err.task) === task) { + callback(err instanceof GitResponseError ? addDeprecationNoticeToError(err) : err, void 0); + } + }; + response.then(onSuccess, onError2); +} +function addDeprecationNoticeToError(err) { + let log = (name) => { + console.warn(`simple-git deprecation notice: accessing GitResponseError.${name} should be GitResponseError.git.${name}, this will no longer be available in version 3`); + log = NOOP; + }; + return Object.create(err, Object.getOwnPropertyNames(err.git).reduce(descriptorReducer, {})); + function descriptorReducer(all, name) { + if (name in err) { + return all; + } + all[name] = { + enumerable: false, + configurable: false, + get() { + log(name); + return err.git[name]; + } + }; + return all; + } +} +var init_task_callback = __esm({ + "src/lib/task-callback.ts"() { + init_git_response_error(); + init_utils(); + } +}); + +// src/lib/tasks/change-working-directory.ts +function changeWorkingDirectoryTask(directory, root) { + return adhocExecTask((instance) => { + if (!folderExists(directory)) { + throw new Error(`Git.cwd: cannot change to non-directory "${directory}"`); + } + return (root || instance).cwd = directory; + }); +} +var init_change_working_directory = __esm({ + "src/lib/tasks/change-working-directory.ts"() { + init_utils(); + init_task(); + } +}); + +// src/lib/tasks/checkout.ts +function checkoutTask(args) { + const commands = ["checkout", ...args]; + if (commands[1] === "-b" && commands.includes("-B")) { + commands[1] = remove$1(commands, "-B"); + } + return straightThroughStringTask(commands); +} +function checkout_default() { + return { + checkout() { + return this._runTask(checkoutTask(getTrailingOptions(arguments, 1)), trailingFunctionArgument(arguments)); + }, + checkoutBranch(branchName, startPoint) { + return this._runTask(checkoutTask(["-b", branchName, startPoint, ...getTrailingOptions(arguments)]), trailingFunctionArgument(arguments)); + }, + checkoutLocalBranch(branchName) { + return this._runTask(checkoutTask(["-b", branchName, ...getTrailingOptions(arguments)]), trailingFunctionArgument(arguments)); + } + }; +} +var init_checkout = __esm({ + "src/lib/tasks/checkout.ts"() { + init_utils(); + init_task(); + } +}); + +// src/lib/parsers/parse-commit.ts +function parseCommitResult(stdOut) { + const result = { + author: null, + branch: "", + commit: "", + root: false, + summary: { + changes: 0, + insertions: 0, + deletions: 0 + } + }; + return parseStringResponse(result, parsers, stdOut); +} +var parsers; +var init_parse_commit = __esm({ + "src/lib/parsers/parse-commit.ts"() { + init_utils(); + parsers = [ + new LineParser(/^\[([^\s]+)( \([^)]+\))? ([^\]]+)/, (result, [branch, root, commit]) => { + result.branch = branch; + result.commit = commit; + result.root = !!root; + }), + new LineParser(/\s*Author:\s(.+)/i, (result, [author]) => { + const parts = author.split("<"); + const email = parts.pop(); + if (!email || !email.includes("@")) { + return; + } + result.author = { + email: email.substr(0, email.length - 1), + name: parts.join("<").trim() + }; + }), + new LineParser(/(\d+)[^,]*(?:,\s*(\d+)[^,]*)(?:,\s*(\d+))/g, (result, [changes, insertions, deletions]) => { + result.summary.changes = parseInt(changes, 10) || 0; + result.summary.insertions = parseInt(insertions, 10) || 0; + result.summary.deletions = parseInt(deletions, 10) || 0; + }), + new LineParser(/^(\d+)[^,]*(?:,\s*(\d+)[^(]+\(([+-]))?/, (result, [changes, lines, direction]) => { + result.summary.changes = parseInt(changes, 10) || 0; + const count = parseInt(lines, 10) || 0; + if (direction === "-") { + result.summary.deletions = count; + } else if (direction === "+") { + result.summary.insertions = count; + } + }) + ]; + } +}); + +// src/lib/tasks/commit.ts +function commitTask(message, files, customArgs) { + const commands = [ + "-c", + "core.abbrev=40", + "commit", + ...prefixedArray(message, "-m"), + ...files, + ...customArgs + ]; + return { + commands, + format: "utf-8", + parser: parseCommitResult + }; +} +function commit_default() { + return { + commit(message, ...rest) { + const next = trailingFunctionArgument(arguments); + const task = rejectDeprecatedSignatures(message) || commitTask(asArray(message), asArray(filterType(rest[0], filterStringOrStringArray, [])), [...filterType(rest[1], filterArray, []), ...getTrailingOptions(arguments, 0, true)]); + return this._runTask(task, next); + } + }; + function rejectDeprecatedSignatures(message) { + return !filterStringOrStringArray(message) && configurationErrorTask(`git.commit: requires the commit message to be supplied as a string/string[]`); + } +} +var init_commit = __esm({ + "src/lib/tasks/commit.ts"() { + init_parse_commit(); + init_utils(); + init_task(); + } +}); + +// src/lib/tasks/hash-object.ts +function hashObjectTask(filePath, write) { + const commands = ["hash-object", filePath]; + if (write) { + commands.push("-w"); + } + return straightThroughStringTask(commands, true); +} +var init_hash_object = __esm({ + "src/lib/tasks/hash-object.ts"() { + init_task(); + } +}); + +// src/lib/responses/InitSummary.ts +function parseInit(bare, path, text) { + const response = String(text).trim(); + let result; + if (result = initResponseRegex.exec(response)) { + return new InitSummary(bare, path, false, result[1]); + } + if (result = reInitResponseRegex.exec(response)) { + return new InitSummary(bare, path, true, result[1]); + } + let gitDir = ""; + const tokens = response.split(" "); + while (tokens.length) { + const token = tokens.shift(); + if (token === "in") { + gitDir = tokens.join(" "); + break; + } + } + return new InitSummary(bare, path, /^re/i.test(response), gitDir); +} +var InitSummary, initResponseRegex, reInitResponseRegex; +var init_InitSummary = __esm({ + "src/lib/responses/InitSummary.ts"() { + InitSummary = class { + constructor(bare, path, existing, gitDir) { + this.bare = bare; + this.path = path; + this.existing = existing; + this.gitDir = gitDir; + } + }; + initResponseRegex = /^Init.+ repository in (.+)$/; + reInitResponseRegex = /^Rein.+ in (.+)$/; + } +}); + +// src/lib/tasks/init.ts +function hasBareCommand(command) { + return command.includes(bareCommand); +} +function initTask(bare = false, path, customArgs) { + const commands = ["init", ...customArgs]; + if (bare && !hasBareCommand(commands)) { + commands.splice(1, 0, bareCommand); + } + return { + commands, + format: "utf-8", + parser(text) { + return parseInit(commands.includes("--bare"), path, text); + } + }; +} +var bareCommand; +var init_init = __esm({ + "src/lib/tasks/init.ts"() { + init_InitSummary(); + bareCommand = "--bare"; + } +}); + +// src/lib/args/log-format.ts +function logFormatFromCommand(customArgs) { + for (let i = 0; i < customArgs.length; i++) { + const format = logFormatRegex.exec(customArgs[i]); + if (format) { + return `--${format[1]}`; + } + } + return "" /* NONE */; +} +function isLogFormat(customArg) { + return logFormatRegex.test(customArg); +} +var logFormatRegex; +var init_log_format = __esm({ + "src/lib/args/log-format.ts"() { + logFormatRegex = /^--(stat|numstat|name-only|name-status)(=|$)/; + } +}); + +// src/lib/responses/DiffSummary.ts +var DiffSummary; +var init_DiffSummary = __esm({ + "src/lib/responses/DiffSummary.ts"() { + DiffSummary = class { + constructor() { + this.changed = 0; + this.deletions = 0; + this.insertions = 0; + this.files = []; + } + }; + } +}); + +// src/lib/parsers/parse-diff-summary.ts +function getDiffParser(format = "" /* NONE */) { + const parser3 = diffSummaryParsers[format]; + return (stdOut) => parseStringResponse(new DiffSummary(), parser3, stdOut, false); +} +var statParser, numStatParser, nameOnlyParser, nameStatusParser, diffSummaryParsers; +var init_parse_diff_summary = __esm({ + "src/lib/parsers/parse-diff-summary.ts"() { + init_log_format(); + init_DiffSummary(); + init_utils(); + statParser = [ + new LineParser(/(.+)\s+\|\s+(\d+)(\s+[+\-]+)?$/, (result, [file, changes, alterations = ""]) => { + result.files.push({ + file: file.trim(), + changes: asNumber(changes), + insertions: alterations.replace(/[^+]/g, "").length, + deletions: alterations.replace(/[^-]/g, "").length, + binary: false + }); + }), + new LineParser(/(.+) \|\s+Bin ([0-9.]+) -> ([0-9.]+) ([a-z]+)/, (result, [file, before, after]) => { + result.files.push({ + file: file.trim(), + before: asNumber(before), + after: asNumber(after), + binary: true + }); + }), + new LineParser(/(\d+) files? changed\s*((?:, \d+ [^,]+){0,2})/, (result, [changed, summary]) => { + const inserted = /(\d+) i/.exec(summary); + const deleted = /(\d+) d/.exec(summary); + result.changed = asNumber(changed); + result.insertions = asNumber(inserted == null ? void 0 : inserted[1]); + result.deletions = asNumber(deleted == null ? void 0 : deleted[1]); + }) + ]; + numStatParser = [ + new LineParser(/(\d+)\t(\d+)\t(.+)$/, (result, [changesInsert, changesDelete, file]) => { + const insertions = asNumber(changesInsert); + const deletions = asNumber(changesDelete); + result.changed++; + result.insertions += insertions; + result.deletions += deletions; + result.files.push({ + file, + changes: insertions + deletions, + insertions, + deletions, + binary: false + }); + }), + new LineParser(/-\t-\t(.+)$/, (result, [file]) => { + result.changed++; + result.files.push({ + file, + after: 0, + before: 0, + binary: true + }); + }) + ]; + nameOnlyParser = [ + new LineParser(/(.+)$/, (result, [file]) => { + result.changed++; + result.files.push({ + file, + changes: 0, + insertions: 0, + deletions: 0, + binary: false + }); + }) + ]; + nameStatusParser = [ + new LineParser(/([ACDMRTUXB])\s*(.+)$/, (result, [_status, file]) => { + result.changed++; + result.files.push({ + file, + changes: 0, + insertions: 0, + deletions: 0, + binary: false + }); + }) + ]; + diffSummaryParsers = { + ["" /* NONE */]: statParser, + ["--stat" /* STAT */]: statParser, + ["--numstat" /* NUM_STAT */]: numStatParser, + ["--name-status" /* NAME_STATUS */]: nameStatusParser, + ["--name-only" /* NAME_ONLY */]: nameOnlyParser + }; + } +}); + +// src/lib/parsers/parse-list-log-summary.ts +function lineBuilder(tokens, fields) { + return fields.reduce((line, field, index) => { + line[field] = tokens[index] || ""; + return line; + }, /* @__PURE__ */ Object.create({ diff: null })); +} +function createListLogSummaryParser(splitter = SPLITTER, fields = defaultFieldNames, logFormat = "" /* NONE */) { + const parseDiffResult = getDiffParser(logFormat); + return function(stdOut) { + const all = toLinesWithContent(stdOut, true, START_BOUNDARY).map(function(item) { + const lineDetail = item.trim().split(COMMIT_BOUNDARY); + const listLogLine = lineBuilder(lineDetail[0].trim().split(splitter), fields); + if (lineDetail.length > 1 && !!lineDetail[1].trim()) { + listLogLine.diff = parseDiffResult(lineDetail[1]); + } + return listLogLine; + }); + return { + all, + latest: all.length && all[0] || null, + total: all.length + }; + }; +} +var START_BOUNDARY, COMMIT_BOUNDARY, SPLITTER, defaultFieldNames; +var init_parse_list_log_summary = __esm({ + "src/lib/parsers/parse-list-log-summary.ts"() { + init_utils(); + init_parse_diff_summary(); + init_log_format(); + START_BOUNDARY = "\xF2\xF2\xF2\xF2\xF2\xF2 "; + COMMIT_BOUNDARY = " \xF2\xF2"; + SPLITTER = " \xF2 "; + defaultFieldNames = ["hash", "date", "message", "refs", "author_name", "author_email"]; + } +}); + +// src/lib/tasks/diff.ts +var diff_exports = {}; +__export(diff_exports, { + diffSummaryTask: () => diffSummaryTask, + validateLogFormatConfig: () => validateLogFormatConfig +}); +function diffSummaryTask(customArgs) { + let logFormat = logFormatFromCommand(customArgs); + const commands = ["diff"]; + if (logFormat === "" /* NONE */) { + logFormat = "--stat" /* STAT */; + commands.push("--stat=4096"); + } + commands.push(...customArgs); + return validateLogFormatConfig(commands) || { + commands, + format: "utf-8", + parser: getDiffParser(logFormat) + }; +} +function validateLogFormatConfig(customArgs) { + const flags = customArgs.filter(isLogFormat); + if (flags.length > 1) { + return configurationErrorTask(`Summary flags are mutually exclusive - pick one of ${flags.join(",")}`); + } + if (flags.length && customArgs.includes("-z")) { + return configurationErrorTask(`Summary flag ${flags} parsing is not compatible with null termination option '-z'`); + } +} +var init_diff = __esm({ + "src/lib/tasks/diff.ts"() { + init_log_format(); + init_parse_diff_summary(); + init_task(); + } +}); + +// src/lib/tasks/log.ts +function prettyFormat(format, splitter) { + const fields = []; + const formatStr = []; + Object.keys(format).forEach((field) => { + fields.push(field); + formatStr.push(String(format[field])); + }); + return [fields, formatStr.join(splitter)]; +} +function userOptions(input) { + return Object.keys(input).reduce((out, key) => { + if (!(key in excludeOptions)) { + out[key] = input[key]; + } + return out; + }, {}); +} +function parseLogOptions(opt = {}, customArgs = []) { + const splitter = filterType(opt.splitter, filterString, SPLITTER); + const format = !filterPrimitives(opt.format) && opt.format ? opt.format : { + hash: "%H", + date: opt.strictDate === false ? "%ai" : "%aI", + message: "%s", + refs: "%D", + body: opt.multiLine ? "%B" : "%b", + author_name: opt.mailMap !== false ? "%aN" : "%an", + author_email: opt.mailMap !== false ? "%aE" : "%ae" + }; + const [fields, formatStr] = prettyFormat(format, splitter); + const suffix = []; + const command = [ + `--pretty=format:${START_BOUNDARY}${formatStr}${COMMIT_BOUNDARY}`, + ...customArgs + ]; + const maxCount = opt.n || opt["max-count"] || opt.maxCount; + if (maxCount) { + command.push(`--max-count=${maxCount}`); + } + if (opt.from || opt.to) { + const rangeOperator = opt.symmetric !== false ? "..." : ".."; + suffix.push(`${opt.from || ""}${rangeOperator}${opt.to || ""}`); + } + if (filterString(opt.file)) { + suffix.push("--follow", opt.file); + } + appendTaskOptions(userOptions(opt), command); + return { + fields, + splitter, + commands: [...command, ...suffix] + }; +} +function logTask(splitter, fields, customArgs) { + const parser3 = createListLogSummaryParser(splitter, fields, logFormatFromCommand(customArgs)); + return { + commands: ["log", ...customArgs], + format: "utf-8", + parser: parser3 + }; +} +function log_default() { + return { + log(...rest) { + const next = trailingFunctionArgument(arguments); + const options = parseLogOptions(trailingOptionsArgument(arguments), filterType(arguments[0], filterArray)); + const task = rejectDeprecatedSignatures(...rest) || validateLogFormatConfig(options.commands) || createLogTask(options); + return this._runTask(task, next); + } + }; + function createLogTask(options) { + return logTask(options.splitter, options.fields, options.commands); + } + function rejectDeprecatedSignatures(from, to) { + return filterString(from) && filterString(to) && configurationErrorTask(`git.log(string, string) should be replaced with git.log({ from: string, to: string })`); + } +} +var excludeOptions; +var init_log = __esm({ + "src/lib/tasks/log.ts"() { + init_log_format(); + init_parse_list_log_summary(); + init_utils(); + init_task(); + init_diff(); + excludeOptions = /* @__PURE__ */ ((excludeOptions2) => { + excludeOptions2[excludeOptions2["--pretty"] = 0] = "--pretty"; + excludeOptions2[excludeOptions2["max-count"] = 1] = "max-count"; + excludeOptions2[excludeOptions2["maxCount"] = 2] = "maxCount"; + excludeOptions2[excludeOptions2["n"] = 3] = "n"; + excludeOptions2[excludeOptions2["file"] = 4] = "file"; + excludeOptions2[excludeOptions2["format"] = 5] = "format"; + excludeOptions2[excludeOptions2["from"] = 6] = "from"; + excludeOptions2[excludeOptions2["to"] = 7] = "to"; + excludeOptions2[excludeOptions2["splitter"] = 8] = "splitter"; + excludeOptions2[excludeOptions2["symmetric"] = 9] = "symmetric"; + excludeOptions2[excludeOptions2["mailMap"] = 10] = "mailMap"; + excludeOptions2[excludeOptions2["multiLine"] = 11] = "multiLine"; + excludeOptions2[excludeOptions2["strictDate"] = 12] = "strictDate"; + return excludeOptions2; + })(excludeOptions || {}); + } +}); + +// src/lib/responses/MergeSummary.ts +var MergeSummaryConflict, MergeSummaryDetail; +var init_MergeSummary = __esm({ + "src/lib/responses/MergeSummary.ts"() { + MergeSummaryConflict = class { + constructor(reason, file = null, meta) { + this.reason = reason; + this.file = file; + this.meta = meta; + } + toString() { + return `${this.file}:${this.reason}`; + } + }; + MergeSummaryDetail = class { + constructor() { + this.conflicts = []; + this.merges = []; + this.result = "success"; + } + get failed() { + return this.conflicts.length > 0; + } + get reason() { + return this.result; + } + toString() { + if (this.conflicts.length) { + return `CONFLICTS: ${this.conflicts.join(", ")}`; + } + return "OK"; + } + }; + } +}); + +// src/lib/responses/PullSummary.ts +var PullSummary, PullFailedSummary; +var init_PullSummary = __esm({ + "src/lib/responses/PullSummary.ts"() { + PullSummary = class { + constructor() { + this.remoteMessages = { + all: [] + }; + this.created = []; + this.deleted = []; + this.files = []; + this.deletions = {}; + this.insertions = {}; + this.summary = { + changes: 0, + deletions: 0, + insertions: 0 + }; + } + }; + PullFailedSummary = class { + constructor() { + this.remote = ""; + this.hash = { + local: "", + remote: "" + }; + this.branch = { + local: "", + remote: "" + }; + this.message = ""; + } + toString() { + return this.message; + } + }; + } +}); + +// src/lib/parsers/parse-remote-objects.ts +function objectEnumerationResult(remoteMessages) { + return remoteMessages.objects = remoteMessages.objects || { + compressing: 0, + counting: 0, + enumerating: 0, + packReused: 0, + reused: { count: 0, delta: 0 }, + total: { count: 0, delta: 0 } + }; +} +function asObjectCount(source) { + const count = /^\s*(\d+)/.exec(source); + const delta = /delta (\d+)/i.exec(source); + return { + count: asNumber(count && count[1] || "0"), + delta: asNumber(delta && delta[1] || "0") + }; +} +var remoteMessagesObjectParsers; +var init_parse_remote_objects = __esm({ + "src/lib/parsers/parse-remote-objects.ts"() { + init_utils(); + remoteMessagesObjectParsers = [ + new RemoteLineParser(/^remote:\s*(enumerating|counting|compressing) objects: (\d+),/i, (result, [action, count]) => { + const key = action.toLowerCase(); + const enumeration = objectEnumerationResult(result.remoteMessages); + Object.assign(enumeration, { [key]: asNumber(count) }); + }), + new RemoteLineParser(/^remote:\s*(enumerating|counting|compressing) objects: \d+% \(\d+\/(\d+)\),/i, (result, [action, count]) => { + const key = action.toLowerCase(); + const enumeration = objectEnumerationResult(result.remoteMessages); + Object.assign(enumeration, { [key]: asNumber(count) }); + }), + new RemoteLineParser(/total ([^,]+), reused ([^,]+), pack-reused (\d+)/i, (result, [total, reused, packReused]) => { + const objects = objectEnumerationResult(result.remoteMessages); + objects.total = asObjectCount(total); + objects.reused = asObjectCount(reused); + objects.packReused = asNumber(packReused); + }) + ]; + } +}); + +// src/lib/parsers/parse-remote-messages.ts +function parseRemoteMessages(_stdOut, stdErr) { + return parseStringResponse({ remoteMessages: new RemoteMessageSummary() }, parsers2, stdErr); +} +var parsers2, RemoteMessageSummary; +var init_parse_remote_messages = __esm({ + "src/lib/parsers/parse-remote-messages.ts"() { + init_utils(); + init_parse_remote_objects(); + parsers2 = [ + new RemoteLineParser(/^remote:\s*(.+)$/, (result, [text]) => { + result.remoteMessages.all.push(text.trim()); + return false; + }), + ...remoteMessagesObjectParsers, + new RemoteLineParser([/create a (?:pull|merge) request/i, /\s(https?:\/\/\S+)$/], (result, [pullRequestUrl]) => { + result.remoteMessages.pullRequestUrl = pullRequestUrl; + }), + new RemoteLineParser([/found (\d+) vulnerabilities.+\(([^)]+)\)/i, /\s(https?:\/\/\S+)$/], (result, [count, summary, url]) => { + result.remoteMessages.vulnerabilities = { + count: asNumber(count), + summary, + url + }; + }) + ]; + RemoteMessageSummary = class { + constructor() { + this.all = []; + } + }; + } +}); + +// src/lib/parsers/parse-pull.ts +function parsePullErrorResult(stdOut, stdErr) { + const pullError = parseStringResponse(new PullFailedSummary(), errorParsers, [stdOut, stdErr]); + return pullError.message && pullError; +} +var FILE_UPDATE_REGEX, SUMMARY_REGEX, ACTION_REGEX, parsers3, errorParsers, parsePullDetail, parsePullResult; +var init_parse_pull = __esm({ + "src/lib/parsers/parse-pull.ts"() { + init_PullSummary(); + init_utils(); + init_parse_remote_messages(); + FILE_UPDATE_REGEX = /^\s*(.+?)\s+\|\s+\d+\s*(\+*)(-*)/; + SUMMARY_REGEX = /(\d+)\D+((\d+)\D+\(\+\))?(\D+(\d+)\D+\(-\))?/; + ACTION_REGEX = /^(create|delete) mode \d+ (.+)/; + parsers3 = [ + new LineParser(FILE_UPDATE_REGEX, (result, [file, insertions, deletions]) => { + result.files.push(file); + if (insertions) { + result.insertions[file] = insertions.length; + } + if (deletions) { + result.deletions[file] = deletions.length; + } + }), + new LineParser(SUMMARY_REGEX, (result, [changes, , insertions, , deletions]) => { + if (insertions !== void 0 || deletions !== void 0) { + result.summary.changes = +changes || 0; + result.summary.insertions = +insertions || 0; + result.summary.deletions = +deletions || 0; + return true; + } + return false; + }), + new LineParser(ACTION_REGEX, (result, [action, file]) => { + append$1(result.files, file); + append$1(action === "create" ? result.created : result.deleted, file); + }) + ]; + errorParsers = [ + new LineParser(/^from\s(.+)$/i, (result, [remote]) => void (result.remote = remote)), + new LineParser(/^fatal:\s(.+)$/, (result, [message]) => void (result.message = message)), + new LineParser(/([a-z0-9]+)\.\.([a-z0-9]+)\s+(\S+)\s+->\s+(\S+)$/, (result, [hashLocal, hashRemote, branchLocal, branchRemote]) => { + result.branch.local = branchLocal; + result.hash.local = hashLocal; + result.branch.remote = branchRemote; + result.hash.remote = hashRemote; + }) + ]; + parsePullDetail = (stdOut, stdErr) => { + return parseStringResponse(new PullSummary(), parsers3, [stdOut, stdErr]); + }; + parsePullResult = (stdOut, stdErr) => { + return Object.assign(new PullSummary(), parsePullDetail(stdOut, stdErr), parseRemoteMessages(stdOut, stdErr)); + }; + } +}); + +// src/lib/parsers/parse-merge.ts +var parsers4, parseMergeResult, parseMergeDetail; +var init_parse_merge = __esm({ + "src/lib/parsers/parse-merge.ts"() { + init_MergeSummary(); + init_utils(); + init_parse_pull(); + parsers4 = [ + new LineParser(/^Auto-merging\s+(.+)$/, (summary, [autoMerge]) => { + summary.merges.push(autoMerge); + }), + new LineParser(/^CONFLICT\s+\((.+)\): Merge conflict in (.+)$/, (summary, [reason, file]) => { + summary.conflicts.push(new MergeSummaryConflict(reason, file)); + }), + new LineParser(/^CONFLICT\s+\((.+\/delete)\): (.+) deleted in (.+) and/, (summary, [reason, file, deleteRef]) => { + summary.conflicts.push(new MergeSummaryConflict(reason, file, { deleteRef })); + }), + new LineParser(/^CONFLICT\s+\((.+)\):/, (summary, [reason]) => { + summary.conflicts.push(new MergeSummaryConflict(reason, null)); + }), + new LineParser(/^Automatic merge failed;\s+(.+)$/, (summary, [result]) => { + summary.result = result; + }) + ]; + parseMergeResult = (stdOut, stdErr) => { + return Object.assign(parseMergeDetail(stdOut, stdErr), parsePullResult(stdOut, stdErr)); + }; + parseMergeDetail = (stdOut) => { + return parseStringResponse(new MergeSummaryDetail(), parsers4, stdOut); + }; + } +}); + +// src/lib/tasks/merge.ts +function mergeTask(customArgs) { + if (!customArgs.length) { + return configurationErrorTask("Git.merge requires at least one option"); + } + return { + commands: ["merge", ...customArgs], + format: "utf-8", + parser(stdOut, stdErr) { + const merge = parseMergeResult(stdOut, stdErr); + if (merge.failed) { + throw new GitResponseError(merge); + } + return merge; + } + }; +} +var init_merge = __esm({ + "src/lib/tasks/merge.ts"() { + init_git_response_error(); + init_parse_merge(); + init_task(); + } +}); + +// src/lib/parsers/parse-push.ts +function pushResultPushedItem(local, remote, status) { + const deleted = status.includes("deleted"); + const tag = status.includes("tag") || /^refs\/tags/.test(local); + const alreadyUpdated = !status.includes("new"); + return { + deleted, + tag, + branch: !tag, + new: !alreadyUpdated, + alreadyUpdated, + local, + remote + }; +} +var parsers5, parsePushResult, parsePushDetail; +var init_parse_push = __esm({ + "src/lib/parsers/parse-push.ts"() { + init_utils(); + init_parse_remote_messages(); + parsers5 = [ + new LineParser(/^Pushing to (.+)$/, (result, [repo]) => { + result.repo = repo; + }), + new LineParser(/^updating local tracking ref '(.+)'/, (result, [local]) => { + result.ref = __spreadProps(__spreadValues({}, result.ref || {}), { + local + }); + }), + new LineParser(/^[=*-]\s+([^:]+):(\S+)\s+\[(.+)]$/, (result, [local, remote, type]) => { + result.pushed.push(pushResultPushedItem(local, remote, type)); + }), + new LineParser(/^Branch '([^']+)' set up to track remote branch '([^']+)' from '([^']+)'/, (result, [local, remote, remoteName]) => { + result.branch = __spreadProps(__spreadValues({}, result.branch || {}), { + local, + remote, + remoteName + }); + }), + new LineParser(/^([^:]+):(\S+)\s+([a-z0-9]+)\.\.([a-z0-9]+)$/, (result, [local, remote, from, to]) => { + result.update = { + head: { + local, + remote + }, + hash: { + from, + to + } + }; + }) + ]; + parsePushResult = (stdOut, stdErr) => { + const pushDetail = parsePushDetail(stdOut, stdErr); + const responseDetail = parseRemoteMessages(stdOut, stdErr); + return __spreadValues(__spreadValues({}, pushDetail), responseDetail); + }; + parsePushDetail = (stdOut, stdErr) => { + return parseStringResponse({ pushed: [] }, parsers5, [stdOut, stdErr]); + }; + } +}); + +// src/lib/tasks/push.ts +var push_exports = {}; +__export(push_exports, { + pushTagsTask: () => pushTagsTask, + pushTask: () => pushTask +}); +function pushTagsTask(ref = {}, customArgs) { + append$1(customArgs, "--tags"); + return pushTask(ref, customArgs); +} +function pushTask(ref = {}, customArgs) { + const commands = ["push", ...customArgs]; + if (ref.branch) { + commands.splice(1, 0, ref.branch); + } + if (ref.remote) { + commands.splice(1, 0, ref.remote); + } + remove$1(commands, "-v"); + append$1(commands, "--verbose"); + append$1(commands, "--porcelain"); + return { + commands, + format: "utf-8", + parser: parsePushResult + }; +} +var init_push = __esm({ + "src/lib/tasks/push.ts"() { + init_parse_push(); + init_utils(); + } +}); + +// src/lib/tasks/show.ts +function show_default() { + return { + showBuffer() { + const commands = ["show", ...getTrailingOptions(arguments, 1)]; + if (!commands.includes("--binary")) { + commands.splice(1, 0, "--binary"); + } + return this._runTask(straightThroughBufferTask(commands), trailingFunctionArgument(arguments)); + }, + show() { + const commands = ["show", ...getTrailingOptions(arguments, 1)]; + return this._runTask(straightThroughStringTask(commands), trailingFunctionArgument(arguments)); + } + }; +} +var init_show = __esm({ + "src/lib/tasks/show.ts"() { + init_utils(); + init_task(); + } +}); + +// src/lib/responses/FileStatusSummary.ts +var fromPathRegex, FileStatusSummary; +var init_FileStatusSummary = __esm({ + "src/lib/responses/FileStatusSummary.ts"() { + fromPathRegex = /^(.+) -> (.+)$/; + FileStatusSummary = class { + constructor(path, index, working_dir) { + this.path = path; + this.index = index; + this.working_dir = working_dir; + if (index + working_dir === "R") { + const detail = fromPathRegex.exec(path) || [null, path, path]; + this.from = detail[1] || ""; + this.path = detail[2] || ""; + } + } + }; + } +}); + +// src/lib/responses/StatusSummary.ts +function renamedFile(line) { + const [to, from] = line.split(NULL$1); + return { + from: from || to, + to + }; +} +function parser2(indexX, indexY, handler) { + return [`${indexX}${indexY}`, handler]; +} +function conflicts(indexX, ...indexY) { + return indexY.map((y) => parser2(indexX, y, (result, file) => append$1(result.conflicted, file))); +} +function splitLine(result, lineStr) { + const trimmed2 = lineStr.trim(); + switch (" ") { + case trimmed2.charAt(2): + return data(trimmed2.charAt(0), trimmed2.charAt(1), trimmed2.substr(3)); + case trimmed2.charAt(1): + return data(" " /* NONE */, trimmed2.charAt(0), trimmed2.substr(2)); + default: + return; + } + function data(index, workingDir, path) { + const raw = `${index}${workingDir}`; + const handler = parsers6.get(raw); + if (handler) { + handler(result, path); + } + if (raw !== "##" && raw !== "!!") { + result.files.push(new FileStatusSummary(path.replace(/\0.+$/, ""), index, workingDir)); + } + } +} +var StatusSummary, parsers6, parseStatusSummary; +var init_StatusSummary = __esm({ + "src/lib/responses/StatusSummary.ts"() { + init_utils(); + init_FileStatusSummary(); + StatusSummary = class { + constructor() { + this.not_added = []; + this.conflicted = []; + this.created = []; + this.deleted = []; + this.ignored = void 0; + this.modified = []; + this.renamed = []; + this.files = []; + this.staged = []; + this.ahead = 0; + this.behind = 0; + this.current = null; + this.tracking = null; + this.detached = false; + this.isClean = () => { + return !this.files.length; + }; + } + }; + parsers6 = new Map([ + parser2(" " /* NONE */, "A" /* ADDED */, (result, file) => append$1(result.created, file)), + parser2(" " /* NONE */, "D" /* DELETED */, (result, file) => append$1(result.deleted, file)), + parser2(" " /* NONE */, "M" /* MODIFIED */, (result, file) => append$1(result.modified, file)), + parser2("A" /* ADDED */, " " /* NONE */, (result, file) => append$1(result.created, file) && append$1(result.staged, file)), + parser2("A" /* ADDED */, "M" /* MODIFIED */, (result, file) => append$1(result.created, file) && append$1(result.staged, file) && append$1(result.modified, file)), + parser2("D" /* DELETED */, " " /* NONE */, (result, file) => append$1(result.deleted, file) && append$1(result.staged, file)), + parser2("M" /* MODIFIED */, " " /* NONE */, (result, file) => append$1(result.modified, file) && append$1(result.staged, file)), + parser2("M" /* MODIFIED */, "M" /* MODIFIED */, (result, file) => append$1(result.modified, file) && append$1(result.staged, file)), + parser2("R" /* RENAMED */, " " /* NONE */, (result, file) => { + append$1(result.renamed, renamedFile(file)); + }), + parser2("R" /* RENAMED */, "M" /* MODIFIED */, (result, file) => { + const renamed = renamedFile(file); + append$1(result.renamed, renamed); + append$1(result.modified, renamed.to); + }), + parser2("!" /* IGNORED */, "!" /* IGNORED */, (_result, _file) => { + append$1(_result.ignored = _result.ignored || [], _file); + }), + parser2("?" /* UNTRACKED */, "?" /* UNTRACKED */, (result, file) => append$1(result.not_added, file)), + ...conflicts("A" /* ADDED */, "A" /* ADDED */, "U" /* UNMERGED */), + ...conflicts("D" /* DELETED */, "D" /* DELETED */, "U" /* UNMERGED */), + ...conflicts("U" /* UNMERGED */, "A" /* ADDED */, "D" /* DELETED */, "U" /* UNMERGED */), + [ + "##", + (result, line) => { + const aheadReg = /ahead (\d+)/; + const behindReg = /behind (\d+)/; + const currentReg = /^(.+?(?=(?:\.{3}|\s|$)))/; + const trackingReg = /\.{3}(\S*)/; + const onEmptyBranchReg = /\son\s([\S]+)$/; + let regexResult; + regexResult = aheadReg.exec(line); + result.ahead = regexResult && +regexResult[1] || 0; + regexResult = behindReg.exec(line); + result.behind = regexResult && +regexResult[1] || 0; + regexResult = currentReg.exec(line); + result.current = regexResult && regexResult[1]; + regexResult = trackingReg.exec(line); + result.tracking = regexResult && regexResult[1]; + regexResult = onEmptyBranchReg.exec(line); + result.current = regexResult && regexResult[1] || result.current; + result.detached = /\(no branch\)/.test(line); + } + ] + ]); + parseStatusSummary = function(text) { + const lines = text.split(NULL$1); + const status = new StatusSummary(); + for (let i = 0, l = lines.length; i < l; ) { + let line = lines[i++].trim(); + if (!line) { + continue; + } + if (line.charAt(0) === "R" /* RENAMED */) { + line += NULL$1 + (lines[i++] || ""); + } + splitLine(status, line); + } + return status; + }; + } +}); + +// src/lib/tasks/status.ts +function statusTask(customArgs) { + const commands = [ + "status", + "--porcelain", + "-b", + "-u", + "--null", + ...customArgs.filter((arg) => !ignoredOptions.includes(arg)) + ]; + return { + format: "utf-8", + commands, + parser(text) { + return parseStatusSummary(text); + } + }; +} +var ignoredOptions; +var init_status = __esm({ + "src/lib/tasks/status.ts"() { + init_StatusSummary(); + ignoredOptions = ["--null", "-z"]; + } +}); + +// src/lib/tasks/version.ts +function versionResponse(major = 0, minor = 0, patch = 0, agent = "", installed = true) { + return Object.defineProperty({ + major, + minor, + patch, + agent, + installed + }, "toString", { + value() { + return `${this.major}.${this.minor}.${this.patch}`; + }, + configurable: false, + enumerable: false + }); +} +function notInstalledResponse() { + return versionResponse(0, 0, 0, "", false); +} +function version_default() { + return { + version() { + return this._runTask({ + commands: ["--version"], + format: "utf-8", + parser: versionParser, + onError(result, error, done, fail) { + if (result.exitCode === -2 /* NOT_FOUND */) { + return done(Buffer.from(NOT_INSTALLED)); + } + fail(error); + } + }); + } + }; +} +function versionParser(stdOut) { + if (stdOut === NOT_INSTALLED) { + return notInstalledResponse(); + } + return parseStringResponse(versionResponse(0, 0, 0, stdOut), parsers7, stdOut); +} +var NOT_INSTALLED, parsers7; +var init_version = __esm({ + "src/lib/tasks/version.ts"() { + init_utils(); + NOT_INSTALLED = "installed=false"; + parsers7 = [ + new LineParser(/version (\d+)\.(\d+)\.(\d+)(?:\s*\((.+)\))?/, (result, [major, minor, patch, agent = ""]) => { + Object.assign(result, versionResponse(asNumber(major), asNumber(minor), asNumber(patch), agent)); + }), + new LineParser(/version (\d+)\.(\d+)\.(\D+)(.+)?$/, (result, [major, minor, patch, agent = ""]) => { + Object.assign(result, versionResponse(asNumber(major), asNumber(minor), patch, agent)); + }) + ]; + } +}); + +// src/lib/simple-git-api.ts +var simple_git_api_exports = {}; +__export(simple_git_api_exports, { + SimpleGitApi: () => SimpleGitApi +}); +var SimpleGitApi; +var init_simple_git_api = __esm({ + "src/lib/simple-git-api.ts"() { + init_task_callback(); + init_change_working_directory(); + init_checkout(); + init_commit(); + init_config(); + init_grep(); + init_hash_object(); + init_init(); + init_log(); + init_merge(); + init_push(); + init_show(); + init_status(); + init_task(); + init_version(); + init_utils(); + SimpleGitApi = class { + constructor(_executor) { + this._executor = _executor; + } + _runTask(task, then) { + const chain = this._executor.chain(); + const promise = chain.push(task); + if (then) { + taskCallback(task, promise, then); + } + return Object.create(this, { + then: { value: promise.then.bind(promise) }, + catch: { value: promise.catch.bind(promise) }, + _executor: { value: chain } + }); + } + add(files) { + return this._runTask(straightThroughStringTask(["add", ...asArray(files)]), trailingFunctionArgument(arguments)); + } + cwd(directory) { + const next = trailingFunctionArgument(arguments); + if (typeof directory === "string") { + return this._runTask(changeWorkingDirectoryTask(directory, this._executor), next); + } + if (typeof (directory == null ? void 0 : directory.path) === "string") { + return this._runTask(changeWorkingDirectoryTask(directory.path, directory.root && this._executor || void 0), next); + } + return this._runTask(configurationErrorTask("Git.cwd: workingDirectory must be supplied as a string"), next); + } + hashObject(path, write) { + return this._runTask(hashObjectTask(path, write === true), trailingFunctionArgument(arguments)); + } + init(bare) { + return this._runTask(initTask(bare === true, this._executor.cwd, getTrailingOptions(arguments)), trailingFunctionArgument(arguments)); + } + merge() { + return this._runTask(mergeTask(getTrailingOptions(arguments)), trailingFunctionArgument(arguments)); + } + mergeFromTo(remote, branch) { + if (!(filterString(remote) && filterString(branch))) { + return this._runTask(configurationErrorTask(`Git.mergeFromTo requires that the 'remote' and 'branch' arguments are supplied as strings`)); + } + return this._runTask(mergeTask([remote, branch, ...getTrailingOptions(arguments)]), trailingFunctionArgument(arguments, false)); + } + outputHandler(handler) { + this._executor.outputHandler = handler; + return this; + } + push() { + const task = pushTask({ + remote: filterType(arguments[0], filterString), + branch: filterType(arguments[1], filterString) + }, getTrailingOptions(arguments)); + return this._runTask(task, trailingFunctionArgument(arguments)); + } + stash() { + return this._runTask(straightThroughStringTask(["stash", ...getTrailingOptions(arguments)]), trailingFunctionArgument(arguments)); + } + status() { + return this._runTask(statusTask(getTrailingOptions(arguments)), trailingFunctionArgument(arguments)); + } + }; + Object.assign(SimpleGitApi.prototype, checkout_default(), commit_default(), config_default(), grep_default(), log_default(), show_default(), version_default()); + } +}); + +// src/lib/runners/scheduler.ts +var scheduler_exports = {}; +__export(scheduler_exports, { + Scheduler: () => Scheduler +}); +var createScheduledTask, Scheduler; +var init_scheduler = __esm({ + "src/lib/runners/scheduler.ts"() { + init_utils(); + init_git_logger(); + createScheduledTask = (() => { + let id = 0; + return () => { + id++; + const { promise, done } = createDeferred(); + return { + promise, + done, + id + }; + }; + })(); + Scheduler = class { + constructor(concurrency = 2) { + this.concurrency = concurrency; + this.logger = createLogger("", "scheduler"); + this.pending = []; + this.running = []; + this.logger(`Constructed, concurrency=%s`, concurrency); + } + schedule() { + if (!this.pending.length || this.running.length >= this.concurrency) { + this.logger(`Schedule attempt ignored, pending=%s running=%s concurrency=%s`, this.pending.length, this.running.length, this.concurrency); + return; + } + const task = append$1(this.running, this.pending.shift()); + this.logger(`Attempting id=%s`, task.id); + task.done(() => { + this.logger(`Completing id=`, task.id); + remove$1(this.running, task); + this.schedule(); + }); + } + next() { + const { promise, id } = append$1(this.pending, createScheduledTask()); + this.logger(`Scheduling id=%s`, id); + this.schedule(); + return promise; + } + }; + } +}); + +// src/lib/tasks/apply-patch.ts +var apply_patch_exports = {}; +__export(apply_patch_exports, { + applyPatchTask: () => applyPatchTask +}); +function applyPatchTask(patches, customArgs) { + return straightThroughStringTask(["apply", ...customArgs, ...patches]); +} +var init_apply_patch = __esm({ + "src/lib/tasks/apply-patch.ts"() { + init_task(); + } +}); + +// src/lib/responses/BranchDeleteSummary.ts +function branchDeletionSuccess(branch, hash) { + return { + branch, + hash, + success: true + }; +} +function branchDeletionFailure(branch) { + return { + branch, + hash: null, + success: false + }; +} +var BranchDeletionBatch; +var init_BranchDeleteSummary = __esm({ + "src/lib/responses/BranchDeleteSummary.ts"() { + BranchDeletionBatch = class { + constructor() { + this.all = []; + this.branches = {}; + this.errors = []; + } + get success() { + return !this.errors.length; + } + }; + } +}); + +// src/lib/parsers/parse-branch-delete.ts +function hasBranchDeletionError(data, processExitCode) { + return processExitCode === 1 /* ERROR */ && deleteErrorRegex.test(data); +} +var deleteSuccessRegex, deleteErrorRegex, parsers8, parseBranchDeletions; +var init_parse_branch_delete = __esm({ + "src/lib/parsers/parse-branch-delete.ts"() { + init_BranchDeleteSummary(); + init_utils(); + deleteSuccessRegex = /(\S+)\s+\(\S+\s([^)]+)\)/; + deleteErrorRegex = /^error[^']+'([^']+)'/m; + parsers8 = [ + new LineParser(deleteSuccessRegex, (result, [branch, hash]) => { + const deletion = branchDeletionSuccess(branch, hash); + result.all.push(deletion); + result.branches[branch] = deletion; + }), + new LineParser(deleteErrorRegex, (result, [branch]) => { + const deletion = branchDeletionFailure(branch); + result.errors.push(deletion); + result.all.push(deletion); + result.branches[branch] = deletion; + }) + ]; + parseBranchDeletions = (stdOut, stdErr) => { + return parseStringResponse(new BranchDeletionBatch(), parsers8, [stdOut, stdErr]); + }; + } +}); + +// src/lib/responses/BranchSummary.ts +var BranchSummaryResult; +var init_BranchSummary = __esm({ + "src/lib/responses/BranchSummary.ts"() { + BranchSummaryResult = class { + constructor() { + this.all = []; + this.branches = {}; + this.current = ""; + this.detached = false; + } + push(status, detached, name, commit, label) { + if (status === "*" /* CURRENT */) { + this.detached = detached; + this.current = name; + } + this.all.push(name); + this.branches[name] = { + current: status === "*" /* CURRENT */, + linkedWorkTree: status === "+" /* LINKED */, + name, + commit, + label + }; + } + }; + } +}); + +// src/lib/parsers/parse-branch.ts +function branchStatus(input) { + return input ? input.charAt(0) : ""; +} +function parseBranchSummary(stdOut) { + return parseStringResponse(new BranchSummaryResult(), parsers9, stdOut); +} +var parsers9; +var init_parse_branch = __esm({ + "src/lib/parsers/parse-branch.ts"() { + init_BranchSummary(); + init_utils(); + parsers9 = [ + new LineParser(/^([*+]\s)?\((?:HEAD )?detached (?:from|at) (\S+)\)\s+([a-z0-9]+)\s(.*)$/, (result, [current, name, commit, label]) => { + result.push(branchStatus(current), true, name, commit, label); + }), + new LineParser(/^([*+]\s)?(\S+)\s+([a-z0-9]+)\s?(.*)$/s, (result, [current, name, commit, label]) => { + result.push(branchStatus(current), false, name, commit, label); + }) + ]; + } +}); + +// src/lib/tasks/branch.ts +var branch_exports = {}; +__export(branch_exports, { + branchLocalTask: () => branchLocalTask, + branchTask: () => branchTask, + containsDeleteBranchCommand: () => containsDeleteBranchCommand, + deleteBranchTask: () => deleteBranchTask, + deleteBranchesTask: () => deleteBranchesTask +}); +function containsDeleteBranchCommand(commands) { + const deleteCommands = ["-d", "-D", "--delete"]; + return commands.some((command) => deleteCommands.includes(command)); +} +function branchTask(customArgs) { + const isDelete = containsDeleteBranchCommand(customArgs); + const commands = ["branch", ...customArgs]; + if (commands.length === 1) { + commands.push("-a"); + } + if (!commands.includes("-v")) { + commands.splice(1, 0, "-v"); + } + return { + format: "utf-8", + commands, + parser(stdOut, stdErr) { + if (isDelete) { + return parseBranchDeletions(stdOut, stdErr).all[0]; + } + return parseBranchSummary(stdOut); + } + }; +} +function branchLocalTask() { + const parser3 = parseBranchSummary; + return { + format: "utf-8", + commands: ["branch", "-v"], + parser: parser3 + }; +} +function deleteBranchesTask(branches, forceDelete = false) { + return { + format: "utf-8", + commands: ["branch", "-v", forceDelete ? "-D" : "-d", ...branches], + parser(stdOut, stdErr) { + return parseBranchDeletions(stdOut, stdErr); + }, + onError({ exitCode, stdOut }, error, done, fail) { + if (!hasBranchDeletionError(String(error), exitCode)) { + return fail(error); + } + done(stdOut); + } + }; +} +function deleteBranchTask(branch, forceDelete = false) { + const task = { + format: "utf-8", + commands: ["branch", "-v", forceDelete ? "-D" : "-d", branch], + parser(stdOut, stdErr) { + return parseBranchDeletions(stdOut, stdErr).branches[branch]; + }, + onError({ exitCode, stdErr, stdOut }, error, _, fail) { + if (!hasBranchDeletionError(String(error), exitCode)) { + return fail(error); + } + throw new GitResponseError(task.parser(bufferToString(stdOut), bufferToString(stdErr)), String(error)); + } + }; + return task; +} +var init_branch = __esm({ + "src/lib/tasks/branch.ts"() { + init_git_response_error(); + init_parse_branch_delete(); + init_parse_branch(); + init_utils(); + } +}); + +// src/lib/responses/CheckIgnore.ts +var parseCheckIgnore; +var init_CheckIgnore = __esm({ + "src/lib/responses/CheckIgnore.ts"() { + parseCheckIgnore = (text) => { + return text.split(/\n/g).map((line) => line.trim()).filter((file) => !!file); + }; + } +}); + +// src/lib/tasks/check-ignore.ts +var check_ignore_exports = {}; +__export(check_ignore_exports, { + checkIgnoreTask: () => checkIgnoreTask +}); +function checkIgnoreTask(paths) { + return { + commands: ["check-ignore", ...paths], + format: "utf-8", + parser: parseCheckIgnore + }; +} +var init_check_ignore = __esm({ + "src/lib/tasks/check-ignore.ts"() { + init_CheckIgnore(); + } +}); + +// src/lib/tasks/clone.ts +var clone_exports = {}; +__export(clone_exports, { + cloneMirrorTask: () => cloneMirrorTask, + cloneTask: () => cloneTask +}); +function disallowedCommand(command) { + return /^--upload-pack(=|$)/.test(command); +} +function cloneTask(repo, directory, customArgs) { + const commands = ["clone", ...customArgs]; + filterString(repo) && commands.push(repo); + filterString(directory) && commands.push(directory); + const banned = commands.find(disallowedCommand); + if (banned) { + return configurationErrorTask(`git.fetch: potential exploit argument blocked.`); + } + return straightThroughStringTask(commands); +} +function cloneMirrorTask(repo, directory, customArgs) { + append$1(customArgs, "--mirror"); + return cloneTask(repo, directory, customArgs); +} +var init_clone = __esm({ + "src/lib/tasks/clone.ts"() { + init_task(); + init_utils(); + } +}); + +// src/lib/parsers/parse-fetch.ts +function parseFetchResult(stdOut, stdErr) { + const result = { + raw: stdOut, + remote: null, + branches: [], + tags: [], + updated: [], + deleted: [] + }; + return parseStringResponse(result, parsers10, [stdOut, stdErr]); +} +var parsers10; +var init_parse_fetch = __esm({ + "src/lib/parsers/parse-fetch.ts"() { + init_utils(); + parsers10 = [ + new LineParser(/From (.+)$/, (result, [remote]) => { + result.remote = remote; + }), + new LineParser(/\* \[new branch]\s+(\S+)\s*-> (.+)$/, (result, [name, tracking]) => { + result.branches.push({ + name, + tracking + }); + }), + new LineParser(/\* \[new tag]\s+(\S+)\s*-> (.+)$/, (result, [name, tracking]) => { + result.tags.push({ + name, + tracking + }); + }), + new LineParser(/- \[deleted]\s+\S+\s*-> (.+)$/, (result, [tracking]) => { + result.deleted.push({ + tracking + }); + }), + new LineParser(/\s*([^.]+)\.\.(\S+)\s+(\S+)\s*-> (.+)$/, (result, [from, to, name, tracking]) => { + result.updated.push({ + name, + tracking, + to, + from + }); + }) + ]; + } +}); + +// src/lib/tasks/fetch.ts +var fetch_exports = {}; +__export(fetch_exports, { + fetchTask: () => fetchTask +}); +function disallowedCommand2(command) { + return /^--upload-pack(=|$)/.test(command); +} +function fetchTask(remote, branch, customArgs) { + const commands = ["fetch", ...customArgs]; + if (remote && branch) { + commands.push(remote, branch); + } + const banned = commands.find(disallowedCommand2); + if (banned) { + return configurationErrorTask(`git.fetch: potential exploit argument blocked.`); + } + return { + commands, + format: "utf-8", + parser: parseFetchResult + }; +} +var init_fetch = __esm({ + "src/lib/tasks/fetch.ts"() { + init_parse_fetch(); + init_task(); + } +}); + +// src/lib/parsers/parse-move.ts +function parseMoveResult(stdOut) { + return parseStringResponse({ moves: [] }, parsers11, stdOut); +} +var parsers11; +var init_parse_move = __esm({ + "src/lib/parsers/parse-move.ts"() { + init_utils(); + parsers11 = [ + new LineParser(/^Renaming (.+) to (.+)$/, (result, [from, to]) => { + result.moves.push({ from, to }); + }) + ]; + } +}); + +// src/lib/tasks/move.ts +var move_exports = {}; +__export(move_exports, { + moveTask: () => moveTask +}); +function moveTask(from, to) { + return { + commands: ["mv", "-v", ...asArray(from), to], + format: "utf-8", + parser: parseMoveResult + }; +} +var init_move = __esm({ + "src/lib/tasks/move.ts"() { + init_parse_move(); + init_utils(); + } +}); + +// src/lib/tasks/pull.ts +var pull_exports = {}; +__export(pull_exports, { + pullTask: () => pullTask +}); +function pullTask(remote, branch, customArgs) { + const commands = ["pull", ...customArgs]; + if (remote && branch) { + commands.splice(1, 0, remote, branch); + } + return { + commands, + format: "utf-8", + parser(stdOut, stdErr) { + return parsePullResult(stdOut, stdErr); + }, + onError(result, _error, _done, fail) { + const pullError = parsePullErrorResult(bufferToString(result.stdOut), bufferToString(result.stdErr)); + if (pullError) { + return fail(new GitResponseError(pullError)); + } + fail(_error); + } + }; +} +var init_pull = __esm({ + "src/lib/tasks/pull.ts"() { + init_git_response_error(); + init_parse_pull(); + init_utils(); + } +}); + +// src/lib/responses/GetRemoteSummary.ts +function parseGetRemotes(text) { + const remotes = {}; + forEach$6(text, ([name]) => remotes[name] = { name }); + return Object.values(remotes); +} +function parseGetRemotesVerbose(text) { + const remotes = {}; + forEach$6(text, ([name, url, purpose]) => { + if (!remotes.hasOwnProperty(name)) { + remotes[name] = { + name, + refs: { fetch: "", push: "" } + }; + } + if (purpose && url) { + remotes[name].refs[purpose.replace(/[^a-z]/g, "")] = url; + } + }); + return Object.values(remotes); +} +function forEach$6(text, handler) { + forEachLineWithContent(text, (line) => handler(line.split(/\s+/))); +} +var init_GetRemoteSummary = __esm({ + "src/lib/responses/GetRemoteSummary.ts"() { + init_utils(); + } +}); + +// src/lib/tasks/remote.ts +var remote_exports = {}; +__export(remote_exports, { + addRemoteTask: () => addRemoteTask, + getRemotesTask: () => getRemotesTask, + listRemotesTask: () => listRemotesTask, + remoteTask: () => remoteTask, + removeRemoteTask: () => removeRemoteTask +}); +function addRemoteTask(remoteName, remoteRepo, customArgs = []) { + return straightThroughStringTask(["remote", "add", ...customArgs, remoteName, remoteRepo]); +} +function getRemotesTask(verbose) { + const commands = ["remote"]; + if (verbose) { + commands.push("-v"); + } + return { + commands, + format: "utf-8", + parser: verbose ? parseGetRemotesVerbose : parseGetRemotes + }; +} +function listRemotesTask(customArgs = []) { + const commands = [...customArgs]; + if (commands[0] !== "ls-remote") { + commands.unshift("ls-remote"); + } + return straightThroughStringTask(commands); +} +function remoteTask(customArgs = []) { + const commands = [...customArgs]; + if (commands[0] !== "remote") { + commands.unshift("remote"); + } + return straightThroughStringTask(commands); +} +function removeRemoteTask(remoteName) { + return straightThroughStringTask(["remote", "remove", remoteName]); +} +var init_remote = __esm({ + "src/lib/tasks/remote.ts"() { + init_GetRemoteSummary(); + init_task(); + } +}); + +// src/lib/tasks/stash-list.ts +var stash_list_exports = {}; +__export(stash_list_exports, { + stashListTask: () => stashListTask +}); +function stashListTask(opt = {}, customArgs) { + const options = parseLogOptions(opt); + const commands = ["stash", "list", ...options.commands, ...customArgs]; + const parser3 = createListLogSummaryParser(options.splitter, options.fields, logFormatFromCommand(commands)); + return validateLogFormatConfig(commands) || { + commands, + format: "utf-8", + parser: parser3 + }; +} +var init_stash_list = __esm({ + "src/lib/tasks/stash-list.ts"() { + init_log_format(); + init_parse_list_log_summary(); + init_diff(); + init_log(); + } +}); + +// src/lib/tasks/sub-module.ts +var sub_module_exports = {}; +__export(sub_module_exports, { + addSubModuleTask: () => addSubModuleTask, + initSubModuleTask: () => initSubModuleTask, + subModuleTask: () => subModuleTask, + updateSubModuleTask: () => updateSubModuleTask +}); +function addSubModuleTask(repo, path) { + return subModuleTask(["add", repo, path]); +} +function initSubModuleTask(customArgs) { + return subModuleTask(["init", ...customArgs]); +} +function subModuleTask(customArgs) { + const commands = [...customArgs]; + if (commands[0] !== "submodule") { + commands.unshift("submodule"); + } + return straightThroughStringTask(commands); +} +function updateSubModuleTask(customArgs) { + return subModuleTask(["update", ...customArgs]); +} +var init_sub_module = __esm({ + "src/lib/tasks/sub-module.ts"() { + init_task(); + } +}); + +// src/lib/responses/TagList.ts +function singleSorted(a, b) { + const aIsNum = isNaN(a); + const bIsNum = isNaN(b); + if (aIsNum !== bIsNum) { + return aIsNum ? 1 : -1; + } + return aIsNum ? sorted(a, b) : 0; +} +function sorted(a, b) { + return a === b ? 0 : a > b ? 1 : -1; +} +function trimmed(input) { + return input.trim(); +} +function toNumber(input) { + if (typeof input === "string") { + return parseInt(input.replace(/^\D+/g, ""), 10) || 0; + } + return 0; +} +var TagList, parseTagList; +var init_TagList = __esm({ + "src/lib/responses/TagList.ts"() { + TagList = class { + constructor(all, latest) { + this.all = all; + this.latest = latest; + } + }; + parseTagList = function(data, customSort = false) { + const tags = data.split("\n").map(trimmed).filter(Boolean); + if (!customSort) { + tags.sort(function(tagA, tagB) { + const partsA = tagA.split("."); + const partsB = tagB.split("."); + if (partsA.length === 1 || partsB.length === 1) { + return singleSorted(toNumber(partsA[0]), toNumber(partsB[0])); + } + for (let i = 0, l = Math.max(partsA.length, partsB.length); i < l; i++) { + const diff = sorted(toNumber(partsA[i]), toNumber(partsB[i])); + if (diff) { + return diff; + } + } + return 0; + }); + } + const latest = customSort ? tags[0] : [...tags].reverse().find((tag) => tag.indexOf(".") >= 0); + return new TagList(tags, latest); + }; + } +}); + +// src/lib/tasks/tag.ts +var tag_exports = {}; +__export(tag_exports, { + addAnnotatedTagTask: () => addAnnotatedTagTask, + addTagTask: () => addTagTask, + tagListTask: () => tagListTask +}); +function tagListTask(customArgs = []) { + const hasCustomSort = customArgs.some((option) => /^--sort=/.test(option)); + return { + format: "utf-8", + commands: ["tag", "-l", ...customArgs], + parser(text) { + return parseTagList(text, hasCustomSort); + } + }; +} +function addTagTask(name) { + return { + format: "utf-8", + commands: ["tag", name], + parser() { + return { name }; + } + }; +} +function addAnnotatedTagTask(name, tagMessage) { + return { + format: "utf-8", + commands: ["tag", "-a", "-m", tagMessage, name], + parser() { + return { name }; + } + }; +} +var init_tag = __esm({ + "src/lib/tasks/tag.ts"() { + init_TagList(); + } +}); + +// src/git.js +var require_git = __commonJS({ + "src/git.js"(exports, module) { + var { GitExecutor: GitExecutor2 } = (init_git_executor(), __toCommonJS(git_executor_exports)); + var { SimpleGitApi: SimpleGitApi2 } = (init_simple_git_api(), __toCommonJS(simple_git_api_exports)); + var { Scheduler: Scheduler2 } = (init_scheduler(), __toCommonJS(scheduler_exports)); + var { configurationErrorTask: configurationErrorTask2 } = (init_task(), __toCommonJS(task_exports)); + var { + asArray: asArray2, + filterArray: filterArray2, + filterPrimitives: filterPrimitives2, + filterString: filterString2, + filterStringOrStringArray: filterStringOrStringArray2, + filterType: filterType2, + getTrailingOptions: getTrailingOptions2, + trailingFunctionArgument: trailingFunctionArgument2, + trailingOptionsArgument: trailingOptionsArgument2 + } = (init_utils(), __toCommonJS(utils_exports)); + var { applyPatchTask: applyPatchTask2 } = (init_apply_patch(), __toCommonJS(apply_patch_exports)); + var { + branchTask: branchTask2, + branchLocalTask: branchLocalTask2, + deleteBranchesTask: deleteBranchesTask2, + deleteBranchTask: deleteBranchTask2 + } = (init_branch(), __toCommonJS(branch_exports)); + var { checkIgnoreTask: checkIgnoreTask2 } = (init_check_ignore(), __toCommonJS(check_ignore_exports)); + var { checkIsRepoTask: checkIsRepoTask2 } = (init_check_is_repo(), __toCommonJS(check_is_repo_exports)); + var { cloneTask: cloneTask2, cloneMirrorTask: cloneMirrorTask2 } = (init_clone(), __toCommonJS(clone_exports)); + var { cleanWithOptionsTask: cleanWithOptionsTask2, isCleanOptionsArray: isCleanOptionsArray2 } = (init_clean(), __toCommonJS(clean_exports)); + var { diffSummaryTask: diffSummaryTask2 } = (init_diff(), __toCommonJS(diff_exports)); + var { fetchTask: fetchTask2 } = (init_fetch(), __toCommonJS(fetch_exports)); + var { moveTask: moveTask2 } = (init_move(), __toCommonJS(move_exports)); + var { pullTask: pullTask2 } = (init_pull(), __toCommonJS(pull_exports)); + var { pushTagsTask: pushTagsTask2 } = (init_push(), __toCommonJS(push_exports)); + var { + addRemoteTask: addRemoteTask2, + getRemotesTask: getRemotesTask2, + listRemotesTask: listRemotesTask2, + remoteTask: remoteTask2, + removeRemoteTask: removeRemoteTask2 + } = (init_remote(), __toCommonJS(remote_exports)); + var { getResetMode: getResetMode2, resetTask: resetTask2 } = (init_reset(), __toCommonJS(reset_exports)); + var { stashListTask: stashListTask2 } = (init_stash_list(), __toCommonJS(stash_list_exports)); + var { + addSubModuleTask: addSubModuleTask2, + initSubModuleTask: initSubModuleTask2, + subModuleTask: subModuleTask2, + updateSubModuleTask: updateSubModuleTask2 + } = (init_sub_module(), __toCommonJS(sub_module_exports)); + var { addAnnotatedTagTask: addAnnotatedTagTask2, addTagTask: addTagTask2, tagListTask: tagListTask2 } = (init_tag(), __toCommonJS(tag_exports)); + var { straightThroughBufferTask: straightThroughBufferTask2, straightThroughStringTask: straightThroughStringTask2 } = (init_task(), __toCommonJS(task_exports)); + function Git2(options, plugins) { + this._executor = new GitExecutor2(options.binary, options.baseDir, new Scheduler2(options.maxConcurrentProcesses), plugins); + this._trimmed = options.trimmed; + } + (Git2.prototype = Object.create(SimpleGitApi2.prototype)).constructor = Git2; + Git2.prototype.customBinary = function(command) { + this._executor.binary = command; + return this; + }; + Git2.prototype.env = function(name, value) { + if (arguments.length === 1 && typeof name === "object") { + this._executor.env = name; + } else { + (this._executor.env = this._executor.env || {})[name] = value; + } + return this; + }; + Git2.prototype.stashList = function(options) { + return this._runTask(stashListTask2(trailingOptionsArgument2(arguments) || {}, filterArray2(options) && options || []), trailingFunctionArgument2(arguments)); + }; + function createCloneTask(api, task, repoPath, localPath) { + if (typeof repoPath !== "string") { + return configurationErrorTask2(`git.${api}() requires a string 'repoPath'`); + } + return task(repoPath, filterType2(localPath, filterString2), getTrailingOptions2(arguments)); + } + Git2.prototype.clone = function() { + return this._runTask(createCloneTask("clone", cloneTask2, ...arguments), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.mirror = function() { + return this._runTask(createCloneTask("mirror", cloneMirrorTask2, ...arguments), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.mv = function(from, to) { + return this._runTask(moveTask2(from, to), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.checkoutLatestTag = function(then) { + var git = this; + return this.pull(function() { + git.tags(function(err, tags) { + git.checkout(tags.latest, then); + }); + }); + }; + Git2.prototype.pull = function(remote, branch, options, then) { + return this._runTask(pullTask2(filterType2(remote, filterString2), filterType2(branch, filterString2), getTrailingOptions2(arguments)), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.fetch = function(remote, branch) { + return this._runTask(fetchTask2(filterType2(remote, filterString2), filterType2(branch, filterString2), getTrailingOptions2(arguments)), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.silent = function(silence) { + console.warn("simple-git deprecation notice: git.silent: logging should be configured using the `debug` library / `DEBUG` environment variable, this will be an error in version 3"); + return this; + }; + Git2.prototype.tags = function(options, then) { + return this._runTask(tagListTask2(getTrailingOptions2(arguments)), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.rebase = function() { + return this._runTask(straightThroughStringTask2(["rebase", ...getTrailingOptions2(arguments)]), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.reset = function(mode) { + return this._runTask(resetTask2(getResetMode2(mode), getTrailingOptions2(arguments)), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.revert = function(commit) { + const next = trailingFunctionArgument2(arguments); + if (typeof commit !== "string") { + return this._runTask(configurationErrorTask2("Commit must be a string"), next); + } + return this._runTask(straightThroughStringTask2(["revert", ...getTrailingOptions2(arguments, 0, true), commit]), next); + }; + Git2.prototype.addTag = function(name) { + const task = typeof name === "string" ? addTagTask2(name) : configurationErrorTask2("Git.addTag requires a tag name"); + return this._runTask(task, trailingFunctionArgument2(arguments)); + }; + Git2.prototype.addAnnotatedTag = function(tagName, tagMessage) { + return this._runTask(addAnnotatedTagTask2(tagName, tagMessage), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.deleteLocalBranch = function(branchName, forceDelete, then) { + return this._runTask(deleteBranchTask2(branchName, typeof forceDelete === "boolean" ? forceDelete : false), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.deleteLocalBranches = function(branchNames, forceDelete, then) { + return this._runTask(deleteBranchesTask2(branchNames, typeof forceDelete === "boolean" ? forceDelete : false), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.branch = function(options, then) { + return this._runTask(branchTask2(getTrailingOptions2(arguments)), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.branchLocal = function(then) { + return this._runTask(branchLocalTask2(), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.raw = function(commands) { + const createRestCommands = !Array.isArray(commands); + const command = [].slice.call(createRestCommands ? arguments : commands, 0); + for (let i = 0; i < command.length && createRestCommands; i++) { + if (!filterPrimitives2(command[i])) { + command.splice(i, command.length - i); + break; + } + } + command.push(...getTrailingOptions2(arguments, 0, true)); + var next = trailingFunctionArgument2(arguments); + if (!command.length) { + return this._runTask(configurationErrorTask2("Raw: must supply one or more command to execute"), next); + } + return this._runTask(straightThroughStringTask2(command, this._trimmed), next); + }; + Git2.prototype.submoduleAdd = function(repo, path, then) { + return this._runTask(addSubModuleTask2(repo, path), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.submoduleUpdate = function(args, then) { + return this._runTask(updateSubModuleTask2(getTrailingOptions2(arguments, true)), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.submoduleInit = function(args, then) { + return this._runTask(initSubModuleTask2(getTrailingOptions2(arguments, true)), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.subModule = function(options, then) { + return this._runTask(subModuleTask2(getTrailingOptions2(arguments)), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.listRemote = function() { + return this._runTask(listRemotesTask2(getTrailingOptions2(arguments)), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.addRemote = function(remoteName, remoteRepo, then) { + return this._runTask(addRemoteTask2(remoteName, remoteRepo, getTrailingOptions2(arguments)), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.removeRemote = function(remoteName, then) { + return this._runTask(removeRemoteTask2(remoteName), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.getRemotes = function(verbose, then) { + return this._runTask(getRemotesTask2(verbose === true), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.remote = function(options, then) { + return this._runTask(remoteTask2(getTrailingOptions2(arguments)), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.tag = function(options, then) { + const command = getTrailingOptions2(arguments); + if (command[0] !== "tag") { + command.unshift("tag"); + } + return this._runTask(straightThroughStringTask2(command), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.updateServerInfo = function(then) { + return this._runTask(straightThroughStringTask2(["update-server-info"]), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.pushTags = function(remote, then) { + const task = pushTagsTask2({ remote: filterType2(remote, filterString2) }, getTrailingOptions2(arguments)); + return this._runTask(task, trailingFunctionArgument2(arguments)); + }; + Git2.prototype.rm = function(files) { + return this._runTask(straightThroughStringTask2(["rm", "-f", ...asArray2(files)]), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.rmKeepLocal = function(files) { + return this._runTask(straightThroughStringTask2(["rm", "--cached", ...asArray2(files)]), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.catFile = function(options, then) { + return this._catFile("utf-8", arguments); + }; + Git2.prototype.binaryCatFile = function() { + return this._catFile("buffer", arguments); + }; + Git2.prototype._catFile = function(format, args) { + var handler = trailingFunctionArgument2(args); + var command = ["cat-file"]; + var options = args[0]; + if (typeof options === "string") { + return this._runTask(configurationErrorTask2("Git.catFile: options must be supplied as an array of strings"), handler); + } + if (Array.isArray(options)) { + command.push.apply(command, options); + } + const task = format === "buffer" ? straightThroughBufferTask2(command) : straightThroughStringTask2(command); + return this._runTask(task, handler); + }; + Git2.prototype.diff = function(options, then) { + const task = filterString2(options) ? configurationErrorTask2("git.diff: supplying options as a single string is no longer supported, switch to an array of strings") : straightThroughStringTask2(["diff", ...getTrailingOptions2(arguments)]); + return this._runTask(task, trailingFunctionArgument2(arguments)); + }; + Git2.prototype.diffSummary = function() { + return this._runTask(diffSummaryTask2(getTrailingOptions2(arguments, 1)), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.applyPatch = function(patches) { + const task = !filterStringOrStringArray2(patches) ? configurationErrorTask2(`git.applyPatch requires one or more string patches as the first argument`) : applyPatchTask2(asArray2(patches), getTrailingOptions2([].slice.call(arguments, 1))); + return this._runTask(task, trailingFunctionArgument2(arguments)); + }; + Git2.prototype.revparse = function() { + const commands = ["rev-parse", ...getTrailingOptions2(arguments, true)]; + return this._runTask(straightThroughStringTask2(commands, true), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.clean = function(mode, options, then) { + const usingCleanOptionsArray = isCleanOptionsArray2(mode); + const cleanMode = usingCleanOptionsArray && mode.join("") || filterType2(mode, filterString2) || ""; + const customArgs = getTrailingOptions2([].slice.call(arguments, usingCleanOptionsArray ? 1 : 0)); + return this._runTask(cleanWithOptionsTask2(cleanMode, customArgs), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.exec = function(then) { + const task = { + commands: [], + format: "utf-8", + parser() { + if (typeof then === "function") { + then(); + } + } + }; + return this._runTask(task); + }; + Git2.prototype.clearQueue = function() { + return this; + }; + Git2.prototype.checkIgnore = function(pathnames, then) { + return this._runTask(checkIgnoreTask2(asArray2(filterType2(pathnames, filterStringOrStringArray2, []))), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.checkIsRepo = function(checkType, then) { + return this._runTask(checkIsRepoTask2(filterType2(checkType, filterString2)), trailingFunctionArgument2(arguments)); + }; + module.exports = Git2; + } +}); + +// src/lib/api.ts +init_pathspec(); + +// src/lib/errors/git-construct-error.ts +init_git_error(); +var GitConstructError = class extends GitError { + constructor(config, message) { + super(void 0, message); + this.config = config; + } +}; + +// src/lib/api.ts +init_git_error(); + +// src/lib/errors/git-plugin-error.ts +init_git_error(); +var GitPluginError = class extends GitError { + constructor(task, plugin, message) { + super(task, message); + this.task = task; + this.plugin = plugin; + Object.setPrototypeOf(this, new.target.prototype); + } +}; + +// src/lib/api.ts +init_git_response_error(); +init_task_configuration_error(); +init_check_is_repo(); +init_clean(); +init_config(); +init_grep(); +init_reset(); + +// src/lib/plugins/abort-plugin.ts +function abortPlugin(signal) { + if (!signal) { + return; + } + const onSpawnAfter = { + type: "spawn.after", + action(_data, context) { + function kill() { + context.kill(new GitPluginError(void 0, "abort", "Abort signal received")); + } + signal.addEventListener("abort", kill); + context.spawned.on("close", () => signal.removeEventListener("abort", kill)); + } + }; + const onSpawnBefore = { + type: "spawn.before", + action(_data, context) { + if (signal.aborted) { + context.kill(new GitPluginError(void 0, "abort", "Abort already signaled")); + } + } + }; + return [onSpawnBefore, onSpawnAfter]; +} + +// src/lib/plugins/block-unsafe-operations-plugin.ts +function isConfigSwitch(arg) { + return typeof arg === "string" && arg.trim().toLowerCase() === "-c"; +} +function preventProtocolOverride(arg, next) { + if (!isConfigSwitch(arg)) { + return; + } + if (!/^\s*protocol(.[a-z]+)?.allow/.test(next)) { + return; + } + throw new GitPluginError(void 0, "unsafe", "Configuring protocol.allow is not permitted without enabling allowUnsafeExtProtocol"); +} +function preventUploadPack(arg, method) { + if (/^\s*--(upload|receive)-pack/.test(arg)) { + throw new GitPluginError(void 0, "unsafe", `Use of --upload-pack or --receive-pack is not permitted without enabling allowUnsafePack`); + } + if (method === "clone" && /^\s*-u\b/.test(arg)) { + throw new GitPluginError(void 0, "unsafe", `Use of clone with option -u is not permitted without enabling allowUnsafePack`); + } + if (method === "push" && /^\s*--exec\b/.test(arg)) { + throw new GitPluginError(void 0, "unsafe", `Use of push with option --exec is not permitted without enabling allowUnsafePack`); + } +} +function blockUnsafeOperationsPlugin({ + allowUnsafeProtocolOverride = false, + allowUnsafePack = false +} = {}) { + return { + type: "spawn.args", + action(args, context) { + args.forEach((current, index) => { + const next = index < args.length ? args[index + 1] : ""; + allowUnsafeProtocolOverride || preventProtocolOverride(current, next); + allowUnsafePack || preventUploadPack(current, context.method); + }); + return args; + } + }; +} + +// src/lib/plugins/command-config-prefixing-plugin.ts +init_utils(); +function commandConfigPrefixingPlugin(configuration) { + const prefix = prefixedArray(configuration, "-c"); + return { + type: "spawn.args", + action(data) { + return [...prefix, ...data]; + } + }; +} + +// src/lib/plugins/completion-detection.plugin.ts +init_utils(); +var never = deferred_1().promise; +function completionDetectionPlugin({ + onClose = true, + onExit = 50 +} = {}) { + function createEvents() { + let exitCode = -1; + const events = { + close: deferred_1(), + closeTimeout: deferred_1(), + exit: deferred_1(), + exitTimeout: deferred_1() + }; + const result = Promise.race([ + onClose === false ? never : events.closeTimeout.promise, + onExit === false ? never : events.exitTimeout.promise + ]); + configureTimeout(onClose, events.close, events.closeTimeout); + configureTimeout(onExit, events.exit, events.exitTimeout); + return { + close(code) { + exitCode = code; + events.close.done(); + }, + exit(code) { + exitCode = code; + events.exit.done(); + }, + get exitCode() { + return exitCode; + }, + result + }; + } + function configureTimeout(flag, event, timeout) { + if (flag === false) { + return; + } + (flag === true ? event.promise : event.promise.then(() => delay(flag))).then(timeout.done); + } + return { + type: "spawn.after", + action(_0, _1) { + return __async(this, arguments, function* (_data, { spawned, close }) { + var _a2, _b; + const events = createEvents(); + let deferClose = true; + let quickClose = () => void (deferClose = false); + (_a2 = spawned.stdout) == null ? void 0 : _a2.on("data", quickClose); + (_b = spawned.stderr) == null ? void 0 : _b.on("data", quickClose); + spawned.on("error", quickClose); + spawned.on("close", (code) => events.close(code)); + spawned.on("exit", (code) => events.exit(code)); + try { + yield events.result; + if (deferClose) { + yield delay(50); + } + close(events.exitCode); + } catch (err) { + close(events.exitCode, err); + } + }); + } + }; +} + +// src/lib/plugins/error-detection.plugin.ts +init_git_error(); +function isTaskError(result) { + return !!(result.exitCode && result.stdErr.length); +} +function getErrorMessage(result) { + return Buffer.concat([...result.stdOut, ...result.stdErr]); +} +function errorDetectionHandler(overwrite = false, isError = isTaskError, errorMessage = getErrorMessage) { + return (error, result) => { + if (!overwrite && error || !isError(result)) { + return error; + } + return errorMessage(result); + }; +} +function errorDetectionPlugin(config) { + return { + type: "task.error", + action(data, context) { + const error = config(data.error, { + stdErr: context.stdErr, + stdOut: context.stdOut, + exitCode: context.exitCode + }); + if (Buffer.isBuffer(error)) { + return { error: new GitError(void 0, error.toString("utf-8")) }; + } + return { + error + }; + } + }; +} + +// src/lib/plugins/plugin-store.ts +init_utils(); +var PluginStore = class { + constructor() { + this.plugins = /* @__PURE__ */ new Set(); + } + add(plugin) { + const plugins = []; + asArray(plugin).forEach((plugin2) => plugin2 && this.plugins.add(append$1(plugins, plugin2))); + return () => { + plugins.forEach((plugin2) => this.plugins.delete(plugin2)); + }; + } + exec(type, data, context) { + let output = data; + const contextual = Object.freeze(Object.create(context)); + for (const plugin of this.plugins) { + if (plugin.type === type) { + output = plugin.action(output, contextual); + } + } + return output; + } +}; + +// src/lib/plugins/progress-monitor-plugin.ts +init_utils(); +function progressMonitorPlugin(progress) { + const progressCommand = "--progress"; + const progressMethods = ["checkout", "clone", "fetch", "pull", "push"]; + const onProgress = { + type: "spawn.after", + action(_data, context) { + var _a2; + if (!context.commands.includes(progressCommand)) { + return; + } + (_a2 = context.spawned.stderr) == null ? void 0 : _a2.on("data", (chunk) => { + const message = /^([\s\S]+?):\s*(\d+)% \((\d+)\/(\d+)\)/.exec(chunk.toString("utf8")); + if (!message) { + return; + } + progress({ + method: context.method, + stage: progressEventStage(message[1]), + progress: asNumber(message[2]), + processed: asNumber(message[3]), + total: asNumber(message[4]) + }); + }); + } + }; + const onArgs = { + type: "spawn.args", + action(args, context) { + if (!progressMethods.includes(context.method)) { + return args; + } + return including(args, progressCommand); + } + }; + return [onArgs, onProgress]; +} +function progressEventStage(input) { + return String(input.toLowerCase().split(" ", 1)) || "unknown"; +} + +// src/lib/plugins/spawn-options-plugin.ts +init_utils(); +function spawnOptionsPlugin(spawnOptions) { + const options = pick(spawnOptions, ["uid", "gid"]); + return { + type: "spawn.options", + action(data) { + return __spreadValues(__spreadValues({}, options), data); + } + }; +} + +// src/lib/plugins/timout-plugin.ts +function timeoutPlugin({ + block, + stdErr = true, + stdOut = true +}) { + if (block > 0) { + return { + type: "spawn.after", + action(_data, context) { + var _a2, _b; + let timeout; + function wait() { + timeout && clearTimeout(timeout); + timeout = setTimeout(kill, block); + } + function stop() { + var _a3, _b2; + (_a3 = context.spawned.stdout) == null ? void 0 : _a3.off("data", wait); + (_b2 = context.spawned.stderr) == null ? void 0 : _b2.off("data", wait); + context.spawned.off("exit", stop); + context.spawned.off("close", stop); + timeout && clearTimeout(timeout); + } + function kill() { + stop(); + context.kill(new GitPluginError(void 0, "timeout", `block timeout reached`)); + } + stdOut && ((_a2 = context.spawned.stdout) == null ? void 0 : _a2.on("data", wait)); + stdErr && ((_b = context.spawned.stderr) == null ? void 0 : _b.on("data", wait)); + context.spawned.on("exit", stop); + context.spawned.on("close", stop); + wait(); + } + }; + } +} + +// src/lib/plugins/suffix-paths.plugin.ts +init_pathspec(); +function suffixPathsPlugin() { + return { + type: "spawn.args", + action(data) { + const prefix = []; + let suffix; + function append2(args) { + (suffix = suffix || []).push(...args); + } + for (let i = 0; i < data.length; i++) { + const param = data[i]; + if (isPathSpec(param)) { + append2(toPaths(param)); + continue; + } + if (param === "--") { + append2(data.slice(i + 1).flatMap((item) => isPathSpec(item) && toPaths(item) || item)); + break; + } + prefix.push(param); + } + return !suffix ? prefix : [...prefix, "--", ...suffix.map(String)]; + } + }; +} + +// src/lib/git-factory.ts +init_utils(); +var Git = require_git(); +function gitInstanceFactory(baseDir, options) { + const plugins = new PluginStore(); + const config = createInstanceConfig(baseDir && (typeof baseDir === "string" ? { baseDir } : baseDir) || {}, options); + if (!folderExists(config.baseDir)) { + throw new GitConstructError(config, `Cannot use simple-git on a directory that does not exist`); + } + if (Array.isArray(config.config)) { + plugins.add(commandConfigPrefixingPlugin(config.config)); + } + plugins.add(blockUnsafeOperationsPlugin(config.unsafe)); + plugins.add(suffixPathsPlugin()); + plugins.add(completionDetectionPlugin(config.completion)); + config.abort && plugins.add(abortPlugin(config.abort)); + config.progress && plugins.add(progressMonitorPlugin(config.progress)); + config.timeout && plugins.add(timeoutPlugin(config.timeout)); + config.spawnOptions && plugins.add(spawnOptionsPlugin(config.spawnOptions)); + plugins.add(errorDetectionPlugin(errorDetectionHandler(true))); + config.errors && plugins.add(errorDetectionPlugin(config.errors)); + return new Git(config, plugins); +} + +// src/lib/runners/promise-wrapped.ts +init_git_response_error(); + +// src/esm.mjs +var simpleGit = gitInstanceFactory; + +// eslint-disable-next-line no-restricted-imports +const registryUrl = 'https://registry.npmjs.com/rdme'; +/** + * The current `rdme` version + * + * @param npmDistTag the `npm` dist tag to retrieve. If this value is omitted, + * the version from the `package.json` is returned. + * @example "8.0.0" + * @see {@link https://docs.npmjs.com/adding-dist-tags-to-packages} + * @note we mock this function in our snapshots, hence it's not the default + * @see {@link https://stackoverflow.com/a/54245672} + */ +async function getPkgVersion(npmDistTag) { + if (npmDistTag) { + return fetch$4(registryUrl) + .then(res => res.json()) + .then(body => body['dist-tags'][npmDistTag]) + .catch(err => { + error$n(`error fetching version from npm registry: ${err.message}`); + return pkg.version; + }); + } + return pkg.version; +} +/** + * The current major `rdme` version + * + * @example 8 + */ +const getMajorPkgVersion = async (npmDistTag) => semver$1.major(await getPkgVersion(npmDistTag)); + +/** + * Removes any non-alphanumeric characters and replaces them with hyphens. + * + * This is used for file names and for YAML keys. + */ +const cleanFileName = (input) => input.replace(/[^a-z0-9]/gi, '-'); +/** + * A validator function used in our prompts for when a user + * is prompted to specify a file path. + * + * @param value the file name + * @param getFullPath An optional function for adding a file path or any filename validations + * @returns true if path is valid (i.e. is non-empty and doesn't already exist), + * otherwise a string containing the error message + */ +function validateFilePath(value, getFullPath = file => file) { + if (value.length) { + const fullPath = getFullPath(value); + if (!fs$i.existsSync(fullPath)) { + return true; + } + return 'Specified output path already exists.'; + } + return 'An output path must be supplied.'; +} +/** + * Validates that a project subdomain value is valid. + * + * @param value the terminal input + * @returns true if the subdomain value is valid, else an error message + */ +function validateSubdomain(value) { + return (/^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$/.test(value) || 'Project subdomain must contain only letters, numbers and dashes.'); +} + +/** + * The base GitHub Actions workflow file, which is used for generating the YAML file. + * + * The reason this is expressed as a JavaScript string as opposed to a YAML file is because + * TypeScript doesn't have a great way to copy over non-TS files to the `dist/`. + * Plus, this way we can write internal comments like this! + * + * @see {@link https://github.com/microsoft/TypeScript/issues/30835} + * @see {@link https://docs.github.com/actions/using-workflows/workflow-syntax-for-github-actions} + */ +const yamlBase = `# This GitHub Actions workflow was auto-generated by the \`rdme\` cli on {{timestamp}} +# You can view our full documentation here: https://docs.readme.com/docs/rdme +name: ReadMe GitHub Action 🦉 + +on: + push: + branches: + # This workflow will run every time you push code to the following branch: \`{{branch}}\` + # Check out GitHub's docs for more info on configuring this: + # https://docs.github.com/actions/using-workflows/events-that-trigger-workflows + - {{branch}} + +jobs: + rdme-{{cleanCommand}}: + runs-on: ubuntu-latest + steps: + - name: Check out repo 📚 + uses: actions/checkout@v4 + + - name: Run \`{{command}}\` command 🚀 + uses: readmeio/rdme@{{rdmeVersion}} + with: + rdme: {{commandString}} +`; + +/** + * Generates the key for storing info in `configstore` object. + * @param repoRoot The root of the repo + */ +const getConfigStoreKey = (repoRoot) => `createGHA.${repoRoot}`; +/** + * The directory where GitHub Actions workflow files are stored. + * + * This is the same across all repositories on GitHub. + * + * @see {@link https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#about-yaml-syntax-for-workflows} + */ +const GITHUB_WORKFLOW_DIR = '.github/workflows'; +const GITHUB_SECRET_NAME = 'README_API_KEY'; +const git = simpleGit(); +/** + * Removes any non-file-friendly characters and adds + * the full path + file extension for GitHub Workflow files. + * @param fileName raw file name to clean up + */ +const getGHAFileName = (fileName) => { + return path$c.join(GITHUB_WORKFLOW_DIR, `${cleanFileName(fileName).toLowerCase()}.yml`); +}; +/** + * Returns a redacted `key` if the current command uses authentication. + * Otherwise, returns `false`. + */ +function getKey$2(args, opts) { + if (args.some(arg => arg.name === 'key')) { + return `••••••••••••${opts.key.slice(-5)}`; + } + return false; +} +/** + * Constructs the command string that we pass into the workflow file. + */ +function constructCmdString(command, args, opts) { + const optsString = args + .sort(arg => (arg.defaultOption ? -1 : 0)) + .map(arg => { + const val = opts[arg.name]; + // if default option, return the value + if (arg.defaultOption) + return val; + // obfuscate the key in a GitHub secret + if (arg.name === 'key') + return `--key=$\{{ secrets.${GITHUB_SECRET_NAME} }}`; + // remove the GitHub flag + if (arg.name === 'github') + return false; + // if a boolean value, return the flag + if (arg.type === Boolean && val) + return `--${arg.name}`; + if (val) + return `--${arg.name}=${val}`; + return false; + }) + .filter(Boolean) + .join(' '); + return `${command} ${optsString}`.trim(); +} +/** + * Function to return various git attributes needed for running GitHub Action + */ +async function getGitData() { + // Expressions to search raw output of `git remote show origin` + const headRegEx = /^ {2}HEAD branch: /g; + const headLineRegEx = /^ {2}HEAD branch:.*/gm; + const isRepo = await git.checkIsRepo().catch(e => { + debug(`error running git repo check: ${e.message}`); + return false; + }); + debug(`[getGitData] isRepo result: ${isRepo}`); + let containsGitHubRemote; + let defaultBranch; + const rawRemotes = await git.remote([]).catch(e => { + debug(`[getGitData] error grabbing git remotes: ${e.message}`); + return ''; + }); + debug(`[getGitData] rawRemotes result: ${rawRemotes}`); + if (rawRemotes) { + const remote = rawRemotes.split('\n')[0]; + debug(`[getGitData] remote result: ${remote}`); + const rawRemote = await git.remote(['show', remote]).catch(e => { + debug(`[getGitData] error accessing remote: ${e.message}`); + return ''; + }); + debug(`[getGitData] rawRemote result: ${rawRemote}`); + // Extract head branch from git output + const rawHead = headLineRegEx.exec(rawRemote)?.[0]; + debug(`[getGitData] rawHead result: ${rawHead}`); + if (rawHead) + defaultBranch = rawHead.replace(headRegEx, ''); + // Extract the word 'github' from git output + const remotesList = (await git.remote(['-v'])); + debug(`[getGitData] remotesList result: ${remotesList}`); + // This is a bit hairy but we want to keep it fairly general here + // in case of GitHub Enterprise, etc. + containsGitHubRemote = /github/.test(remotesList); + } + debug(`[getGitData] containsGitHubRemote result: ${containsGitHubRemote}`); + debug(`[getGitData] defaultBranch result: ${defaultBranch}`); + const repoRoot = await git.revparse(['--show-toplevel']).catch(e => { + debug(`[getGitData] error grabbing git root: ${e.message}`); + return ''; + }); + debug(`[getGitData] repoRoot result: ${repoRoot}`); + return { containsGitHubRemote, defaultBranch, isRepo, repoRoot }; +} +/** + * Post-command flow for creating a GitHub Actions workflow file. + * + */ +async function createGHA(msg, command, args, opts) { + debug(`running GHA onboarding for ${command} command`); + debug(`opts used in createGHA: ${JSON.stringify(opts)}`); + // if in a CI environment, + // don't even bother running the git commands + if (!opts.github && (isCI() || isNpmScript())) { + debug('not running GHA onboarding workflow in CI and/or npm script, exiting'); + return msg; + } + const { containsGitHubRemote, defaultBranch, isRepo, repoRoot } = await getGitData(); + const configVal = configstore.get(getConfigStoreKey(repoRoot)); + debug(`repo value in config: ${configVal}`); + const majorPkgVersion = await getMajorPkgVersion(); + debug(`major pkg version: ${majorPkgVersion}`); + if (!opts.github) { + if ( + // not a repo + !isRepo || + // user has previously declined to set up GHA for current repo and `rdme` package version + configVal === majorPkgVersion || + // is a repo, but does not contain a GitHub remote + (isRepo && !containsGitHubRemote) || + // not testing this function + (isTest() && !process.env.TEST_RDME_CREATEGHA)) { + debug('not running GHA onboarding workflow, exiting'); + // We return the original command message and pretend this command flow never happened. + return msg; + } + } + if (msg) + info(msg, { includeEmojiPrefix: false }); + if (opts.github) { + info(chalk$5.bold("\n🚀 Let's get you set up with GitHub Actions! 🚀\n"), { includeEmojiPrefix: false }); + } + else { + info([ + '', + chalk$5.bold("🐙 Looks like you're running this command in a GitHub Repository! 🐙"), + '', + `🚀 With a few quick clicks, you can run this \`${command}\` command via GitHub Actions (${chalk$5.underline('https://github.com/features/actions')})`, + '', + `✨ This means it will run ${chalk$5.italic('automagically')} with every push to a branch of your choice!`, + '', + ].join('\n'), { includeEmojiPrefix: false }); + } + const previousWorkingDirectory = process.cwd(); + if (repoRoot && repoRoot !== previousWorkingDirectory) { + process.chdir(repoRoot); + debug(`switching working directory from ${previousWorkingDirectory} to ${process.cwd()}`); + } + prompts$1.override({ shouldCreateGHA: opts.github }); + const { branch, filePath, shouldCreateGHA } = await promptTerminal([ + { + message: 'Would you like to add a GitHub Actions workflow?', + name: 'shouldCreateGHA', + type: 'confirm', + initial: true, + }, + { + message: 'What GitHub branch should this workflow run on?', + name: 'branch', + type: 'text', + initial: defaultBranch || 'main', + }, + { + message: 'What would you like to name the GitHub Actions workflow file?', + name: 'filePath', + type: 'text', + initial: cleanFileName(`rdme-${command}`), + format: prev => getGHAFileName(prev), + validate: value => validateFilePath(value, getGHAFileName), + }, + ], { + // @ts-expect-error answers is definitely an object, + // despite TS insisting that it's an array. + // link: https://github.com/terkelg/prompts#optionsonsubmit + onSubmit: (p, a, answers) => !answers.shouldCreateGHA, + }); + if (!shouldCreateGHA) { + // if the user says no, we don't want to bug them again + // for this repo and version of `rdme + configstore.set(getConfigStoreKey(repoRoot), majorPkgVersion); + throw new Error('GitHub Actions workflow creation cancelled. If you ever change your mind, you can run this command again with the `--github` flag.'); + } + const data = { + branch, + cleanCommand: cleanFileName(command), + command, + commandString: constructCmdString(command, args, opts), + rdmeVersion: `v${majorPkgVersion}`, + timestamp: new Date().toISOString(), + }; + debug(`data for resolver: ${JSON.stringify(data)}`); + let output = yamlBase; + Object.keys(data).forEach((key) => { + output = output.replace(new RegExp(`{{${key}}}`, 'g'), data[key]); + }); + if (!fs$i.existsSync(GITHUB_WORKFLOW_DIR)) { + debug('GHA workflow directory does not exist, creating'); + fs$i.mkdirSync(GITHUB_WORKFLOW_DIR, { recursive: true }); + } + fs$i.writeFileSync(filePath, output); + const success = [chalk$5.green('\nYour GitHub Actions workflow file has been created! ✨\n')]; + const key = getKey$2(args, opts); + if (key) { + success.push(chalk$5.bold('Almost done! Just a couple more steps:'), `1. Push your newly created file (${chalk$5.underline(filePath)}) to GitHub 🚀`, `2. Create a GitHub secret called ${chalk$5.bold(GITHUB_SECRET_NAME)} and populate the value with your ReadMe API key (${key}) 🔑`, '', `🔐 Check out GitHub's docs for more info on creating encrypted secrets (${chalk$5.underline('https://docs.github.com/actions/security-guides/encrypted-secrets#creating-encrypted-secrets-for-a-repository')})`); + } + else { + success.push(`${chalk$5.bold('Almost done!')} Push your newly created file (${chalk$5.underline(filePath)}) to GitHub and you're all set 🚀`); + } + success.push('', `🦉 If you have any more questions, feel free to drop us a line! ${chalk$5.underline('support@readme.io')}`, ''); + return Promise.resolve(success.join('\n')); +} + +const SUCCESS_NO_CONTENT = 204; +function getProxy() { + // this is something of an industry standard env var, hence the checks for different casings + const proxy = process.env.HTTPS_PROXY || process.env.https_proxy; + if (proxy) { + // adds trailing slash + return proxy.endsWith('/') ? proxy : `${proxy}/`; + } + return ''; +} +function stripQuotes(s) { + if (!s) + return ''; + return s.replace(/(^"|[",]*$)/g, ''); +} +/** + * Parses Warning header into an array of warning header objects + * @param header raw `Warning` header + * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Warning} + * @see {@link https://www.rfc-editor.org/rfc/rfc7234#section-5.5} + * @see {@link https://github.com/marcbachmann/warning-header-parser} + */ +function parseWarningHeader(header) { + try { + const warnings = header.split(/([0-9]{3} [a-z0-9.@\-/]*) /g); + let previous; + return warnings.reduce((all, w) => { + // eslint-disable-next-line no-param-reassign + w = w.trim(); + const newError = w.match(/^([0-9]{3}) (.*)/); + if (newError) { + previous = { code: newError[1], agent: newError[2], message: '' }; + } + else if (w) { + const errorContent = w.split(/" "/); + if (errorContent) { + previous.message = stripQuotes(errorContent[0]); + previous.date = stripQuotes(errorContent[1]); + all.push(previous); + } + } + return all; + }, []); + } + catch (e) { + debug(`error parsing warning header: ${e.message}`); + return [{ code: '199', agent: '-', message: header }]; + } +} +/** + * Getter function for a string to be used in the user-agent header based on the current + * environment. + * + */ +function getUserAgent() { + const gh = isGHA() ? '-github' : ''; + return `rdme${gh}/${pkg.version}`; +} +/** + * Creates a relative path for the file from the root of the repo, + * otherwise returns the path + */ +async function normalizeFilePath(opts) { + if (opts.fileType === 'path') { + const repoRoot = await git.revparse(['--show-toplevel']).catch(e => { + debug(`[fetch] error grabbing git root: ${e.message}`); + return ''; + }); + return path$c.relative(repoRoot, opts.filePath); + } + return opts.filePath; +} +/** + * Sanitizes and stringifies the `Headers` object for logging purposes + */ +function sanitizeHeaders(headers) { + const raw = new Headers$2(headers).raw(); + if (raw.Authorization) + raw.Authorization = ['redacted']; + return JSON.stringify(raw); +} +/** + * Wrapper for the `fetch` API so we can add rdme-specific headers to all API requests. + * + * @param pathname the pathname to make the request to. Must have a leading slash. + * @param fileOpts optional object containing information about the file being sent. + * We use this to construct a full source URL for the file. + */ +async function readmeAPIFetch(pathname, options = { headers: new Headers$2() }, fileOpts = { filePath: '', fileType: false }) { + let source = 'cli'; + let headers = options.headers; + if (!(options.headers instanceof Headers$2)) { + headers = new Headers$2(options.headers); + } + headers.set('User-Agent', getUserAgent()); + if (isGHA()) { + source = 'cli-gh'; + headers.set('x-github-repository', process.env.GITHUB_REPOSITORY); + headers.set('x-github-run-attempt', process.env.GITHUB_RUN_ATTEMPT); + headers.set('x-github-run-id', process.env.GITHUB_RUN_ID); + headers.set('x-github-run-number', process.env.GITHUB_RUN_NUMBER); + headers.set('x-github-sha', process.env.GITHUB_SHA); + const filePath = await normalizeFilePath(fileOpts); + if (filePath) { + /** + * Constructs a full URL to the file using GitHub Actions runner variables + * @see {@link https://docs.github.com/en/actions/learn-github-actions/environment-variables#default-environment-variables} + * @example https://github.com/readmeio/rdme/blob/cb4129d5c7b51ff3b50f933a9c7d0c3d0d33d62c/documentation/rdme.md + */ + try { + const sourceUrl = new URL(`${process.env.GITHUB_SERVER_URL}/${process.env.GITHUB_REPOSITORY}/blob/${process.env.GITHUB_SHA}/${filePath}`).href; + headers.set('x-readme-source-url', sourceUrl); + } + catch (e) { + debug(`error constructing github source url: ${e.message}`); + } + } + } + if (isCI()) { + headers.set('x-rdme-ci', ciName()); + } + headers.set('x-readme-source', source); + if (fileOpts.filePath && fileOpts.fileType === 'url') { + headers.set('x-readme-source-url', fileOpts.filePath); + } + const fullUrl = `${getProxy()}${config.host}${pathname}`; + debug(`making ${(options.method || 'get').toUpperCase()} request to ${fullUrl} with headers: ${sanitizeHeaders(headers)}`); + return fetch$4(fullUrl, { + ...options, + headers, + }).then(res => { + const warningHeader = res.headers.get('Warning'); + if (warningHeader) { + debug(`received warning header: ${warningHeader}`); + const warnings = parseWarningHeader(warningHeader); + warnings.forEach(warning => { + warn$1(warning.message, 'ReadMe API Warning:'); + }); + } + return res; + }); +} +/** + * Small handler for handling responses from our API. + * + * If we receive JSON errors, we throw an APIError exception. + * + * If we receive non-JSON responses, we consider them errors and throw them. + * + * @param rejectOnJsonError if omitted (or set to true), the function will return + * an `APIError` if the JSON body contains an `error` property. If set to false, + * the function will return a resolved promise containing the JSON object. + * + */ +async function handleRes(res, rejectOnJsonError = true) { + const contentType = res.headers.get('content-type'); + const extension = mime.extension(contentType); + if (extension === 'json') { + // TODO: type this better + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const body = (await res.json()); + debug(`received status code ${res.status} from ${res.url} with JSON response: ${JSON.stringify(body)}`); + if (body.error && rejectOnJsonError) { + return Promise.reject(new APIError(body)); + } + return body; + } + if (res.status === SUCCESS_NO_CONTENT) { + debug(`received status code ${res.status} from ${res.url} with no content`); + return {}; + } + // If we receive a non-JSON response, it's likely an error. + // Let's debug the raw response body and throw it. + const body = await res.text(); + debug(`received status code ${res.status} from ${res.url} with non-JSON response: ${body}`); + return Promise.reject(body); +} +/** + * Returns the basic auth header and any other defined headers for use in `node-fetch` API calls. + * + */ +function cleanHeaders(key, inputHeaders = new Headers$2()) { + const encodedKey = Buffer.from(`${key}:`).toString('base64'); + const headers = new Headers$2({ + Authorization: `Basic ${encodedKey}`, + }); + for (const header of inputHeaders.entries()) { + // If you supply `undefined` or `null` to the `Headers` API it'll convert that those to a + // string. + if (header[1] !== 'null' && header[1] !== 'undefined' && header[1].length > 0) { + headers.set(header[0], header[1]); + } + } + return headers; +} + +function loginFetch(body) { + return readmeAPIFetch('/api/v1/login', { + method: 'post', + headers: { Accept: 'application/json', 'Content-Type': 'application/json' }, + body: JSON.stringify(body), + }); +} +/** + * The prompt flow for logging a user in and writing the credentials to + * `configstore`. This is a separate lib function because we reuse it both + * in the `login` command as well as any time a user omits an API key. + * @param otp an optional one-time passcode, if the user passes one in + * via a flag to the the `login` command + * @returns A Promise-wrapped string with the logged-in user's credentials + */ +async function loginFlow(otp) { + const storedConfig = getCurrentConfig(); + const { email, password, project } = await promptTerminal([ + { + type: 'text', + name: 'email', + message: 'What is your email address?', + initial: storedConfig.email, + validate(val) { + return isEmail.default(val) ? true : 'Please provide a valid email address.'; + }, + }, + { + type: 'invisible', + name: 'password', + message: 'What is your password?', + }, + { + type: 'text', + name: 'project', + message: 'What project subdomain are you logging into?', + initial: storedConfig.project, + validate: validateSubdomain, + }, + ]); + if (!project) { + return Promise.reject(new Error('No project subdomain provided. Please use `--project`.')); + } + if (!isEmail.default(email)) { + return Promise.reject(new Error('You must provide a valid email address.')); + } + const payload = { email, password, project }; + // if the user passed in a `otp` option, include that in the login payload + if (otp) + payload.token = otp; + return loginFetch(payload) + .then(handleRes) + .catch(async (err) => { + // if the user's login requires 2FA, let's prompt them for the token! + if (err.code === 'LOGIN_TWOFACTOR') { + debug('2FA error response, prompting for 2FA code'); + const otpPrompt = await promptTerminal({ + type: 'text', + name: 'otp', + message: 'What is your 2FA token?', + }); + return loginFetch({ email, password, project, token: otpPrompt.otp }).then(handleRes); + } + throw err; + }) + .then(res => { + configstore.set('apiKey', res.apiKey); + configstore.set('email', email); + configstore.set('project', project); + return `Successfully logged in as ${chalk$5.green(email)} to the ${chalk$5.blue(project)} project.`; + }); +} + +var CommandCategories; +(function (CommandCategories) { + CommandCategories["ADMIN"] = "admin"; + CommandCategories["APIS"] = "apis"; + CommandCategories["CATEGORIES"] = "categories"; + CommandCategories["CHANGELOGS"] = "changelogs"; + CommandCategories["CUSTOM_PAGES"] = "custompages"; + CommandCategories["DOCS"] = "docs"; + CommandCategories["UTILITIES"] = "utilities"; + CommandCategories["VERSIONS"] = "versions"; +})(CommandCategories || (CommandCategories = {})); +class Command { + constructor() { + /** + * Should the command be hidden from our `--help` screens? + */ + this.hidden = false; + /** + * Does the command run the GitHub Actions onboarding called via + * `src/index.ts`? + */ + this.supportsGHA = false; + /** + * Arguments to hide from the individual command help screen + * (typically used for hiding default arguments) + * + * @example ['spec'] + */ + this.hiddenArgs = []; + } + async run(opts) { + Command.debug(`command: ${this.command}`); + Command.debug(`opts: ${JSON.stringify(opts)}`); + if (this.args.some(arg => arg.name === 'key')) { + const { email, project } = getCurrentConfig(); + // We only want to log this if the API key is stored in the configstore, **not** in an env var. + if (opts.key && configstore.get('apiKey') === opts.key) { + info(`🔑 ${chalk$5.green(email)} is currently logged in, using the stored API key for this project: ${chalk$5.blue(project)}`, { includeEmojiPrefix: false }); + } + if (!opts.key) { + if (isCI()) { + throw new Error('No project API key provided. Please use `--key`.'); + } + info("Looks like you're missing a ReadMe API key, let's fix that! 🦉", { includeEmojiPrefix: false }); + const result = await loginFlow(); + info(result, { includeEmojiPrefix: false }); + // eslint-disable-next-line no-param-reassign + opts.key = configstore.get('apiKey'); + } + } + if (opts.github && isCI()) { + throw new Error('The `--github` flag is only for usage in non-CI environments.'); + } + // This is a bit of a hack so we can keep our types consistent + // for this `run` function. + return Promise.resolve(''); + } + /** + * Used in any command where `github` is an option. + */ + getGitHubArg() { + return { + name: 'github', + type: Boolean, + description: 'Create a new GitHub Actions workflow for this command.', + }; + } + /** + * Used in any command where `key` is an option. + */ + getKeyArg() { + return { + name: 'key', + type: String, + description: 'Project API key', + }; + } + /** + * Used in the `openapi` family of commands where `title` is an option. + */ + getTitleArg() { + return { + name: 'title', + type: String, + description: 'An override value for the `info.title` field in the API definition', + }; + } + /** + * Used in any command where `version` is an option. + */ + getVersionArg() { + return { + name: 'version', + type: String, + description: 'Project version. If running command in a CI environment and this option is not passed, the main project version will be used.', + }; + } + /** + * Used in the `versions:create` and `versions:update` commands. + */ + getVersionOpts() { + return [ + { + name: 'version', + type: String, + defaultOption: true, + }, + { + name: 'codename', + type: String, + description: 'The codename, or nickname, for a particular version.', + }, + { + name: 'main', + type: String, + description: "Should this version be the primary (default) version for your project? (Must be 'true' or 'false')", + }, + { + name: 'beta', + type: String, + description: "Is this version in beta? (Must be 'true' or 'false')", + }, + { + name: 'deprecated', + type: String, + description: "Would you like to deprecate this version? (Must be 'true' or 'false')", + }, + { + name: 'isPublic', + type: String, + description: "Would you like to make this version public? Any primary version must be public. (Must be 'true' or 'false')", + }, + ]; + } + /** + * Used in the `openapi` family of commands where `workingDirectory` is an option. + */ + getWorkingDirArg() { + return { + name: 'workingDirectory', + type: String, + description: 'Working directory (for usage with relative external references)', + }; + } + static debug(msg) { + debug(msg); + } + static info(msg) { + info(msg); + } + static warn(msg) { + warn$1(msg); + } +} + +/** + * Returns all categories for a given project and version + * + * @param {String} key project API key + * @param {String} selectedVersion project version + * @returns An array of category objects + */ +async function getCategories$1(key, selectedVersion) { + function getNumberOfPages() { + let totalCount = 0; + return readmeAPIFetch('/api/v1/categories?perPage=20&page=1', { + method: 'get', + headers: cleanHeaders(key, new Headers$2({ + 'x-readme-version': selectedVersion, + Accept: 'application/json', + })), + }) + .then(res => { + totalCount = Math.ceil(parseInt(res.headers.get('x-total-count'), 10) / 20); + return handleRes(res); + }) + .then(res => { + return { firstPage: res, totalCount }; + }); + } + const { firstPage, totalCount } = await getNumberOfPages(); + const allCategories = firstPage.concat(...(await Promise.all( + // retrieves all categories beyond first page + [...new Array(totalCount + 1).keys()].slice(2).map(async (page) => { + return readmeAPIFetch(`/api/v1/categories?perPage=20&page=${page}`, { + method: 'get', + headers: cleanHeaders(key, new Headers$2({ + 'x-readme-version': selectedVersion, + Accept: 'application/json', + })), + }).then(handleRes); + })))); + return allCategories; +} + +/** + * Validates and returns a project version. + * + * @param versionFlag version input parameter + * @param key project API key + * @returns a cleaned up project version + */ +async function getProjectVersion(versionFlag, key, returnStable = false) { + try { + if (versionFlag) { + return await readmeAPIFetch(`/api/v1/version/${versionFlag}`, { + method: 'get', + headers: cleanHeaders(key), + }) + .then(handleRes) + .then((res) => res.version); + } + if (isCI()) { + warn$1('No `--version` parameter detected in current CI environment. Defaulting to main version.'); + return undefined; + } + const versionList = await readmeAPIFetch('/api/v1/version', { + method: 'get', + headers: cleanHeaders(key), + }).then(handleRes); + if (versionList.length === 1) { + return versionList[0].version; + } + if (returnStable) { + const stableVersion = versionList.find(v => v.is_stable === true); + return stableVersion.version; + } + const { versionSelection } = await promptTerminal({ + type: 'select', + name: 'versionSelection', + message: 'Select your desired version', + choices: versionList.map(v => { + return { + title: v.version, + value: v.version, + }; + }), + }); + return versionSelection; + } + catch (err) { + return Promise.reject(new APIError(err)); + } +} + +class CategoriesCreateCommand extends Command { + constructor() { + super(); + this.command = 'categories:create'; + this.usage = 'categories:create [options]'; + this.description = 'Create a category with the specified title and guide in your ReadMe project.'; + this.cmdCategory = CommandCategories.CATEGORIES; + this.hiddenArgs = ['title']; + this.args = [ + this.getKeyArg(), + this.getVersionArg(), + { + name: 'title', + type: String, + defaultOption: true, + }, + { + name: 'categoryType', + type: String, + description: 'Category type, must be `guide` or `reference`', + }, + { + name: 'preventDuplicates', + type: Boolean, + description: 'Prevents the creation of a new category if there is an existing category with a matching `categoryType` and `title`', + }, + ]; + } + async run(opts) { + await super.run(opts); + const { categoryType, title, key, version, preventDuplicates } = opts; + if (!title) { + return Promise.reject(new Error(`No title provided. Usage \`${config.cli} ${this.usage}\`.`)); + } + if (categoryType !== 'guide' && categoryType !== 'reference') { + return Promise.reject(new Error('`categoryType` must be `guide` or `reference`.')); + } + const selectedVersion = await getProjectVersion(version, key); + Command.debug(`selectedVersion: ${selectedVersion}`); + async function matchCategory() { + const allCategories = await getCategories$1(key, selectedVersion); + return allCategories.find((category) => { + return category.title.trim().toLowerCase() === title.trim().toLowerCase() && category.type === categoryType; + }); + } + async function createCategory() { + if (preventDuplicates) { + const matchedCategory = await matchCategory(); + if (typeof matchedCategory !== 'undefined') { + return Promise.reject(new Error(`The '${matchedCategory.title}' category with a type of '${matchedCategory.type}' already exists with an id of '${matchedCategory.id}'. A new category was not created.`)); + } + } + return readmeAPIFetch('/api/v1/categories', { + method: 'post', + headers: cleanHeaders(key, new Headers$2({ + 'x-readme-version': selectedVersion, + 'Content-Type': 'application/json', + })), + body: JSON.stringify({ + title, + type: categoryType, + }), + }) + .then(handleRes) + .then(res => `🌱 successfully created '${res.title}' with a type of '${res.type}' and an id of '${res.id}'`); + } + const createdCategory = chalk$5.green(await createCategory()); + return Promise.resolve(createdCategory); + } +} + +class CategoriesCommand extends Command { + constructor() { + super(); + this.command = 'categories'; + this.usage = 'categories [options]'; + this.description = 'Get all categories in your ReadMe project.'; + this.cmdCategory = CommandCategories.CATEGORIES; + this.args = [this.getKeyArg(), this.getVersionArg()]; + } + async run(opts) { + await super.run(opts); + const { key, version } = opts; + const selectedVersion = await getProjectVersion(version, key); + Command.debug(`selectedVersion: ${selectedVersion}`); + const allCategories = await getCategories$1(key, selectedVersion); + return Promise.resolve(JSON.stringify(allCategories, null, 2)); + } +} + +/* eslint-disable @typescript-eslint/no-explicit-any */ +/** + * This TypeScript decorator will enable the GitHub Action onboarding workflow + * for the decorated command. + * + * @see {@link https://www.typescriptlang.org/docs/handbook/decorators.html#class-decorators} + */ +function supportsGHA(constructor) { + return class extends constructor { + constructor() { + super(...arguments); + this.supportsGHA = true; + } + }; +} + +// A simple implementation of make-array +function makeArray (subject) { + return Array.isArray(subject) + ? subject + : [subject] +} + +const EMPTY = ''; +const SPACE$1 = ' '; +const ESCAPE = '\\'; +const REGEX_TEST_BLANK_LINE = /^\s+$/; +const REGEX_INVALID_TRAILING_BACKSLASH = /(?:[^\\]|^)\\$/; +const REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/; +const REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\#/; +const REGEX_SPLITALL_CRLF = /\r?\n/g; +// /foo, +// ./foo, +// ../foo, +// . +// .. +const REGEX_TEST_INVALID_PATH = /^\.*\/|^\.+$/; + +const SLASH$1 = '/'; + +// Do not use ternary expression here, since "istanbul ignore next" is buggy +let TMP_KEY_IGNORE = 'node-ignore'; +/* istanbul ignore else */ +if (typeof Symbol !== 'undefined') { + TMP_KEY_IGNORE = Symbol.for('node-ignore'); +} +const KEY_IGNORE = TMP_KEY_IGNORE; + +const define = (object, key, value) => + Object.defineProperty(object, key, {value}); + +const REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g; + +const RETURN_FALSE = () => false; + +// Sanitize the range of a regular expression +// The cases are complicated, see test cases for details +const sanitizeRange = range => range.replace( + REGEX_REGEXP_RANGE, + (match, from, to) => from.charCodeAt(0) <= to.charCodeAt(0) + ? match + // Invalid range (out of order) which is ok for gitignore rules but + // fatal for JavaScript regular expression, so eliminate it. + : EMPTY +); + +// See fixtures #59 +const cleanRangeBackSlash = slashes => { + const {length} = slashes; + return slashes.slice(0, length - length % 2) +}; + +// > If the pattern ends with a slash, +// > it is removed for the purpose of the following description, +// > but it would only find a match with a directory. +// > In other words, foo/ will match a directory foo and paths underneath it, +// > but will not match a regular file or a symbolic link foo +// > (this is consistent with the way how pathspec works in general in Git). +// '`foo/`' will not match regular file '`foo`' or symbolic link '`foo`' +// -> ignore-rules will not deal with it, because it costs extra `fs.stat` call +// you could use option `mark: true` with `glob` + +// '`foo/`' should not continue with the '`..`' +const REPLACERS = [ + + // > Trailing spaces are ignored unless they are quoted with backslash ("\") + [ + // (a\ ) -> (a ) + // (a ) -> (a) + // (a \ ) -> (a ) + /\\?\s+$/, + match => match.indexOf('\\') === 0 + ? SPACE$1 + : EMPTY + ], + + // replace (\ ) with ' ' + [ + /\\\s/g, + () => SPACE$1 + ], + + // Escape metacharacters + // which is written down by users but means special for regular expressions. + + // > There are 12 characters with special meanings: + // > - the backslash \, + // > - the caret ^, + // > - the dollar sign $, + // > - the period or dot ., + // > - the vertical bar or pipe symbol |, + // > - the question mark ?, + // > - the asterisk or star *, + // > - the plus sign +, + // > - the opening parenthesis (, + // > - the closing parenthesis ), + // > - and the opening square bracket [, + // > - the opening curly brace {, + // > These special characters are often called "metacharacters". + [ + /[\\$.|*+(){^]/g, + match => `\\${match}` + ], + + [ + // > a question mark (?) matches a single character + /(?!\\)\?/g, + () => '[^/]' + ], + + // leading slash + [ + + // > A leading slash matches the beginning of the pathname. + // > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c". + // A leading slash matches the beginning of the pathname + /^\//, + () => '^' + ], + + // replace special metacharacter slash after the leading slash + [ + /\//g, + () => '\\/' + ], + + [ + // > A leading "**" followed by a slash means match in all directories. + // > For example, "**/foo" matches file or directory "foo" anywhere, + // > the same as pattern "foo". + // > "**/foo/bar" matches file or directory "bar" anywhere that is directly + // > under directory "foo". + // Notice that the '*'s have been replaced as '\\*' + /^\^*\\\*\\\*\\\//, + + // '**/foo' <-> 'foo' + () => '^(?:.*\\/)?' + ], + + // starting + [ + // there will be no leading '/' + // (which has been replaced by section "leading slash") + // If starts with '**', adding a '^' to the regular expression also works + /^(?=[^^])/, + function startingReplacer () { + // If has a slash `/` at the beginning or middle + return !/\/(?!$)/.test(this) + // > Prior to 2.22.1 + // > If the pattern does not contain a slash /, + // > Git treats it as a shell glob pattern + // Actually, if there is only a trailing slash, + // git also treats it as a shell glob pattern + + // After 2.22.1 (compatible but clearer) + // > If there is a separator at the beginning or middle (or both) + // > of the pattern, then the pattern is relative to the directory + // > level of the particular .gitignore file itself. + // > Otherwise the pattern may also match at any level below + // > the .gitignore level. + ? '(?:^|\\/)' + + // > Otherwise, Git treats the pattern as a shell glob suitable for + // > consumption by fnmatch(3) + : '^' + } + ], + + // two globstars + [ + // Use lookahead assertions so that we could match more than one `'/**'` + /\\\/\\\*\\\*(?=\\\/|$)/g, + + // Zero, one or several directories + // should not use '*', or it will be replaced by the next replacer + + // Check if it is not the last `'/**'` + (_, index, str) => index + 6 < str.length + + // case: /**/ + // > A slash followed by two consecutive asterisks then a slash matches + // > zero or more directories. + // > For example, "a/**/b" matches "a/b", "a/x/b", "a/x/y/b" and so on. + // '/**/' + ? '(?:\\/[^\\/]+)*' + + // case: /** + // > A trailing `"/**"` matches everything inside. + + // #21: everything inside but it should not include the current folder + : '\\/.+' + ], + + // normal intermediate wildcards + [ + // Never replace escaped '*' + // ignore rule '\*' will match the path '*' + + // 'abc.*/' -> go + // 'abc.*' -> skip this rule, + // coz trailing single wildcard will be handed by [trailing wildcard] + /(^|[^\\]+)(\\\*)+(?=.+)/g, + + // '*.js' matches '.js' + // '*.js' doesn't match 'abc' + (_, p1, p2) => { + // 1. + // > An asterisk "*" matches anything except a slash. + // 2. + // > Other consecutive asterisks are considered regular asterisks + // > and will match according to the previous rules. + const unescaped = p2.replace(/\\\*/g, '[^\\/]*'); + return p1 + unescaped + } + ], + + [ + // unescape, revert step 3 except for back slash + // For example, if a user escape a '\\*', + // after step 3, the result will be '\\\\\\*' + /\\\\\\(?=[$.|*+(){^])/g, + () => ESCAPE + ], + + [ + // '\\\\' -> '\\' + /\\\\/g, + () => ESCAPE + ], + + [ + // > The range notation, e.g. [a-zA-Z], + // > can be used to match one of the characters in a range. + + // `\` is escaped by step 3 + /(\\)?\[([^\]/]*?)(\\*)($|\])/g, + (match, leadEscape, range, endEscape, close) => leadEscape === ESCAPE + // '\\[bar]' -> '\\\\[bar\\]' + ? `\\[${range}${cleanRangeBackSlash(endEscape)}${close}` + : close === ']' + ? endEscape.length % 2 === 0 + // A normal case, and it is a range notation + // '[bar]' + // '[bar\\\\]' + ? `[${sanitizeRange(range)}${endEscape}]` + // Invalid range notaton + // '[bar\\]' -> '[bar\\\\]' + : '[]' + : '[]' + ], + + // ending + [ + // 'js' will not match 'js.' + // 'ab' will not match 'abc' + /(?:[^*])$/, + + // WTF! + // https://git-scm.com/docs/gitignore + // changes in [2.22.1](https://git-scm.com/docs/gitignore/2.22.1) + // which re-fixes #24, #38 + + // > If there is a separator at the end of the pattern then the pattern + // > will only match directories, otherwise the pattern can match both + // > files and directories. + + // 'js*' will not match 'a.js' + // 'js/' will not match 'a.js' + // 'js' will match 'a.js' and 'a.js/' + match => /\/$/.test(match) + // foo/ will not match 'foo' + ? `${match}$` + // foo matches 'foo' and 'foo/' + : `${match}(?=$|\\/$)` + ], + + // trailing wildcard + [ + /(\^|\\\/)?\\\*$/, + (_, p1) => { + const prefix = p1 + // '\^': + // '/*' does not match EMPTY + // '/*' does not match everything + + // '\\\/': + // 'abc/*' does not match 'abc/' + ? `${p1}[^/]+` + + // 'a*' matches 'a' + // 'a*' matches 'aa' + : '[^/]*'; + + return `${prefix}(?=$|\\/$)` + } + ], +]; + +// A simple cache, because an ignore rule only has only one certain meaning +const regexCache = Object.create(null); + +// @param {pattern} +const makeRegex = (pattern, ignoreCase) => { + let source = regexCache[pattern]; + + if (!source) { + source = REPLACERS.reduce( + (prev, current) => prev.replace(current[0], current[1].bind(pattern)), + pattern + ); + regexCache[pattern] = source; + } + + return ignoreCase + ? new RegExp(source, 'i') + : new RegExp(source) +}; + +const isString$3 = subject => typeof subject === 'string'; + +// > A blank line matches no files, so it can serve as a separator for readability. +const checkPattern = pattern => pattern + && isString$3(pattern) + && !REGEX_TEST_BLANK_LINE.test(pattern) + && !REGEX_INVALID_TRAILING_BACKSLASH.test(pattern) + + // > A line starting with # serves as a comment. + && pattern.indexOf('#') !== 0; + +const splitPattern = pattern => pattern.split(REGEX_SPLITALL_CRLF); + +class IgnoreRule { + constructor ( + origin, + pattern, + negative, + regex + ) { + this.origin = origin; + this.pattern = pattern; + this.negative = negative; + this.regex = regex; + } +} + +const createRule = (pattern, ignoreCase) => { + const origin = pattern; + let negative = false; + + // > An optional prefix "!" which negates the pattern; + if (pattern.indexOf('!') === 0) { + negative = true; + pattern = pattern.substr(1); + } + + pattern = pattern + // > Put a backslash ("\") in front of the first "!" for patterns that + // > begin with a literal "!", for example, `"\!important!.txt"`. + .replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, '!') + // > Put a backslash ("\") in front of the first hash for patterns that + // > begin with a hash. + .replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, '#'); + + const regex = makeRegex(pattern, ignoreCase); + + return new IgnoreRule( + origin, + pattern, + negative, + regex + ) +}; + +const throwError$4 = (message, Ctor) => { + throw new Ctor(message) +}; + +const checkPath = (path, originalPath, doThrow) => { + if (!isString$3(path)) { + return doThrow( + `path must be a string, but got \`${originalPath}\``, + TypeError + ) + } + + // We don't know if we should ignore EMPTY, so throw + if (!path) { + return doThrow(`path must not be empty`, TypeError) + } + + // Check if it is a relative path + if (checkPath.isNotRelative(path)) { + const r = '`path.relative()`d'; + return doThrow( + `path should be a ${r} string, but got "${originalPath}"`, + RangeError + ) + } + + return true +}; + +const isNotRelative = path => REGEX_TEST_INVALID_PATH.test(path); + +checkPath.isNotRelative = isNotRelative; +checkPath.convert = p => p; + +class Ignore { + constructor ({ + ignorecase = true, + ignoreCase = ignorecase, + allowRelativePaths = false + } = {}) { + define(this, KEY_IGNORE, true); + + this._rules = []; + this._ignoreCase = ignoreCase; + this._allowRelativePaths = allowRelativePaths; + this._initCache(); + } + + _initCache () { + this._ignoreCache = Object.create(null); + this._testCache = Object.create(null); + } + + _addPattern (pattern) { + // #32 + if (pattern && pattern[KEY_IGNORE]) { + this._rules = this._rules.concat(pattern._rules); + this._added = true; + return + } + + if (checkPattern(pattern)) { + const rule = createRule(pattern, this._ignoreCase); + this._added = true; + this._rules.push(rule); + } + } + + // @param {Array<string> | string | Ignore} pattern + add (pattern) { + this._added = false; + + makeArray( + isString$3(pattern) + ? splitPattern(pattern) + : pattern + ).forEach(this._addPattern, this); + + // Some rules have just added to the ignore, + // making the behavior changed. + if (this._added) { + this._initCache(); + } + + return this + } + + // legacy + addPattern (pattern) { + return this.add(pattern) + } + + // | ignored : unignored + // negative | 0:0 | 0:1 | 1:0 | 1:1 + // -------- | ------- | ------- | ------- | -------- + // 0 | TEST | TEST | SKIP | X + // 1 | TESTIF | SKIP | TEST | X + + // - SKIP: always skip + // - TEST: always test + // - TESTIF: only test if checkUnignored + // - X: that never happen + + // @param {boolean} whether should check if the path is unignored, + // setting `checkUnignored` to `false` could reduce additional + // path matching. + + // @returns {TestResult} true if a file is ignored + _testOne (path, checkUnignored) { + let ignored = false; + let unignored = false; + + this._rules.forEach(rule => { + const {negative} = rule; + if ( + unignored === negative && ignored !== unignored + || negative && !ignored && !unignored && !checkUnignored + ) { + return + } + + const matched = rule.regex.test(path); + + if (matched) { + ignored = !negative; + unignored = negative; + } + }); + + return { + ignored, + unignored + } + } + + // @returns {TestResult} + _test (originalPath, cache, checkUnignored, slices) { + const path = originalPath + // Supports nullable path + && checkPath.convert(originalPath); + + checkPath( + path, + originalPath, + this._allowRelativePaths + ? RETURN_FALSE + : throwError$4 + ); + + return this._t(path, cache, checkUnignored, slices) + } + + _t (path, cache, checkUnignored, slices) { + if (path in cache) { + return cache[path] + } + + if (!slices) { + // path/to/a.js + // ['path', 'to', 'a.js'] + slices = path.split(SLASH$1); + } + + slices.pop(); + + // If the path has no parent directory, just test it + if (!slices.length) { + return cache[path] = this._testOne(path, checkUnignored) + } + + const parent = this._t( + slices.join(SLASH$1) + SLASH$1, + cache, + checkUnignored, + slices + ); + + // If the path contains a parent directory, check the parent first + return cache[path] = parent.ignored + // > It is not possible to re-include a file if a parent directory of + // > that file is excluded. + ? parent + : this._testOne(path, checkUnignored) + } + + ignores (path) { + return this._test(path, this._ignoreCache, false).ignored + } + + createFilter () { + return path => !this.ignores(path) + } + + filter (paths) { + return makeArray(paths).filter(this.createFilter()) + } + + // @returns {TestResult} + test (path) { + return this._test(path, this._testCache, true) + } +} + +const factory = options => new Ignore(options); + +const isPathValid = path => + checkPath(path && checkPath.convert(path), path, RETURN_FALSE); + +factory.isPathValid = isPathValid; + +// Fixes typescript +factory.default = factory; + +var ignore = factory; + +// Windows +// -------------------------------------------------------------- +/* istanbul ignore if */ +if ( + // Detect `process` so that it can run in browsers. + typeof process !== 'undefined' + && ( + process.env && process.env.IGNORE_TEST_WIN32 + || process.platform === 'win32' + ) +) { + /* eslint no-control-regex: "off" */ + const makePosix = str => /^\\\\\?\\/.test(str) + || /["<>|\u0000-\u001F]+/u.test(str) + ? str + : str.replace(/\\/g, '/'); + + checkPath.convert = makePosix; + + // 'C:\\foo' <- 'C:\\foo' has been converted to 'C:/' + // 'd:\\foo' + const REGIX_IS_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i; + checkPath.isNotRelative = path => + REGIX_IS_WINDOWS_PATH_ABSOLUTE.test(path) + || isNotRelative(path); +} + +var ignore$1 = /*@__PURE__*/getDefaultExportFromCjs(ignore); + +/** + * Recursively grabs all files within a given directory + * (including subdirectories) + * @param folderToSearch path to directory + * @param ignoreGit boolean to indicate whether or not to ignore + * `.git` directory plus any files specified in `.gitignore` + * @returns array of file names + */ +function readdirRecursive(folderToSearch, ignoreGit = false) { + debug(`current readdirRecursive folder: ${folderToSearch}`); + let ignoreFilter; + if (ignoreGit) { + // Initialize ignore filter with `.git` directory + ignoreFilter = ignore$1.default().add(path$c.join(folderToSearch, '.git/')); + // If .gitignore file exists, load its contents into ignore filter + if (fs$i.existsSync(path$c.join(folderToSearch, '.gitignore'))) { + debug('.gitignore file found, adding to ignore filter'); + ignoreFilter.add(fs$i.readFileSync(path$c.join(folderToSearch, '.gitignore')).toString()); + } + } + const filesInFolder = fs$i.readdirSync(folderToSearch, { withFileTypes: true }).filter(item => { + if (!ignoreGit) + return true; + // Some logic to construct pathname the way that `ignore` package consumes it + // https://github.com/kaelzhang/node-ignore#2-filenames-and-dirnames + let fullPathName = path$c.join(folderToSearch, item.name); + if (item.isDirectory()) + fullPathName = `${fullPathName}/`; + return !ignoreFilter.ignores(fullPathName); + }); + const files = filesInFolder + .filter(fileHandle => fileHandle.isFile()) + .map(fileHandle => path$c.join(folderToSearch, fileHandle.name)); + const folders = filesInFolder.filter(fileHandle => fileHandle.isDirectory()); + const subFiles = [].concat(...folders.map(fileHandle => readdirRecursive(path$c.join(folderToSearch, fileHandle.name), ignoreGit))); + return [...files, ...subFiles]; +} + +var toString$2 = Object.prototype.toString; + +var kindOf = function kindOf(val) { + if (val === void 0) return 'undefined'; + if (val === null) return 'null'; + + var type = typeof val; + if (type === 'boolean') return 'boolean'; + if (type === 'string') return 'string'; + if (type === 'number') return 'number'; + if (type === 'symbol') return 'symbol'; + if (type === 'function') { + return isGeneratorFn(val) ? 'generatorfunction' : 'function'; + } + + if (isArray$l(val)) return 'array'; + if (isBuffer$7(val)) return 'buffer'; + if (isArguments$7(val)) return 'arguments'; + if (isDate(val)) return 'date'; + if (isError(val)) return 'error'; + if (isRegexp(val)) return 'regexp'; + + switch (ctorName(val)) { + case 'Symbol': return 'symbol'; + case 'Promise': return 'promise'; + + // Set, Map, WeakSet, WeakMap + case 'WeakMap': return 'weakmap'; + case 'WeakSet': return 'weakset'; + case 'Map': return 'map'; + case 'Set': return 'set'; + + // 8-bit typed arrays + case 'Int8Array': return 'int8array'; + case 'Uint8Array': return 'uint8array'; + case 'Uint8ClampedArray': return 'uint8clampedarray'; + + // 16-bit typed arrays + case 'Int16Array': return 'int16array'; + case 'Uint16Array': return 'uint16array'; + + // 32-bit typed arrays + case 'Int32Array': return 'int32array'; + case 'Uint32Array': return 'uint32array'; + case 'Float32Array': return 'float32array'; + case 'Float64Array': return 'float64array'; + } + + if (isGeneratorObj(val)) { + return 'generator'; + } + + // Non-plain objects + type = toString$2.call(val); + switch (type) { + case '[object Object]': return 'object'; + // iterators + case '[object Map Iterator]': return 'mapiterator'; + case '[object Set Iterator]': return 'setiterator'; + case '[object String Iterator]': return 'stringiterator'; + case '[object Array Iterator]': return 'arrayiterator'; + } + + // other + return type.slice(8, -1).toLowerCase().replace(/\s/g, ''); +}; + +function ctorName(val) { + return typeof val.constructor === 'function' ? val.constructor.name : null; +} + +function isArray$l(val) { + if (Array.isArray) return Array.isArray(val); + return val instanceof Array; +} + +function isError(val) { + return val instanceof Error || (typeof val.message === 'string' && val.constructor && typeof val.constructor.stackTraceLimit === 'number'); +} + +function isDate(val) { + if (val instanceof Date) return true; + return typeof val.toDateString === 'function' + && typeof val.getDate === 'function' + && typeof val.setDate === 'function'; +} + +function isRegexp(val) { + if (val instanceof RegExp) return true; + return typeof val.flags === 'string' + && typeof val.ignoreCase === 'boolean' + && typeof val.multiline === 'boolean' + && typeof val.global === 'boolean'; +} + +function isGeneratorFn(name, val) { + return ctorName(name) === 'GeneratorFunction'; +} + +function isGeneratorObj(val) { + return typeof val.throw === 'function' + && typeof val.return === 'function' + && typeof val.next === 'function'; +} + +function isArguments$7(val) { + try { + if (typeof val.length === 'number' && typeof val.callee === 'function') { + return true; + } + } catch (err) { + if (err.message.indexOf('callee') !== -1) { + return true; + } + } + return false; +} + +/** + * If you need to support Safari 5-7 (8-10 yr-old browser), + * take a look at https://github.com/feross/is-buffer + */ + +function isBuffer$7(val) { + if (val.constructor && typeof val.constructor.isBuffer === 'function') { + return val.constructor.isBuffer(val); + } + return false; +} + +/*! + * is-extendable <https://github.com/jonschlinkert/is-extendable> + * + * Copyright (c) 2015, Jon Schlinkert. + * Licensed under the MIT License. + */ + +var isExtendable = function isExtendable(val) { + return typeof val !== 'undefined' && val !== null + && (typeof val === 'object' || typeof val === 'function'); +}; + +var isObject$n = isExtendable; + +var extendShallow = function extend(o/*, objects*/) { + if (!isObject$n(o)) { o = {}; } + + var len = arguments.length; + for (var i = 1; i < len; i++) { + var obj = arguments[i]; + + if (isObject$n(obj)) { + assign$1(o, obj); + } + } + return o; +}; + +function assign$1(a, b) { + for (var key in b) { + if (hasOwn(b, key)) { + a[key] = b[key]; + } + } +} + +/** + * Returns true if the given `key` is an own property of `obj`. + */ + +function hasOwn(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} + +var typeOf$2 = kindOf; +var extend$4 = extendShallow; + +/** + * Parse sections in `input` with the given `options`. + * + * ```js + * var sections = require('{%= name %}'); + * var result = sections(input, options); + * // { content: 'Content before sections', sections: [] } + * ``` + * @param {String|Buffer|Object} `input` If input is an object, it's `content` property must be a string or buffer. + * @param {Object} options + * @return {Object} Returns an object with a `content` string and an array of `sections` objects. + * @api public + */ + +var sectionMatter = function(input, options) { + if (typeof options === 'function') { + options = { parse: options }; + } + + var file = toObject(input); + var defaults = {section_delimiter: '---', parse: identity$6}; + var opts = extend$4({}, defaults, options); + var delim = opts.section_delimiter; + var lines = file.content.split(/\r?\n/); + var sections = null; + var section = createSection(); + var content = []; + var stack = []; + + function initSections(val) { + file.content = val; + sections = []; + content = []; + } + + function closeSection(val) { + if (stack.length) { + section.key = getKey$1(stack[0], delim); + section.content = val; + opts.parse(section, sections); + sections.push(section); + section = createSection(); + content = []; + stack = []; + } + } + + for (var i = 0; i < lines.length; i++) { + var line = lines[i]; + var len = stack.length; + var ln = line.trim(); + + if (isDelimiter(ln, delim)) { + if (ln.length === 3 && i !== 0) { + if (len === 0 || len === 2) { + content.push(line); + continue; + } + stack.push(ln); + section.data = content.join('\n'); + content = []; + continue; + } + + if (sections === null) { + initSections(content.join('\n')); + } + + if (len === 2) { + closeSection(content.join('\n')); + } + + stack.push(ln); + continue; + } + + content.push(line); + } + + if (sections === null) { + initSections(content.join('\n')); + } else { + closeSection(content.join('\n')); + } + + file.sections = sections; + return file; +}; + +function isDelimiter(line, delim) { + if (line.slice(0, delim.length) !== delim) { + return false; + } + if (line.charAt(delim.length + 1) === delim.slice(-1)) { + return false; + } + return true; +} + +function toObject(input) { + if (typeOf$2(input) !== 'object') { + input = { content: input }; + } + + if (typeof input.content !== 'string' && !isBuffer$6(input.content)) { + throw new TypeError('expected a buffer or string'); + } + + input.content = input.content.toString(); + input.sections = []; + return input; +} + +function getKey$1(val, delim) { + return val ? val.slice(delim.length).trim() : ''; +} + +function createSection() { + return { key: '', data: '', content: '' }; +} + +function identity$6(val) { + return val; +} + +function isBuffer$6(val) { + if (val && val.constructor && typeof val.constructor.isBuffer === 'function') { + return val.constructor.isBuffer(val); + } + return false; +} + +var engines$2 = {exports: {}}; + +var jsYaml$3 = {}; + +var loader$4 = {}; + +var common$h = {}; + +function isNothing$2(subject) { + return (typeof subject === 'undefined') || (subject === null); +} + + +function isObject$m(subject) { + return (typeof subject === 'object') && (subject !== null); +} + + +function toArray$4(sequence) { + if (Array.isArray(sequence)) return sequence; + else if (isNothing$2(sequence)) return []; + + return [ sequence ]; +} + + +function extend$3(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$3(string, count) { + var result = '', cycle; + + for (cycle = 0; cycle < count; cycle += 1) { + result += string; + } + + return result; +} + + +function isNegativeZero$2(number) { + return (number === 0) && (Number.NEGATIVE_INFINITY === 1 / number); +} + + +common$h.isNothing = isNothing$2; +common$h.isObject = isObject$m; +common$h.toArray = toArray$4; +common$h.repeat = repeat$3; +common$h.isNegativeZero = isNegativeZero$2; +common$h.extend = extend$3; + +function YAMLException$a(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$a.prototype = Object.create(Error.prototype); +YAMLException$a.prototype.constructor = YAMLException$a; + + +YAMLException$a.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$2 = YAMLException$a; + +var common$g = common$h; + + +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$g.repeat(' ', indent) + head + snippet + tail + '\n' + + common$g.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$9 = exception$2; + +var TYPE_CONSTRUCTOR_OPTIONS$2 = [ + 'kind', + 'resolve', + 'construct', + 'instanceOf', + 'predicate', + 'represent', + 'defaultStyle', + 'styleAliases' +]; + +var YAML_NODE_KINDS$2 = [ + 'scalar', + 'sequence', + 'mapping' +]; + +function compileStyleAliases$2(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$y(tag, options) { + options = options || {}; + + Object.keys(options).forEach(function (name) { + if (TYPE_CONSTRUCTOR_OPTIONS$2.indexOf(name) === -1) { + throw new YAMLException$9('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$2(options['styleAliases'] || null); + + if (YAML_NODE_KINDS$2.indexOf(this.kind) === -1) { + throw new YAMLException$9('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.'); + } +} + +var type$g = Type$y; + +/*eslint-disable max-len*/ + +var common$f = common$h; +var YAMLException$8 = exception$2; +var Type$x = type$g; + + +function compileList$2(schema, name, result) { + var exclude = []; + + schema.include.forEach(function (includedSchema) { + result = compileList$2(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$2(/* 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$b(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$8('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.'); + } + }); + + this.compiledImplicit = compileList$2(this, 'implicit', []); + this.compiledExplicit = compileList$2(this, 'explicit', []); + this.compiledTypeMap = compileMap$2(this.compiledImplicit, this.compiledExplicit); +} + + +Schema$b.DEFAULT = null; + + +Schema$b.create = function createSchema() { + var schemas, types; + + switch (arguments.length) { + case 1: + schemas = Schema$b.DEFAULT; + types = arguments[0]; + break; + + case 2: + schemas = arguments[0]; + types = arguments[1]; + break; + + default: + throw new YAMLException$8('Wrong number of arguments for Schema.create function'); + } + + schemas = common$f.toArray(schemas); + types = common$f.toArray(types); + + if (!schemas.every(function (schema) { return schema instanceof Schema$b; })) { + throw new YAMLException$8('Specified list of super schemas (or a single Schema object) contains a non-Schema object.'); + } + + if (!types.every(function (type) { return type instanceof Type$x; })) { + throw new YAMLException$8('Specified list of YAML types (or a single Type object) contains a non-Type object.'); + } + + return new Schema$b({ + include: schemas, + explicit: types + }); +}; + + +var schema$3 = Schema$b; + +var Type$w = type$g; + +var str$2 = new Type$w('tag:yaml.org,2002:str', { + kind: 'scalar', + construct: function (data) { return data !== null ? data : ''; } +}); + +var Type$v = type$g; + +var seq$3 = new Type$v('tag:yaml.org,2002:seq', { + kind: 'sequence', + construct: function (data) { return data !== null ? data : []; } +}); + +var Type$u = type$g; + +var map$5 = new Type$u('tag:yaml.org,2002:map', { + kind: 'mapping', + construct: function (data) { return data !== null ? data : {}; } +}); + +var Schema$a = schema$3; + + +var failsafe$3 = new Schema$a({ + explicit: [ + str$2, + seq$3, + map$5 + ] +}); + +var Type$t = type$g; + +function resolveYamlNull$2(data) { + if (data === null) return true; + + var max = data.length; + + return (max === 1 && data === '~') || + (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL')); +} + +function constructYamlNull$2() { + return null; +} + +function isNull$4(object) { + return object === null; +} + +var _null$2 = new Type$t('tag:yaml.org,2002:null', { + kind: 'scalar', + resolve: resolveYamlNull$2, + construct: constructYamlNull$2, + predicate: isNull$4, + represent: { + canonical: function () { return '~'; }, + lowercase: function () { return 'null'; }, + uppercase: function () { return 'NULL'; }, + camelcase: function () { return 'Null'; } + }, + defaultStyle: 'lowercase' +}); + +var Type$s = type$g; + +function resolveYamlBoolean$2(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$2(data) { + return data === 'true' || + data === 'True' || + data === 'TRUE'; +} + +function isBoolean$4(object) { + return Object.prototype.toString.call(object) === '[object Boolean]'; +} + +var bool$2 = new Type$s('tag:yaml.org,2002:bool', { + kind: 'scalar', + resolve: resolveYamlBoolean$2, + construct: constructYamlBoolean$2, + predicate: isBoolean$4, + 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$e = common$h; +var Type$r = type$g; + +function isHexCode$2(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) || + ((0x41/* A */ <= c) && (c <= 0x46/* F */)) || + ((0x61/* a */ <= c) && (c <= 0x66/* f */)); +} + +function isOctCode$2(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */)); +} + +function isDecCode$2(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)); +} + +function resolveYamlInteger$2(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$2(data.charCodeAt(index))) return false; + hasDigits = true; + } + return hasDigits && ch !== '_'; + } + + // base 8 + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (!isOctCode$2(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$2(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$2(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$4(object) { + return (Object.prototype.toString.call(object)) === '[object Number]' && + (object % 1 === 0 && !common$e.isNegativeZero(object)); +} + +var int$2 = new Type$r('tag:yaml.org,2002:int', { + kind: 'scalar', + resolve: resolveYamlInteger$2, + construct: constructYamlInteger$2, + predicate: isInteger$4, + 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$d = common$h; +var Type$q = type$g; + +var YAML_FLOAT_PATTERN$2 = 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$2(data) { + if (data === null) return false; + + if (!YAML_FLOAT_PATTERN$2.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$2(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$2 = /^[-+]?[0-9]+e/; + +function representYamlFloat$2(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$d.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$2.test(res) ? res.replace('e', '.e') : res; +} + +function isFloat$2(object) { + return (Object.prototype.toString.call(object) === '[object Number]') && + (object % 1 !== 0 || common$d.isNegativeZero(object)); +} + +var float$2 = new Type$q('tag:yaml.org,2002:float', { + kind: 'scalar', + resolve: resolveYamlFloat$2, + construct: constructYamlFloat$2, + predicate: isFloat$2, + represent: representYamlFloat$2, + defaultStyle: 'lowercase' +}); + +var Schema$9 = schema$3; + + +var json$5 = new Schema$9({ + include: [ + failsafe$3 + ], + implicit: [ + _null$2, + bool$2, + int$2, + float$2 + ] +}); + +var Schema$8 = schema$3; + + +var core$b = new Schema$8({ + include: [ + json$5 + ] +}); + +var Type$p = type$g; + +var YAML_DATE_REGEXP$2 = 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$2 = 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$2(data) { + if (data === null) return false; + if (YAML_DATE_REGEXP$2.exec(data) !== null) return true; + if (YAML_TIMESTAMP_REGEXP$2.exec(data) !== null) return true; + return false; +} + +function constructYamlTimestamp$2(data) { + var match, year, month, day, hour, minute, second, fraction = 0, + delta = null, tz_hour, tz_minute, date; + + match = YAML_DATE_REGEXP$2.exec(data); + if (match === null) match = YAML_TIMESTAMP_REGEXP$2.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$2(object /*, style*/) { + return object.toISOString(); +} + +var timestamp$3 = new Type$p('tag:yaml.org,2002:timestamp', { + kind: 'scalar', + resolve: resolveYamlTimestamp$2, + construct: constructYamlTimestamp$2, + instanceOf: Date, + represent: representYamlTimestamp$2 +}); + +var Type$o = type$g; + +function resolveYamlMerge$2(data) { + return data === '<<' || data === null; +} + +var merge$3 = new Type$o('tag:yaml.org,2002:merge', { + kind: 'scalar', + resolve: resolveYamlMerge$2 +}); + +/*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$n = type$g; + + +// [ 64, 65, 66 ] -> [ padding, CR, LF ] +var BASE64_MAP$2 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r'; + + +function resolveYamlBinary$2(data) { + if (data === null) return false; + + var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP$2; + + // 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$2(data) { + var idx, tailbits, + input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to simplify scan + max = input.length, + map = BASE64_MAP$2, + 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$2(object /*, style*/) { + var result = '', bits = 0, idx, tail, + max = object.length, + map = BASE64_MAP$2; + + // 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$2(object) { + return NodeBuffer && NodeBuffer.isBuffer(object); +} + +var binary$5 = new Type$n('tag:yaml.org,2002:binary', { + kind: 'scalar', + resolve: resolveYamlBinary$2, + construct: constructYamlBinary$2, + predicate: isBinary$2, + represent: representYamlBinary$2 +}); + +var Type$m = type$g; + +var _hasOwnProperty$8 = Object.prototype.hasOwnProperty; +var _toString$6 = Object.prototype.toString; + +function resolveYamlOmap$2(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$6.call(pair) !== '[object Object]') return false; + + for (pairKey in pair) { + if (_hasOwnProperty$8.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$2(data) { + return data !== null ? data : []; +} + +var omap$3 = new Type$m('tag:yaml.org,2002:omap', { + kind: 'sequence', + resolve: resolveYamlOmap$2, + construct: constructYamlOmap$2 +}); + +var Type$l = type$g; + +var _toString$5 = Object.prototype.toString; + +function resolveYamlPairs$2(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$5.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$2(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$3 = new Type$l('tag:yaml.org,2002:pairs', { + kind: 'sequence', + resolve: resolveYamlPairs$2, + construct: constructYamlPairs$2 +}); + +var Type$k = type$g; + +var _hasOwnProperty$7 = Object.prototype.hasOwnProperty; + +function resolveYamlSet$2(data) { + if (data === null) return true; + + var key, object = data; + + for (key in object) { + if (_hasOwnProperty$7.call(object, key)) { + if (object[key] !== null) return false; + } + } + + return true; +} + +function constructYamlSet$2(data) { + return data !== null ? data : {}; +} + +var set$4 = new Type$k('tag:yaml.org,2002:set', { + kind: 'mapping', + resolve: resolveYamlSet$2, + construct: constructYamlSet$2 +}); + +var Schema$7 = schema$3; + + +var default_safe = new Schema$7({ + include: [ + core$b + ], + implicit: [ + timestamp$3, + merge$3 + ], + explicit: [ + binary$5, + omap$3, + pairs$3, + set$4 + ] +}); + +var Type$j = type$g; + +function resolveJavascriptUndefined() { + return true; +} + +function constructJavascriptUndefined() { + /*eslint-disable no-undefined*/ + return undefined; +} + +function representJavascriptUndefined() { + return ''; +} + +function isUndefined$2(object) { + return typeof object === 'undefined'; +} + +var _undefined$1 = new Type$j('tag:yaml.org,2002:js/undefined', { + kind: 'scalar', + resolve: resolveJavascriptUndefined, + construct: constructJavascriptUndefined, + predicate: isUndefined$2, + represent: representJavascriptUndefined +}); + +var Type$i = type$g; + +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$i('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$h = type$g; + +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$c(object) { + return Object.prototype.toString.call(object) === '[object Function]'; +} + +var _function = new Type$h('tag:yaml.org,2002:js/function', { + kind: 'scalar', + resolve: resolveJavascriptFunction, + construct: constructJavascriptFunction, + predicate: isFunction$c, + represent: representJavascriptFunction +}); + +var Schema$6 = schema$3; + + +var default_full = Schema$6.DEFAULT = new Schema$6({ + include: [ + default_safe + ], + explicit: [ + _undefined$1, + regexp, + _function + ] +}); + +/*eslint-disable max-len,no-use-before-define*/ + +var common$c = common$h; +var YAMLException$7 = exception$2; +var Mark = mark; +var DEFAULT_SAFE_SCHEMA$1 = default_safe; +var DEFAULT_FULL_SCHEMA$1 = default_full; + + +var _hasOwnProperty$6 = Object.prototype.hasOwnProperty; + + +var CONTEXT_FLOW_IN$2 = 1; +var CONTEXT_FLOW_OUT$2 = 2; +var CONTEXT_BLOCK_IN$2 = 3; +var CONTEXT_BLOCK_OUT$2 = 4; + + +var CHOMPING_CLIP$2 = 1; +var CHOMPING_STRIP$2 = 2; +var CHOMPING_KEEP$2 = 3; + + +var PATTERN_NON_PRINTABLE$2 = /[\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$2 = /[\x85\u2028\u2029]/; +var PATTERN_FLOW_INDICATORS$2 = /[,\[\]\{\}]/; +var PATTERN_TAG_HANDLE$2 = /^(?:!|!!|![a-z\-]+!)$/i; +var PATTERN_TAG_URI$2 = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i; + + +function _class$2(obj) { return Object.prototype.toString.call(obj); } + +function is_EOL$2(c) { + return (c === 0x0A/* LF */) || (c === 0x0D/* CR */); +} + +function is_WHITE_SPACE$2(c) { + return (c === 0x09/* Tab */) || (c === 0x20/* Space */); +} + +function is_WS_OR_EOL$2(c) { + return (c === 0x09/* Tab */) || + (c === 0x20/* Space */) || + (c === 0x0A/* LF */) || + (c === 0x0D/* CR */); +} + +function is_FLOW_INDICATOR$2(c) { + return c === 0x2C/* , */ || + c === 0x5B/* [ */ || + c === 0x5D/* ] */ || + c === 0x7B/* { */ || + c === 0x7D/* } */; +} + +function fromHexCode$2(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$2(c) { + if (c === 0x78/* x */) { return 2; } + if (c === 0x75/* u */) { return 4; } + if (c === 0x55/* U */) { return 8; } + return 0; +} + +function fromDecimalCode$2(c) { + if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { + return c - 0x30; + } + + return -1; +} + +function simpleEscapeSequence$2(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$2(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$2 = new Array(256); // integer, for fast access +var simpleEscapeMap$2 = new Array(256); +for (var i$3 = 0; i$3 < 256; i$3++) { + simpleEscapeCheck$2[i$3] = simpleEscapeSequence$2(i$3) ? 1 : 0; + simpleEscapeMap$2[i$3] = simpleEscapeSequence$2(i$3); +} + + +function State$4(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$2(state, message) { + return new YAMLException$7( + message, + new Mark(state.filename, state.input, state.position, state.line, (state.position - state.lineStart))); +} + +function throwError$3(state, message) { + throw generateError$2(state, message); +} + +function throwWarning$2(state, message) { + if (state.onWarning) { + state.onWarning.call(null, generateError$2(state, message)); + } +} + + +var directiveHandlers$2 = { + + YAML: function handleYamlDirective(state, name, args) { + + var match, major, minor; + + if (state.version !== null) { + throwError$3(state, 'duplication of %YAML directive'); + } + + if (args.length !== 1) { + throwError$3(state, 'YAML directive accepts exactly one argument'); + } + + match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]); + + if (match === null) { + throwError$3(state, 'ill-formed argument of the YAML directive'); + } + + major = parseInt(match[1], 10); + minor = parseInt(match[2], 10); + + if (major !== 1) { + throwError$3(state, 'unacceptable YAML version of the document'); + } + + state.version = args[0]; + state.checkLineBreaks = (minor < 2); + + if (minor !== 1 && minor !== 2) { + throwWarning$2(state, 'unsupported YAML version of the document'); + } + }, + + TAG: function handleTagDirective(state, name, args) { + + var handle, prefix; + + if (args.length !== 2) { + throwError$3(state, 'TAG directive accepts exactly two arguments'); + } + + handle = args[0]; + prefix = args[1]; + + if (!PATTERN_TAG_HANDLE$2.test(handle)) { + throwError$3(state, 'ill-formed tag handle (first argument) of the TAG directive'); + } + + if (_hasOwnProperty$6.call(state.tagMap, handle)) { + throwError$3(state, 'there is a previously declared suffix for "' + handle + '" tag handle'); + } + + if (!PATTERN_TAG_URI$2.test(prefix)) { + throwError$3(state, 'ill-formed tag prefix (second argument) of the TAG directive'); + } + + state.tagMap[handle] = prefix; + } +}; + + +function captureSegment$2(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$3(state, 'expected valid JSON character'); + } + } + } else if (PATTERN_NON_PRINTABLE$2.test(_result)) { + throwError$3(state, 'the stream contains non-printable characters'); + } + + state.result += _result; + } +} + +function mergeMappings$2(state, destination, source, overridableKeys) { + var sourceKeys, key, index, quantity; + + if (!common$c.isObject(source)) { + throwError$3(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$6.call(destination, key)) { + destination[key] = source[key]; + overridableKeys[key] = true; + } + } +} + +function storeMappingPair$2(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$3(state, 'nested arrays are not supported inside keys'); + } + + if (typeof keyNode === 'object' && _class$2(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$2(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$2(state, _result, valueNode[index], overridableKeys); + } + } else { + mergeMappings$2(state, _result, valueNode, overridableKeys); + } + } else { + if (!state.json && + !_hasOwnProperty$6.call(overridableKeys, keyNode) && + _hasOwnProperty$6.call(_result, keyNode)) { + state.line = startLine || state.line; + state.position = startPos || state.position; + throwError$3(state, 'duplicated mapping key'); + } + _result[keyNode] = valueNode; + delete overridableKeys[keyNode]; + } + + return _result; +} + +function readLineBreak$2(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$3(state, 'a line break is expected'); + } + + state.line += 1; + state.lineStart = state.position; +} + +function skipSeparationSpace$2(state, allowComments, checkIndent) { + var lineBreaks = 0, + ch = state.input.charCodeAt(state.position); + + while (ch !== 0) { + while (is_WHITE_SPACE$2(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$2(ch)) { + readLineBreak$2(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$2(state, 'deficient indentation'); + } + + return lineBreaks; +} + +function testDocumentSeparator$2(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$2(ch)) { + return true; + } + } + + return false; +} + +function writeFoldedLines$2(state, count) { + if (count === 1) { + state.result += ' '; + } else if (count > 1) { + state.result += common$c.repeat('\n', count - 1); + } +} + + +function readPlainScalar$2(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$2(ch) || + is_FLOW_INDICATOR$2(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$2(following) || + withinFlowCollection && is_FLOW_INDICATOR$2(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$2(following) || + withinFlowCollection && is_FLOW_INDICATOR$2(following)) { + break; + } + + } else if (ch === 0x23/* # */) { + preceding = state.input.charCodeAt(state.position - 1); + + if (is_WS_OR_EOL$2(preceding)) { + break; + } + + } else if ((state.position === state.lineStart && testDocumentSeparator$2(state)) || + withinFlowCollection && is_FLOW_INDICATOR$2(ch)) { + break; + + } else if (is_EOL$2(ch)) { + _line = state.line; + _lineStart = state.lineStart; + _lineIndent = state.lineIndent; + skipSeparationSpace$2(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$2(state, captureStart, captureEnd, false); + writeFoldedLines$2(state, state.line - _line); + captureStart = captureEnd = state.position; + hasPendingContent = false; + } + + if (!is_WHITE_SPACE$2(ch)) { + captureEnd = state.position + 1; + } + + ch = state.input.charCodeAt(++state.position); + } + + captureSegment$2(state, captureStart, captureEnd, false); + + if (state.result) { + return true; + } + + state.kind = _kind; + state.result = _result; + return false; +} + +function readSingleQuotedScalar$2(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$2(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$2(ch)) { + captureSegment$2(state, captureStart, captureEnd, true); + writeFoldedLines$2(state, skipSeparationSpace$2(state, false, nodeIndent)); + captureStart = captureEnd = state.position; + + } else if (state.position === state.lineStart && testDocumentSeparator$2(state)) { + throwError$3(state, 'unexpected end of the document within a single quoted scalar'); + + } else { + state.position++; + captureEnd = state.position; + } + } + + throwError$3(state, 'unexpected end of the stream within a single quoted scalar'); +} + +function readDoubleQuotedScalar$2(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$2(state, captureStart, state.position, true); + state.position++; + return true; + + } else if (ch === 0x5C/* \ */) { + captureSegment$2(state, captureStart, state.position, true); + ch = state.input.charCodeAt(++state.position); + + if (is_EOL$2(ch)) { + skipSeparationSpace$2(state, false, nodeIndent); + + // TODO: rework to inline fn with no type cast? + } else if (ch < 256 && simpleEscapeCheck$2[ch]) { + state.result += simpleEscapeMap$2[ch]; + state.position++; + + } else if ((tmp = escapedHexLen$2(ch)) > 0) { + hexLength = tmp; + hexResult = 0; + + for (; hexLength > 0; hexLength--) { + ch = state.input.charCodeAt(++state.position); + + if ((tmp = fromHexCode$2(ch)) >= 0) { + hexResult = (hexResult << 4) + tmp; + + } else { + throwError$3(state, 'expected hexadecimal character'); + } + } + + state.result += charFromCodepoint$2(hexResult); + + state.position++; + + } else { + throwError$3(state, 'unknown escape sequence'); + } + + captureStart = captureEnd = state.position; + + } else if (is_EOL$2(ch)) { + captureSegment$2(state, captureStart, captureEnd, true); + writeFoldedLines$2(state, skipSeparationSpace$2(state, false, nodeIndent)); + captureStart = captureEnd = state.position; + + } else if (state.position === state.lineStart && testDocumentSeparator$2(state)) { + throwError$3(state, 'unexpected end of the document within a double quoted scalar'); + + } else { + state.position++; + captureEnd = state.position; + } + } + + throwError$3(state, 'unexpected end of the stream within a double quoted scalar'); +} + +function readFlowCollection$2(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$2(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$3(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$2(following)) { + isPair = isExplicitPair = true; + state.position++; + skipSeparationSpace$2(state, true, nodeIndent); + } + } + + _line = state.line; + composeNode$2(state, nodeIndent, CONTEXT_FLOW_IN$2, false, true); + keyTag = state.tag; + keyNode = state.result; + skipSeparationSpace$2(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$2(state, true, nodeIndent); + composeNode$2(state, nodeIndent, CONTEXT_FLOW_IN$2, false, true); + valueNode = state.result; + } + + if (isMapping) { + storeMappingPair$2(state, _result, overridableKeys, keyTag, keyNode, valueNode); + } else if (isPair) { + _result.push(storeMappingPair$2(state, null, overridableKeys, keyTag, keyNode, valueNode)); + } else { + _result.push(keyNode); + } + + skipSeparationSpace$2(state, true, nodeIndent); + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x2C/* , */) { + readNext = true; + ch = state.input.charCodeAt(++state.position); + } else { + readNext = false; + } + } + + throwError$3(state, 'unexpected end of the stream within a flow collection'); +} + +function readBlockScalar$2(state, nodeIndent) { + var captureStart, + folding, + chomping = CHOMPING_CLIP$2, + 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$2 === chomping) { + chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP$2 : CHOMPING_STRIP$2; + } else { + throwError$3(state, 'repeat of a chomping mode identifier'); + } + + } else if ((tmp = fromDecimalCode$2(ch)) >= 0) { + if (tmp === 0) { + throwError$3(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$3(state, 'repeat of an indentation width identifier'); + } + + } else { + break; + } + } + + if (is_WHITE_SPACE$2(ch)) { + do { ch = state.input.charCodeAt(++state.position); } + while (is_WHITE_SPACE$2(ch)); + + if (ch === 0x23/* # */) { + do { ch = state.input.charCodeAt(++state.position); } + while (!is_EOL$2(ch) && (ch !== 0)); + } + } + + while (ch !== 0) { + readLineBreak$2(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$2(ch)) { + emptyLines++; + continue; + } + + // End of the scalar. + if (state.lineIndent < textIndent) { + + // Perform the chomping. + if (chomping === CHOMPING_KEEP$2) { + state.result += common$c.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + } else if (chomping === CHOMPING_CLIP$2) { + 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$2(ch)) { + atMoreIndented = true; + // except for the first content line (cf. Example 8.1) + state.result += common$c.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + + // End of more-indented block. + } else if (atMoreIndented) { + atMoreIndented = false; + state.result += common$c.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$c.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$c.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + } + + didReadContent = true; + detectedIndent = true; + emptyLines = 0; + captureStart = state.position; + + while (!is_EOL$2(ch) && (ch !== 0)) { + ch = state.input.charCodeAt(++state.position); + } + + captureSegment$2(state, captureStart, state.position, false); + } + + return true; +} + +function readBlockSequence$2(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$2(following)) { + break; + } + + detected = true; + state.position++; + + if (skipSeparationSpace$2(state, true, -1)) { + if (state.lineIndent <= nodeIndent) { + _result.push(null); + ch = state.input.charCodeAt(state.position); + continue; + } + } + + _line = state.line; + composeNode$2(state, nodeIndent, CONTEXT_BLOCK_IN$2, false, true); + _result.push(state.result); + skipSeparationSpace$2(state, true, -1); + + ch = state.input.charCodeAt(state.position); + + if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { + throwError$3(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$2(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$2(following)) { + + if (ch === 0x3F/* ? */) { + if (atExplicitKey) { + storeMappingPair$2(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$3(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$2(state, flowIndent, CONTEXT_FLOW_OUT$2, false, true)) { + + if (state.line === _line) { + ch = state.input.charCodeAt(state.position); + + while (is_WHITE_SPACE$2(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (ch === 0x3A/* : */) { + ch = state.input.charCodeAt(++state.position); + + if (!is_WS_OR_EOL$2(ch)) { + throwError$3(state, 'a whitespace character is expected after the key-value separator within a block mapping'); + } + + if (atExplicitKey) { + storeMappingPair$2(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$3(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$3(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$2(state, nodeIndent, CONTEXT_BLOCK_OUT$2, true, allowCompact)) { + if (atExplicitKey) { + keyNode = state.result; + } else { + valueNode = state.result; + } + } + + if (!atExplicitKey) { + storeMappingPair$2(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _pos); + keyTag = keyNode = valueNode = null; + } + + skipSeparationSpace$2(state, true, -1); + ch = state.input.charCodeAt(state.position); + } + + if (state.lineIndent > nodeIndent && (ch !== 0)) { + throwError$3(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$2(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$2(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$3(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$3(state, 'unexpected end of the stream within a verbatim tag'); + } + } else { + while (ch !== 0 && !is_WS_OR_EOL$2(ch)) { + + if (ch === 0x21/* ! */) { + if (!isNamed) { + tagHandle = state.input.slice(_position - 1, state.position + 1); + + if (!PATTERN_TAG_HANDLE$2.test(tagHandle)) { + throwError$3(state, 'named tag handle cannot contain such characters'); + } + + isNamed = true; + _position = state.position + 1; + } else { + throwError$3(state, 'tag suffix cannot contain exclamation marks'); + } + } + + ch = state.input.charCodeAt(++state.position); + } + + tagName = state.input.slice(_position, state.position); + + if (PATTERN_FLOW_INDICATORS$2.test(tagName)) { + throwError$3(state, 'tag suffix cannot contain flow indicator characters'); + } + } + + if (tagName && !PATTERN_TAG_URI$2.test(tagName)) { + throwError$3(state, 'tag name cannot contain such characters: ' + tagName); + } + + if (isVerbatim) { + state.tag = tagName; + + } else if (_hasOwnProperty$6.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$3(state, 'undeclared tag handle "' + tagHandle + '"'); + } + + return true; +} + +function readAnchorProperty$2(state) { + var _position, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x26/* & */) return false; + + if (state.anchor !== null) { + throwError$3(state, 'duplication of an anchor property'); + } + + ch = state.input.charCodeAt(++state.position); + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL$2(ch) && !is_FLOW_INDICATOR$2(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (state.position === _position) { + throwError$3(state, 'name of an anchor node must contain at least one character'); + } + + state.anchor = state.input.slice(_position, state.position); + return true; +} + +function readAlias$2(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$2(ch) && !is_FLOW_INDICATOR$2(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (state.position === _position) { + throwError$3(state, 'name of an alias node must contain at least one character'); + } + + alias = state.input.slice(_position, state.position); + + if (!_hasOwnProperty$6.call(state.anchorMap, alias)) { + throwError$3(state, 'unidentified alias "' + alias + '"'); + } + + state.result = state.anchorMap[alias]; + skipSeparationSpace$2(state, true, -1); + return true; +} + +function composeNode$2(state, parentIndent, nodeContext, allowToSeek, allowCompact) { + var allowBlockStyles, + allowBlockScalars, + allowBlockCollections, + indentStatus = 1, // 1: this>parent, 0: this=parent, -1: this<parent + atNewLine = false, + hasContent = false, + typeIndex, + typeQuantity, + type, + flowIndent, + blockIndent; + + if (state.listener !== null) { + state.listener('open', state); + } + + state.tag = null; + state.anchor = null; + state.kind = null; + state.result = null; + + allowBlockStyles = allowBlockScalars = allowBlockCollections = + CONTEXT_BLOCK_OUT$2 === nodeContext || + CONTEXT_BLOCK_IN$2 === nodeContext; + + if (allowToSeek) { + if (skipSeparationSpace$2(state, true, -1)) { + atNewLine = true; + + if (state.lineIndent > parentIndent) { + indentStatus = 1; + } else if (state.lineIndent === parentIndent) { + indentStatus = 0; + } else if (state.lineIndent < parentIndent) { + indentStatus = -1; + } + } + } + + if (indentStatus === 1) { + while (readTagProperty$2(state) || readAnchorProperty$2(state)) { + if (skipSeparationSpace$2(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$2 === nodeContext) { + if (CONTEXT_FLOW_IN$2 === nodeContext || CONTEXT_FLOW_OUT$2 === nodeContext) { + flowIndent = parentIndent; + } else { + flowIndent = parentIndent + 1; + } + + blockIndent = state.position - state.lineStart; + + if (indentStatus === 1) { + if (allowBlockCollections && + (readBlockSequence$2(state, blockIndent) || + readBlockMapping$2(state, blockIndent, flowIndent)) || + readFlowCollection$2(state, flowIndent)) { + hasContent = true; + } else { + if ((allowBlockScalars && readBlockScalar$2(state, flowIndent)) || + readSingleQuotedScalar$2(state, flowIndent) || + readDoubleQuotedScalar$2(state, flowIndent)) { + hasContent = true; + + } else if (readAlias$2(state)) { + hasContent = true; + + if (state.tag !== null || state.anchor !== null) { + throwError$3(state, 'alias node should not have any properties'); + } + + } else if (readPlainScalar$2(state, flowIndent, CONTEXT_FLOW_IN$2 === 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$2(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$3(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$6.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$3(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$3(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$3(state, 'unknown tag !<' + state.tag + '>'); + } + } + + if (state.listener !== null) { + state.listener('close', state); + } + return state.tag !== null || state.anchor !== null || hasContent; +} + +function readDocument$2(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$2(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$2(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + directiveName = state.input.slice(_position, state.position); + directiveArgs = []; + + if (directiveName.length < 1) { + throwError$3(state, 'directive name must not be less than one character in length'); + } + + while (ch !== 0) { + while (is_WHITE_SPACE$2(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (ch === 0x23/* # */) { + do { ch = state.input.charCodeAt(++state.position); } + while (ch !== 0 && !is_EOL$2(ch)); + break; + } + + if (is_EOL$2(ch)) break; + + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL$2(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + directiveArgs.push(state.input.slice(_position, state.position)); + } + + if (ch !== 0) readLineBreak$2(state); + + if (_hasOwnProperty$6.call(directiveHandlers$2, directiveName)) { + directiveHandlers$2[directiveName](state, directiveName, directiveArgs); + } else { + throwWarning$2(state, 'unknown document directive "' + directiveName + '"'); + } + } + + skipSeparationSpace$2(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$2(state, true, -1); + + } else if (hasDirectives) { + throwError$3(state, 'directives end mark is expected'); + } + + composeNode$2(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT$2, false, true); + skipSeparationSpace$2(state, true, -1); + + if (state.checkLineBreaks && + PATTERN_NON_ASCII_LINE_BREAKS$2.test(state.input.slice(documentStart, state.position))) { + throwWarning$2(state, 'non-ASCII line breaks are interpreted as content'); + } + + state.documents.push(state.result); + + if (state.position === state.lineStart && testDocumentSeparator$2(state)) { + + if (state.input.charCodeAt(state.position) === 0x2E/* . */) { + state.position += 3; + skipSeparationSpace$2(state, true, -1); + } + return; + } + + if (state.position < (state.length - 1)) { + throwError$3(state, 'end of the stream or a document separator is expected'); + } else { + return; + } +} + + +function loadDocuments$2(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$4(input, options); + + var nullpos = input.indexOf('\0'); + + if (nullpos !== -1) { + state.position = nullpos; + throwError$3(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$2(state); + } + + return state.documents; +} + + +function loadAll$3(input, iterator, options) { + if (iterator !== null && typeof iterator === 'object' && typeof options === 'undefined') { + options = iterator; + iterator = null; + } + + var documents = loadDocuments$2(input, options); + + if (typeof iterator !== 'function') { + return documents; + } + + for (var index = 0, length = documents.length; index < length; index += 1) { + iterator(documents[index]); + } +} + + +function load$3(input, options) { + var documents = loadDocuments$2(input, options); + + if (documents.length === 0) { + /*eslint-disable no-undefined*/ + return undefined; + } else if (documents.length === 1) { + return documents[0]; + } + throw new YAMLException$7('expected a single document in the stream, but found more'); +} + + +function safeLoadAll$1(input, iterator, options) { + if (typeof iterator === 'object' && iterator !== null && typeof options === 'undefined') { + options = iterator; + iterator = null; + } + + return loadAll$3(input, iterator, common$c.extend({ schema: DEFAULT_SAFE_SCHEMA$1 }, options)); +} + + +function safeLoad$1(input, options) { + return load$3(input, common$c.extend({ schema: DEFAULT_SAFE_SCHEMA$1 }, options)); +} + + +loader$4.loadAll = loadAll$3; +loader$4.load = load$3; +loader$4.safeLoadAll = safeLoadAll$1; +loader$4.safeLoad = safeLoad$1; + +var dumper$4 = {}; + +/*eslint-disable no-use-before-define*/ + +var common$b = common$h; +var YAMLException$6 = exception$2; +var DEFAULT_FULL_SCHEMA = default_full; +var DEFAULT_SAFE_SCHEMA = default_safe; + +var _toString$4 = Object.prototype.toString; +var _hasOwnProperty$5 = Object.prototype.hasOwnProperty; + +var CHAR_TAB$2 = 0x09; /* Tab */ +var CHAR_LINE_FEED$2 = 0x0A; /* LF */ +var CHAR_CARRIAGE_RETURN$2 = 0x0D; /* CR */ +var CHAR_SPACE$2 = 0x20; /* Space */ +var CHAR_EXCLAMATION$2 = 0x21; /* ! */ +var CHAR_DOUBLE_QUOTE$2 = 0x22; /* " */ +var CHAR_SHARP$2 = 0x23; /* # */ +var CHAR_PERCENT$2 = 0x25; /* % */ +var CHAR_AMPERSAND$2 = 0x26; /* & */ +var CHAR_SINGLE_QUOTE$2 = 0x27; /* ' */ +var CHAR_ASTERISK$2 = 0x2A; /* * */ +var CHAR_COMMA$2 = 0x2C; /* , */ +var CHAR_MINUS$2 = 0x2D; /* - */ +var CHAR_COLON$2 = 0x3A; /* : */ +var CHAR_EQUALS$2 = 0x3D; /* = */ +var CHAR_GREATER_THAN$2 = 0x3E; /* > */ +var CHAR_QUESTION$2 = 0x3F; /* ? */ +var CHAR_COMMERCIAL_AT$2 = 0x40; /* @ */ +var CHAR_LEFT_SQUARE_BRACKET$2 = 0x5B; /* [ */ +var CHAR_RIGHT_SQUARE_BRACKET$2 = 0x5D; /* ] */ +var CHAR_GRAVE_ACCENT$2 = 0x60; /* ` */ +var CHAR_LEFT_CURLY_BRACKET$2 = 0x7B; /* { */ +var CHAR_VERTICAL_LINE$2 = 0x7C; /* | */ +var CHAR_RIGHT_CURLY_BRACKET$2 = 0x7D; /* } */ + +var ESCAPE_SEQUENCES$2 = {}; + +ESCAPE_SEQUENCES$2[0x00] = '\\0'; +ESCAPE_SEQUENCES$2[0x07] = '\\a'; +ESCAPE_SEQUENCES$2[0x08] = '\\b'; +ESCAPE_SEQUENCES$2[0x09] = '\\t'; +ESCAPE_SEQUENCES$2[0x0A] = '\\n'; +ESCAPE_SEQUENCES$2[0x0B] = '\\v'; +ESCAPE_SEQUENCES$2[0x0C] = '\\f'; +ESCAPE_SEQUENCES$2[0x0D] = '\\r'; +ESCAPE_SEQUENCES$2[0x1B] = '\\e'; +ESCAPE_SEQUENCES$2[0x22] = '\\"'; +ESCAPE_SEQUENCES$2[0x5C] = '\\\\'; +ESCAPE_SEQUENCES$2[0x85] = '\\N'; +ESCAPE_SEQUENCES$2[0xA0] = '\\_'; +ESCAPE_SEQUENCES$2[0x2028] = '\\L'; +ESCAPE_SEQUENCES$2[0x2029] = '\\P'; + +var DEPRECATED_BOOLEANS_SYNTAX$2 = [ + 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON', + 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF' +]; + +function compileStyleMap$2(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$5.call(type.styleAliases, style)) { + style = type.styleAliases[style]; + } + + result[tag] = style; + } + + return result; +} + +function encodeHex$2(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$6('code point within a string may not be greater than 0xFFFFFFFF'); + } + + return '\\' + handle + common$b.repeat('0', length - string.length) + string; +} + +function State$3(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$b.isNothing(options['flowLevel']) ? -1 : options['flowLevel']); + this.styleMap = compileStyleMap$2(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$2(string, spaces) { + var ind = common$b.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$2(state, level) { + return '\n' + common$b.repeat(' ', state.indent * level); +} + +function testImplicitResolving$2(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$3(c) { + return c === CHAR_SPACE$2 || c === CHAR_TAB$2; +} + +// 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$2(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$2(c) && !isWhitespace$3(c) + // byte-order-mark + && c !== 0xFEFF + // b-char + && c !== CHAR_CARRIAGE_RETURN$2 + && c !== CHAR_LINE_FEED$2; +} + +// Simplified test for values allowed after the first character in plain style. +function isPlainSafe$2(c, prev) { + // Uses a subset of nb-char - c-flow-indicator - ":" - "#" + // where nb-char ::= c-printable - b-char - c-byte-order-mark. + return isPrintable$2(c) && c !== 0xFEFF + // - c-flow-indicator + && c !== CHAR_COMMA$2 + && c !== CHAR_LEFT_SQUARE_BRACKET$2 + && c !== CHAR_RIGHT_SQUARE_BRACKET$2 + && c !== CHAR_LEFT_CURLY_BRACKET$2 + && c !== CHAR_RIGHT_CURLY_BRACKET$2 + // - ":" - "#" + // /* An ns-char preceding */ "#" + && c !== CHAR_COLON$2 + && ((c !== CHAR_SHARP$2) || (prev && isNsChar(prev))); +} + +// Simplified test for values allowed as the first character in plain style. +function isPlainSafeFirst$2(c) { + // Uses a subset of ns-char - c-indicator + // where ns-char = nb-char - s-white. + return isPrintable$2(c) && c !== 0xFEFF + && !isWhitespace$3(c) // - s-white + // - (c-indicator ::= + // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}” + && c !== CHAR_MINUS$2 + && c !== CHAR_QUESTION$2 + && c !== CHAR_COLON$2 + && c !== CHAR_COMMA$2 + && c !== CHAR_LEFT_SQUARE_BRACKET$2 + && c !== CHAR_RIGHT_SQUARE_BRACKET$2 + && c !== CHAR_LEFT_CURLY_BRACKET$2 + && c !== CHAR_RIGHT_CURLY_BRACKET$2 + // | “#” | “&” | “*” | “!” | “|” | “=” | “>” | “'” | “"” + && c !== CHAR_SHARP$2 + && c !== CHAR_AMPERSAND$2 + && c !== CHAR_ASTERISK$2 + && c !== CHAR_EXCLAMATION$2 + && c !== CHAR_VERTICAL_LINE$2 + && c !== CHAR_EQUALS$2 + && c !== CHAR_GREATER_THAN$2 + && c !== CHAR_SINGLE_QUOTE$2 + && c !== CHAR_DOUBLE_QUOTE$2 + // | “%” | “@” | “`”) + && c !== CHAR_PERCENT$2 + && c !== CHAR_COMMERCIAL_AT$2 + && c !== CHAR_GRAVE_ACCENT$2; +} + +// Determines whether block indentation indicator is required. +function needIndentIndicator$2(string) { + var leadingSpaceRe = /^\n* /; + return leadingSpaceRe.test(string); +} + +var STYLE_PLAIN$2 = 1, + STYLE_SINGLE$2 = 2, + STYLE_LITERAL$2 = 3, + STYLE_FOLDED$2 = 4, + STYLE_DOUBLE$2 = 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$2(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$2(string.charCodeAt(0)) + && !isWhitespace$3(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$2(char)) { + return STYLE_DOUBLE$2; + } + prev_char = i > 0 ? string.charCodeAt(i - 1) : null; + plain = plain && isPlainSafe$2(char, prev_char); + } + } else { + // Case: block styles permitted. + for (i = 0; i < string.length; i++) { + char = string.charCodeAt(i); + if (char === CHAR_LINE_FEED$2) { + 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$2(char)) { + return STYLE_DOUBLE$2; + } + prev_char = i > 0 ? string.charCodeAt(i - 1) : null; + plain = plain && isPlainSafe$2(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$2 : STYLE_SINGLE$2; + } + // Edge case: block indentation indicator can only have one digit. + if (indentPerLevel > 9 && needIndentIndicator$2(string)) { + return STYLE_DOUBLE$2; + } + // At this point we know block styles are valid. + // Prefer literal style unless we want to fold. + return hasFoldableLine ? STYLE_FOLDED$2 : STYLE_LITERAL$2; +} + +// 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$2(state, string, level, iskey) { + state.dump = (function () { + if (string.length === 0) { + return "''"; + } + if (!state.noCompatMode && + DEPRECATED_BOOLEANS_SYNTAX$2.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$2(state, string); + } + + switch (chooseScalarStyle$2(string, singleLineOnly, state.indent, lineWidth, testAmbiguity)) { + case STYLE_PLAIN$2: + return string; + case STYLE_SINGLE$2: + return "'" + string.replace(/'/g, "''") + "'"; + case STYLE_LITERAL$2: + return '|' + blockHeader$2(string, state.indent) + + dropEndingNewline$2(indentString$2(string, indent)); + case STYLE_FOLDED$2: + return '>' + blockHeader$2(string, state.indent) + + dropEndingNewline$2(indentString$2(foldString$2(string, lineWidth), indent)); + case STYLE_DOUBLE$2: + return '"' + escapeString$3(string) + '"'; + default: + throw new YAMLException$6('impossible error: invalid scalar style'); + } + }()); +} + +// Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9. +function blockHeader$2(string, indentPerLevel) { + var indentIndicator = needIndentIndicator$2(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$2(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$2(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$2(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$2(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$2(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$3(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$2((char - 0xD800) * 0x400 + nextChar - 0xDC00 + 0x10000); + // Advance index one extra since we already used that char here. + i++; continue; + } + } + escapeSeq = ESCAPE_SEQUENCES$2[char]; + result += !escapeSeq && isPrintable$2(char) + ? string[i] + : escapeSeq || encodeHex$2(char); + } + + return result; +} + +function writeFlowSequence$2(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$2(state, level, object[index], false, false)) { + if (index !== 0) _result += ',' + (!state.condenseFlow ? ' ' : ''); + _result += state.dump; + } + } + + state.tag = _tag; + state.dump = '[' + _result + ']'; +} + +function writeBlockSequence$2(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$2(state, level + 1, object[index], true, true)) { + if (!compact || index !== 0) { + _result += generateNextLine$2(state, level); + } + + if (state.dump && CHAR_LINE_FEED$2 === state.dump.charCodeAt(0)) { + _result += '-'; + } else { + _result += '- '; + } + + _result += state.dump; + } + } + + state.tag = _tag; + state.dump = _result || '[]'; // Empty sequence if no valid values. +} + +function writeFlowMapping$2(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$2(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$2(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$2(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$6('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$2(state, level); + } + + objectKey = objectKeyList[index]; + objectValue = object[objectKey]; + + if (!writeNode$2(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$2 === state.dump.charCodeAt(0)) { + pairBuffer += '?'; + } else { + pairBuffer += '? '; + } + } + + pairBuffer += state.dump; + + if (explicitPair) { + pairBuffer += generateNextLine$2(state, level); + } + + if (!writeNode$2(state, level + 1, objectValue, true, explicitPair)) { + continue; // Skip this pair because of invalid value. + } + + if (state.dump && CHAR_LINE_FEED$2 === 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$2(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$4.call(type.represent) === '[object Function]') { + _result = type.represent(object, style); + } else if (_hasOwnProperty$5.call(type.represent, style)) { + _result = type.represent[style](object, style); + } else { + throw new YAMLException$6('!<' + 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$2(state, level, object, block, compact, iskey) { + state.tag = null; + state.dump = object; + + if (!detectType$2(state, object, false)) { + detectType$2(state, object, true); + } + + var type = _toString$4.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$2(state, level, state.dump, compact); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + state.dump; + } + } else { + writeFlowMapping$2(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$2(state, arrayLevel, state.dump, compact); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + state.dump; + } + } else { + writeFlowSequence$2(state, arrayLevel, state.dump); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; + } + } + } else if (type === '[object String]') { + if (state.tag !== '?') { + writeScalar$2(state, state.dump, level, iskey); + } + } else { + if (state.skipInvalid) return false; + throw new YAMLException$6('unacceptable kind of an object to dump ' + type); + } + + if (state.tag !== null && state.tag !== '?') { + state.dump = '!<' + state.tag + '> ' + state.dump; + } + } + + return true; +} + +function getDuplicateReferences$2(object, state) { + var objects = [], + duplicatesIndexes = [], + index, + length; + + inspectNode$2(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$2(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$2(object[index], objects, duplicatesIndexes); + } + } else { + objectKeyList = Object.keys(object); + + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + inspectNode$2(object[objectKeyList[index]], objects, duplicatesIndexes); + } + } + } + } +} + +function dump$3(input, options) { + options = options || {}; + + var state = new State$3(options); + + if (!state.noRefs) getDuplicateReferences$2(input, state); + + if (writeNode$2(state, 0, input, true, true)) return state.dump + '\n'; + + return ''; +} + +function safeDump$1(input, options) { + return dump$3(input, common$b.extend({ schema: DEFAULT_SAFE_SCHEMA }, options)); +} + +dumper$4.dump = dump$3; +dumper$4.safeDump = safeDump$1; + +var loader$3 = loader$4; +var dumper$3 = dumper$4; + + +function deprecated(name) { + return function () { + throw new Error('Function ' + name + ' is deprecated and cannot be used.'); + }; +} + + +jsYaml$3.Type = type$g; +jsYaml$3.Schema = schema$3; +jsYaml$3.FAILSAFE_SCHEMA = failsafe$3; +jsYaml$3.JSON_SCHEMA = json$5; +jsYaml$3.CORE_SCHEMA = core$b; +jsYaml$3.DEFAULT_SAFE_SCHEMA = default_safe; +jsYaml$3.DEFAULT_FULL_SCHEMA = default_full; +jsYaml$3.load = loader$3.load; +jsYaml$3.loadAll = loader$3.loadAll; +jsYaml$3.safeLoad = loader$3.safeLoad; +jsYaml$3.safeLoadAll = loader$3.safeLoadAll; +jsYaml$3.dump = dumper$3.dump; +jsYaml$3.safeDump = dumper$3.safeDump; +jsYaml$3.YAMLException = exception$2; + +// Deprecated schema names from JS-YAML 2.0.x +jsYaml$3.MINIMAL_SCHEMA = failsafe$3; +jsYaml$3.SAFE_SCHEMA = default_safe; +jsYaml$3.DEFAULT_SCHEMA = default_full; + +// Deprecated functions from JS-YAML 1.x.x +jsYaml$3.scan = deprecated('scan'); +jsYaml$3.parse = deprecated('parse'); +jsYaml$3.compose = deprecated('compose'); +jsYaml$3.addConstructor = deprecated('addConstructor'); + +var yaml$4 = jsYaml$3; + + +var jsYaml$2 = yaml$4; + +(function (module, exports) { + + const yaml = jsYaml$2; + + /** + * Default engines + */ + + const engines = module.exports; + + /** + * YAML + */ + + engines.yaml = { + parse: yaml.safeLoad.bind(yaml), + stringify: yaml.safeDump.bind(yaml) + }; + + /** + * JSON + */ + + engines.json = { + parse: JSON.parse.bind(JSON), + stringify: function(obj, options) { + const opts = Object.assign({replacer: null, space: 2}, options); + return JSON.stringify(obj, opts.replacer, opts.space); + } + }; + + /** + * JavaScript + */ + + engines.javascript = { + parse: function parse(str, options, wrap) { + /* eslint no-eval: 0 */ + try { + if (wrap !== false) { + str = '(function() {\nreturn ' + str.trim() + ';\n}());'; + } + return eval(str) || {}; + } catch (err) { + if (wrap !== false && /(unexpected|identifier)/i.test(err.message)) { + return parse(str, options, false); + } + throw new SyntaxError(err); + } + }, + stringify: function() { + throw new Error('stringifying JavaScript is not supported'); + } + }; +} (engines$2)); + +var enginesExports = engines$2.exports; + +var utils$8 = {}; + +/*! + * strip-bom-string <https://github.com/jonschlinkert/strip-bom-string> + * + * Copyright (c) 2015, 2017, Jon Schlinkert. + * Released under the MIT License. + */ + +var stripBomString = function(str) { + if (typeof str === 'string' && str.charAt(0) === '\ufeff') { + return str.slice(1); + } + return str; +}; + +(function (exports) { + + const stripBom = stripBomString; + const typeOf = kindOf; + + exports.define = function(obj, key, val) { + Reflect.defineProperty(obj, key, { + enumerable: false, + configurable: true, + writable: true, + value: val + }); + }; + + /** + * Returns true if `val` is a buffer + */ + + exports.isBuffer = function(val) { + return typeOf(val) === 'buffer'; + }; + + /** + * Returns true if `val` is an object + */ + + exports.isObject = function(val) { + return typeOf(val) === 'object'; + }; + + /** + * Cast `input` to a buffer + */ + + exports.toBuffer = function(input) { + return typeof input === 'string' ? Buffer.from(input) : input; + }; + + /** + * Cast `val` to a string. + */ + + exports.toString = function(input) { + if (exports.isBuffer(input)) return stripBom(String(input)); + if (typeof input !== 'string') { + throw new TypeError('expected input to be a string or buffer'); + } + return stripBom(input); + }; + + /** + * Cast `val` to an array. + */ + + exports.arrayify = function(val) { + return val ? (Array.isArray(val) ? val : [val]) : []; + }; + + /** + * Returns true if `str` starts with `substr`. + */ + + exports.startsWith = function(str, substr, len) { + if (typeof len !== 'number') len = substr.length; + return str.slice(0, len) === substr; + }; +} (utils$8)); + +const engines$1 = enginesExports; +const utils$7 = utils$8; + +var defaults$a = function(options) { + const opts = Object.assign({}, options); + + // ensure that delimiters are an array + opts.delimiters = utils$7.arrayify(opts.delims || opts.delimiters || '---'); + if (opts.delimiters.length === 1) { + opts.delimiters.push(opts.delimiters[0]); + } + + opts.language = (opts.language || opts.lang || 'yaml').toLowerCase(); + opts.engines = Object.assign({}, engines$1, opts.parsers, opts.engines); + return opts; +}; + +var engine = function(name, options) { + let engine = options.engines[name] || options.engines[aliase(name)]; + if (typeof engine === 'undefined') { + throw new Error('gray-matter engine "' + name + '" is not registered'); + } + if (typeof engine === 'function') { + engine = { parse: engine }; + } + return engine; +}; + +function aliase(name) { + switch (name.toLowerCase()) { + case 'js': + case 'javascript': + return 'javascript'; + case 'coffee': + case 'coffeescript': + case 'cson': + return 'coffee'; + case 'yaml': + case 'yml': + return 'yaml'; + default: { + return name; + } + } +} + +const typeOf$1 = kindOf; +const getEngine$1 = engine; +const defaults$9 = defaults$a; + +var stringify$5 = function(file, data, options) { + if (data == null && options == null) { + switch (typeOf$1(file)) { + case 'object': + data = file.data; + options = {}; + break; + case 'string': + return file; + default: { + throw new TypeError('expected file to be a string or object'); + } + } + } + + const str = file.content; + const opts = defaults$9(options); + if (data == null) { + if (!opts.data) return file; + data = opts.data; + } + + const language = file.language || opts.language; + const engine = getEngine$1(language, opts); + if (typeof engine.stringify !== 'function') { + throw new TypeError('expected "' + language + '.stringify" to be a function'); + } + + data = Object.assign({}, file.data, data); + const open = opts.delimiters[0]; + const close = opts.delimiters[1]; + const matter = engine.stringify(data, options).trim(); + let buf = ''; + + if (matter !== '{}') { + buf = newline$1(open) + newline$1(matter) + newline$1(close); + } + + if (typeof file.excerpt === 'string' && file.excerpt !== '') { + if (str.indexOf(file.excerpt.trim()) === -1) { + buf += newline$1(file.excerpt) + newline$1(close); + } + } + + return buf + newline$1(str); +}; + +function newline$1(str) { + return str.slice(-1) !== '\n' ? str + '\n' : str; +} + +const defaults$8 = defaults$a; + +var excerpt$1 = function(file, options) { + const opts = defaults$8(options); + + if (file.data == null) { + file.data = {}; + } + + if (typeof opts.excerpt === 'function') { + return opts.excerpt(file, opts); + } + + const sep = file.data.excerpt_separator || opts.excerpt_separator; + if (sep == null && (opts.excerpt === false || opts.excerpt == null)) { + return file; + } + + const delimiter = typeof opts.excerpt === 'string' + ? opts.excerpt + : (sep || opts.delimiters[0]); + + // if enabled, get the excerpt defined after front-matter + const idx = file.content.indexOf(delimiter); + if (idx !== -1) { + file.excerpt = file.content.slice(0, idx); + } + + return file; +}; + +const typeOf = kindOf; +const stringify$4 = stringify$5; +const utils$6 = utils$8; + +/** + * Normalize the given value to ensure an object is returned + * with the expected properties. + */ + +var toFile$1 = function(file) { + if (typeOf(file) !== 'object') { + file = { content: file }; + } + + if (typeOf(file.data) !== 'object') { + file.data = {}; + } + + // if file was passed as an object, ensure that + // "file.content" is set + if (file.contents && file.content == null) { + file.content = file.contents; + } + + // set non-enumerable properties on the file object + utils$6.define(file, 'orig', utils$6.toBuffer(file.content)); + utils$6.define(file, 'language', file.language || ''); + utils$6.define(file, 'matter', file.matter || ''); + utils$6.define(file, 'stringify', function(data, options) { + if (options && options.language) { + file.language = options.language; + } + return stringify$4(file, data, options); + }); + + // strip BOM and ensure that "file.content" is a string + file.content = utils$6.toString(file.content); + file.isEmpty = false; + file.excerpt = ''; + return file; +}; + +const getEngine = engine; +const defaults$7 = defaults$a; + +var parse$c = function(language, str, options) { + const opts = defaults$7(options); + const engine = getEngine(language, opts); + if (typeof engine.parse !== 'function') { + throw new TypeError('expected "' + language + '.parse" to be a function'); + } + return engine.parse(str, opts); +}; + +const fs$7 = require$$0$8; +const sections = sectionMatter; +const defaults$6 = defaults$a; +const stringify$3 = stringify$5; +const excerpt = excerpt$1; +const engines = enginesExports; +const toFile = toFile$1; +const parse$b = parse$c; +const utils$5 = utils$8; + +/** + * Takes a string or object with `content` property, extracts + * and parses front-matter from the string, then returns an object + * with `data`, `content` and other [useful properties](#returned-object). + * + * ```js + * const matter = require('gray-matter'); + * console.log(matter('---\ntitle: Home\n---\nOther stuff')); + * //=> { data: { title: 'Home'}, content: 'Other stuff' } + * ``` + * @param {Object|String} `input` String, or object with `content` string + * @param {Object} `options` + * @return {Object} + * @api public + */ + +function matter(input, options) { + if (input === '') { + return { data: {}, content: input, excerpt: '', orig: input }; + } + + let file = toFile(input); + const cached = matter.cache[file.content]; + + if (!options) { + if (cached) { + file = Object.assign({}, cached); + file.orig = cached.orig; + return file; + } + + // only cache if there are no options passed. if we cache when options + // are passed, we would need to also cache options values, which would + // negate any performance benefits of caching + matter.cache[file.content] = file; + } + + return parseMatter(file, options); +} + +/** + * Parse front matter + */ + +function parseMatter(file, options) { + const opts = defaults$6(options); + const open = opts.delimiters[0]; + const close = '\n' + opts.delimiters[1]; + let str = file.content; + + if (opts.language) { + file.language = opts.language; + } + + // get the length of the opening delimiter + const openLen = open.length; + if (!utils$5.startsWith(str, open, openLen)) { + excerpt(file, opts); + return file; + } + + // if the next character after the opening delimiter is + // a character from the delimiter, then it's not a front- + // matter delimiter + if (str.charAt(openLen) === open.slice(-1)) { + return file; + } + + // strip the opening delimiter + str = str.slice(openLen); + const len = str.length; + + // use the language defined after first delimiter, if it exists + const language = matter.language(str, opts); + if (language.name) { + file.language = language.name; + str = str.slice(language.raw.length); + } + + // get the index of the closing delimiter + let closeIndex = str.indexOf(close); + if (closeIndex === -1) { + closeIndex = len; + } + + // get the raw front-matter block + file.matter = str.slice(0, closeIndex); + + const block = file.matter.replace(/^\s*#[^\n]+/gm, '').trim(); + if (block === '') { + file.isEmpty = true; + file.empty = file.content; + file.data = {}; + } else { + + // create file.data by parsing the raw file.matter block + file.data = parse$b(file.language, file.matter, opts); + } + + // update file.content + if (closeIndex === len) { + file.content = ''; + } else { + file.content = str.slice(closeIndex + close.length); + if (file.content[0] === '\r') { + file.content = file.content.slice(1); + } + if (file.content[0] === '\n') { + file.content = file.content.slice(1); + } + } + + excerpt(file, opts); + + if (opts.sections === true || typeof opts.section === 'function') { + sections(file, opts.section); + } + return file; +} + +/** + * Expose engines + */ + +matter.engines = engines; + +/** + * Stringify an object to YAML or the specified language, and + * append it to the given string. By default, only YAML and JSON + * can be stringified. See the [engines](#engines) section to learn + * how to stringify other languages. + * + * ```js + * console.log(matter.stringify('foo bar baz', {title: 'Home'})); + * // results in: + * // --- + * // title: Home + * // --- + * // foo bar baz + * ``` + * @param {String|Object} `file` The content string to append to stringified front-matter, or a file object with `file.content` string. + * @param {Object} `data` Front matter to stringify. + * @param {Object} `options` [Options](#options) to pass to gray-matter and [js-yaml]. + * @return {String} Returns a string created by wrapping stringified yaml with delimiters, and appending that to the given string. + * @api public + */ + +matter.stringify = function(file, data, options) { + if (typeof file === 'string') file = matter(file, options); + return stringify$3(file, data, options); +}; + +/** + * Synchronously read a file from the file system and parse + * front matter. Returns the same object as the [main function](#matter). + * + * ```js + * const file = matter.read('./content/blog-post.md'); + * ``` + * @param {String} `filepath` file path of the file to read. + * @param {Object} `options` [Options](#options) to pass to gray-matter. + * @return {Object} Returns [an object](#returned-object) with `data` and `content` + * @api public + */ + +matter.read = function(filepath, options) { + const str = fs$7.readFileSync(filepath, 'utf8'); + const file = matter(str, options); + file.path = filepath; + return file; +}; + +/** + * Returns true if the given `string` has front matter. + * @param {String} `string` + * @param {Object} `options` + * @return {Boolean} True if front matter exists. + * @api public + */ + +matter.test = function(str, options) { + return utils$5.startsWith(str, defaults$6(options).delimiters[0]); +}; + +/** + * Detect the language to use, if one is defined after the + * first front-matter delimiter. + * @param {String} `string` + * @param {Object} `options` + * @return {Object} Object with `raw` (actual language string), and `name`, the language with whitespace trimmed + */ + +matter.language = function(str, options) { + const opts = defaults$6(options); + const open = opts.delimiters[0]; + + if (matter.test(str)) { + str = str.slice(open.length); + } + + const language = str.slice(0, str.search(/\r?\n/)); + return { + raw: language, + name: language ? language.trim() : '' + }; +}; + +/** + * Expose `matter` + */ + +matter.cache = {}; +matter.clearCache = function() { + matter.cache = {}; +}; +var grayMatter = matter; + +var grayMatter$1 = /*@__PURE__*/getDefaultExportFromCjs(grayMatter); + +/** + * Returns the content, matter and slug of the specified Markdown or HTML file + * + * @param {String} filepath path to the HTML/Markdown file + * (file extension must end in `.html`, `.md`., or `.markdown`) + */ +function readDoc(filepath) { + debug(`reading file ${filepath}`); + const rawFileContents = fs$i.readFileSync(filepath, 'utf8'); + const matter = grayMatter$1(rawFileContents); + const { content, data } = matter; + debug(`front matter for ${filepath}: ${JSON.stringify(matter)}`); + // Stripping the subdirectories and markdown extension from the filename and lowercasing to get the default slug. + const slug = matter.data.slug || path$c.basename(filepath).replace(path$c.extname(filepath), '').toLowerCase(); + const hash = crypto$1.createHash('sha1').update(rawFileContents).digest('hex'); + return { content, data, hash, slug }; +} + +/** + * Reads the contents of the specified Markdown or HTML file + * and creates/updates the corresponding doc in ReadMe + * + * @param key the project API key + * @param selectedVersion the project version + * @param dryRun boolean indicating dry run mode + * @param filePath path to file + * @param type module within ReadMe to update (e.g. docs, changelogs, etc.) + * @returns A promise-wrapped string with the result + */ +async function pushDoc(key, selectedVersion, dryRun, filePath, type) { + const { content, data, hash, slug } = readDoc(filePath); + // TODO: ideally we should offer a zero-configuration approach that doesn't + // require YAML front matter, but that will have to be a breaking change + if (!Object.keys(data).length) { + debug(`No front matter attributes found for ${filePath}, not syncing`); + return `⏭️ no front matter attributes found for ${filePath}, skipping`; + } + let payload = { body: content, ...data, lastUpdatedHash: hash }; + if (type === CommandCategories.CUSTOM_PAGES) { + if (filePath.endsWith('.html')) { + payload = { html: content, htmlmode: true, ...data, lastUpdatedHash: hash }; + } + else { + payload = { body: content, htmlmode: false, ...data, lastUpdatedHash: hash }; + } + } + function createDoc() { + if (dryRun) { + return `🎭 dry run! This will create '${slug}' with contents from ${filePath} with the following metadata: ${JSON.stringify(data)}`; + } + return (readmeAPIFetch(`/api/v1/${type}`, { + method: 'post', + headers: cleanHeaders(key, new Headers$2({ + 'x-readme-version': selectedVersion, + 'Content-Type': 'application/json', + })), + body: JSON.stringify({ + slug, + ...payload, + }), + }, { filePath, fileType: 'path' }) + .then(handleRes) + // eslint-disable-next-line no-underscore-dangle + .then(res => `🌱 successfully created '${res.slug}' (ID: ${res._id}) with contents from ${filePath}`)); + } + function updateDoc(existingDoc) { + if (hash === existingDoc.lastUpdatedHash) { + return `${dryRun ? '🎭 dry run! ' : ''}\`${slug}\` ${dryRun ? 'will not be' : 'was not'} updated because there were no changes.`; + } + if (dryRun) { + return `🎭 dry run! This will update '${slug}' with contents from ${filePath} with the following metadata: ${JSON.stringify(data)}`; + } + return readmeAPIFetch(`/api/v1/${type}/${slug}`, { + method: 'put', + headers: cleanHeaders(key, new Headers$2({ + 'x-readme-version': selectedVersion, + 'Content-Type': 'application/json', + })), + body: JSON.stringify(payload), + }, { filePath, fileType: 'path' }) + .then(handleRes) + .then(res => `✏️ successfully updated '${res.slug}' with contents from ${filePath}`); + } + return readmeAPIFetch(`/api/v1/${type}/${slug}`, { + method: 'get', + headers: cleanHeaders(key, new Headers$2({ + 'x-readme-version': selectedVersion, + Accept: 'application/json', + })), + }) + .then(async (res) => { + const body = await handleRes(res, false); + if (!res.ok) { + if (res.status !== 404) + return Promise.reject(new APIError(body)); + debug(`error retrieving data for ${slug}, creating doc`); + return createDoc(); + } + debug(`data received for ${slug}, updating doc`); + return updateDoc(body); + }) + .catch(err => { + // eslint-disable-next-line no-param-reassign + err.message = `Error uploading ${chalk$5.underline(filePath)}:\n\n${err.message}`; + throw err; + }); +} +/** + * Takes a path (either to a directory of files or to a single file) + * and syncs those (either via POST or PUT) to ReadMe. + * @returns A promise-wrapped string with the results + */ +async function syncDocsPath( +/** Project API key */ +key, +/** ReadMe project version */ +selectedVersion, +/** module within ReadMe to update (e.g. docs, changelogs, etc.) */ +cmdType, +/** Example command usage, used in error message */ +usage, +/** Path input, can either be a directory or a single file */ +pathInput, +/** boolean indicating dry run mode */ +dryRun, +/** array of allowed file extensions */ +allowedFileExtensions = ['.markdown', '.md']) { + if (!pathInput) { + return Promise.reject(new Error(`No path provided. Usage \`${config.cli} ${usage}\`.`)); + } + const stat = await fs$j.stat(pathInput).catch(err => { + if (err.code === 'ENOENT') { + throw new Error("Oops! We couldn't locate a file or directory at the path you provided."); + } + throw err; + }); + let output; + if (stat.isDirectory()) { + // Filter out any files that don't match allowedFileExtensions + const files = readdirRecursive(pathInput).filter(file => allowedFileExtensions.includes(path$c.extname(file).toLowerCase())); + Command.debug(`number of files: ${files.length}`); + if (!files.length) { + return Promise.reject(new Error(`The directory you provided (${pathInput}) doesn't contain any of the following required files: ${allowedFileExtensions.join(', ')}.`)); + } + output = (await Promise.all(files.map(async (filename) => { + return pushDoc(key, selectedVersion, dryRun, filename, cmdType); + }))).join('\n'); + } + else { + const fileExtension = path$c.extname(pathInput).toLowerCase(); + if (!allowedFileExtensions.includes(fileExtension)) { + return Promise.reject(new Error(`Invalid file extension (${fileExtension}). Must be one of the following: ${allowedFileExtensions.join(', ')}`)); + } + output = await pushDoc(key, selectedVersion, dryRun, pathInput, cmdType); + } + return Promise.resolve(chalk$5.green(output)); +} + +var __decorate$5 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +}; +let ChangelogsCommand = class ChangelogsCommand extends Command { + constructor() { + super(); + this.command = 'changelogs'; + this.usage = 'changelogs <path> [options]'; + this.description = + 'Sync Markdown files to your ReadMe project as Changelog posts. Can either be a path to a directory or a single Markdown file.'; + this.cmdCategory = CommandCategories.CHANGELOGS; + this.hiddenArgs = ['filePath']; + this.args = [ + this.getKeyArg(), + { + name: 'filePath', + type: String, + defaultOption: true, + }, + this.getGitHubArg(), + { + name: 'dryRun', + type: Boolean, + description: 'Runs the command without creating/updating any changelogs in ReadMe. Useful for debugging.', + }, + ]; + } + async run(opts) { + await super.run(opts); + const { dryRun, filePath, key } = opts; + return syncDocsPath(key, undefined, this.cmdCategory, this.usage, filePath, dryRun); + } +}; +ChangelogsCommand = __decorate$5([ + supportsGHA +], ChangelogsCommand); +var ChangelogsCommand$1 = ChangelogsCommand; + +var __decorate$4 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +}; +let CustomPagesCommand = class CustomPagesCommand extends Command { + constructor() { + super(); + this.command = 'custompages'; + this.usage = 'custompages <path> [options]'; + this.description = + 'Sync Markdown/HTML files to your ReadMe project as Custom Pages. Can either be a path to a directory or a single Markdown/HTML file.'; + this.cmdCategory = CommandCategories.CUSTOM_PAGES; + this.hiddenArgs = ['filePath']; + this.args = [ + this.getKeyArg(), + { + name: 'filePath', + type: String, + defaultOption: true, + }, + this.getGitHubArg(), + { + name: 'dryRun', + type: Boolean, + description: 'Runs the command without creating/updating any custom pages in ReadMe. Useful for debugging.', + }, + ]; + } + async run(opts) { + await super.run(opts); + const { dryRun, filePath, key } = opts; + return syncDocsPath(key, undefined, this.cmdCategory, this.usage, filePath, dryRun, ['.html', '.markdown', '.md']); + } +}; +CustomPagesCommand = __decorate$4([ + supportsGHA +], CustomPagesCommand); +var CustomPagesCommand$1 = CustomPagesCommand; + +var spawn$1 = require$$0$h.spawn; + +var editor = function (file, opts, cb) { + if (typeof opts === 'function') { + cb = opts; + opts = {}; + } + if (!opts) opts = {}; + + var ed = /^win/.test(process.platform) ? 'notepad' : 'vim'; + var editor = opts.editor || process.env.VISUAL || process.env.EDITOR || ed; + var args = editor.split(/\s+/); + var bin = args.shift(); + + var ps = spawn$1(bin, args.concat([ file ]), { stdio: 'inherit' }); + + ps.on('exit', function (code, sig) { + if (typeof cb === 'function') cb(code, sig); + }); +}; + +var editor$1 = /*@__PURE__*/getDefaultExportFromCjs(editor); + +/* eslint-disable @typescript-eslint/no-explicit-any */ +/** + * This TypeScript decorator will cause the decorated command to be hidden from all help and + * "Related commands" screens. + * + * @see {@link https://www.typescriptlang.org/docs/handbook/decorators.html#class-decorators} + */ +function isHidden$1(constructor) { + return class extends constructor { + constructor() { + super(...arguments); + this.hidden = true; + } + }; +} + +var __decorate$3 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +}; +const writeFile$1 = node_util.promisify(fs$i.writeFile); +const readFile$2 = node_util.promisify(fs$i.readFile); +const unlink = node_util.promisify(fs$i.unlink); +let DocsEditCommand = class DocsEditCommand extends Command { + constructor() { + super(); + this.command = 'docs:edit'; + this.usage = 'docs:edit <slug> [options]'; + this.description = 'Edit a single file from your ReadMe project without saving locally. [deprecated]'; + this.cmdCategory = CommandCategories.DOCS; + this.hiddenArgs = ['slug']; + this.args = [ + this.getKeyArg(), + this.getVersionArg(), + { + name: 'slug', + type: String, + defaultOption: true, + }, + ]; + } + async run(opts) { + Command.warn('`rdme docs:edit` is now deprecated and will be removed in a future release.'); + await super.run(opts); + const { slug, key, version } = opts; + if (!slug) { + return Promise.reject(new Error(`No slug provided. Usage \`${config.cli} ${this.usage}\`.`)); + } + const selectedVersion = await getProjectVersion(version, key); + Command.debug(`selectedVersion: ${selectedVersion}`); + const filename = `${slug}.md`; + const existingDoc = await readmeAPIFetch(`/api/v1/docs/${slug}`, { + method: 'get', + headers: cleanHeaders(key, new Headers$2({ + 'x-readme-version': selectedVersion, + Accept: 'application/json', + })), + }).then(handleRes); + await writeFile$1(filename, existingDoc.body); + Command.debug(`wrote to local file: ${filename}, opening editor`); + return new Promise((resolve, reject) => { + (opts.mockEditor || editor$1)(filename, async (code) => { + Command.debug(`editor closed with code ${code}`); + if (code !== 0) + return reject(new Error('Non zero exit code from $EDITOR')); + const updatedDoc = await readFile$2(filename, 'utf8'); + Command.debug(`read edited contents of ${filename}, sending to ReadMe`); + return readmeAPIFetch(`/api/v1/docs/${slug}`, { + method: 'put', + headers: cleanHeaders(key, new Headers$2({ + 'x-readme-version': selectedVersion, + 'Content-Type': 'application/json', + })), + body: JSON.stringify(Object.assign(existingDoc, { + body: updatedDoc, + })), + }) + .then(res => handleRes(res, false)) + .then(async (res) => { + // We need to use the `reject` function from + // the Promise that's wrapping this function. + if (res.error) { + return reject(new APIError(res)); + } + Command.info('Doc successfully updated. Cleaning up local file.'); + await unlink(filename); + Command.debug('file unlinked'); + // Normally we should resolve with a value that is logged to the console, + // but since we need to wait for the temporary file to be removed, + // it's okay to resolve the promise with no value. + return resolve(undefined); + }); + }); + }); + } +}; +DocsEditCommand = __decorate$3([ + isHidden$1 +], DocsEditCommand); +var DocsEditCommand$1 = DocsEditCommand; + +class DocsCommand extends Command { + constructor() { + super(); + this.command = 'docs'; + this.usage = 'docs <path> [options]'; + this.description = + 'Sync Markdown files to your ReadMe project as Guides. Can either be a path to a directory or a single Markdown file.'; + this.cmdCategory = CommandCategories.DOCS; + this.hiddenArgs = ['filePath']; + this.args = [ + this.getKeyArg(), + this.getVersionArg(), + { + name: 'filePath', + type: String, + defaultOption: true, + }, + this.getGitHubArg(), + { + name: 'dryRun', + type: Boolean, + description: 'Runs the command without creating/updating any docs in ReadMe. Useful for debugging.', + }, + ]; + } + async run(opts) { + await super.run(opts); + const { dryRun, filePath, key, version } = opts; + // TODO: should we allow version selection at all here? + // Let's revisit this once we re-evaluate our category logic in the API. + // Ideally we should ignore this parameter entirely if the category is included. + const selectedVersion = await getProjectVersion(version, key); + return syncDocsPath(key, selectedVersion, this.cmdCategory, this.usage, filePath, dryRun).then(msg => createGHA(msg, this.command, this.args, { ...opts, version: selectedVersion })); + } +} + +/** + * Delete a document from ReadMe + * + * @param {String} key the project API key + * @param {String} selectedVersion the project version + * @param {Boolean} dryRun boolean indicating dry run mode + * @param {String} slug The slug of the document to delete + * @param {String} type module within ReadMe to update (e.g. docs, changelogs, etc.) + * @returns {Promise<String>} a string containing the result + */ +async function deleteDoc(key, selectedVersion, dryRun, slug, type) { + if (dryRun) { + return Promise.resolve(`🎭 dry run! This will delete \`${slug}\`.`); + } + return readmeAPIFetch(`/api/v1/${type}/${slug}`, { + method: 'delete', + headers: cleanHeaders(key, new Headers$2({ + 'x-readme-version': selectedVersion, + 'Content-Type': 'application/json', + })), + }) + .then(handleRes) + .then(() => `🗑️ successfully deleted \`${slug}\`.`); +} + +function flatten$3(data) { + const allDocs = []; + const docs = [].concat(...data); + docs.forEach(doc => { + allDocs.push(doc); + if (doc.children) { + doc.children.forEach(child => { + allDocs.push(child); + }); + } + }); + // Docs with children cannot be deleted unless the children are deleted first, + // so move those parent docs to the back of the list + allDocs.sort(a => (a.children?.length ? 1 : -1)); + return allDocs; +} +async function getCategoryDocs(key, selectedVersion, category) { + return readmeAPIFetch(`/api/v1/categories/${category}/docs`, { + method: 'get', + headers: cleanHeaders(key, new Headers$2({ + 'x-readme-version': selectedVersion, + 'Content-Type': 'application/json', + })), + }).then(handleRes); +} +/** + * Retrieve the docs under all categories + * + * @param {String} key the project API key + * @param {String} selectedVersion the project version + * @returns {Promise<Array<Document>>} an array containing the docs + */ +async function getDocs(key, selectedVersion) { + return getCategories$1(key, selectedVersion) + .then(categories => categories.filter(({ type }) => type === 'guide')) + .then(categories => categories.map(({ slug }) => getCategoryDocs(key, selectedVersion, slug))) + .then(categoryDocsPromises => Promise.all(categoryDocsPromises)) + .then(flatten$3); +} + +function getSlug(filename) { + const { slug } = readDoc(filename); + return slug; +} +class DocsPruneCommand extends Command { + constructor() { + super(); + this.command = 'docs:prune'; + this.usage = 'docs:prune <folder> [options]'; + this.description = 'Delete any docs from ReadMe if their slugs are not found in the target folder.'; + this.cmdCategory = CommandCategories.DOCS; + this.hiddenArgs = ['folder']; + this.args = [ + this.getKeyArg(), + this.getVersionArg(), + { + name: 'folder', + type: String, + defaultOption: true, + }, + this.getGitHubArg(), + { + name: 'confirm', + type: Boolean, + description: 'Bypass the confirmation prompt. Useful for CI environments.', + }, + { + name: 'dryRun', + type: Boolean, + description: 'Runs the command without creating/updating any docs in ReadMe. Useful for debugging.', + }, + ]; + } + async run(opts) { + await super.run(opts); + const { dryRun, folder, key, version } = opts; + if (!folder) { + return Promise.reject(new Error(`No folder provided. Usage \`${config.cli} ${this.usage}\`.`)); + } + // TODO: should we allow version selection at all here? + // Let's revisit this once we re-evaluate our category logic in the API. + // Ideally we should ignore this parameter entirely if the category is included. + const selectedVersion = await getProjectVersion(version, key); + Command.debug(`selectedVersion: ${selectedVersion}`); + // Strip out non-markdown files + const files = readdirRecursive(folder).filter(file => file.toLowerCase().endsWith('.md') || file.toLowerCase().endsWith('.markdown')); + Command.debug(`number of files: ${files.length}`); + prompts$1.override(opts); + const { confirm } = await promptTerminal({ + type: 'confirm', + name: 'confirm', + message: `This command will delete all guides page from your ReadMe project (version ${selectedVersion}) that are not also in ${folder}, would you like to confirm?`, + }); + if (!confirm) { + return Promise.reject(new Error('Aborting, no changes were made.')); + } + const docs = await getDocs(key, selectedVersion); + const docSlugs = docs.map(({ slug }) => slug); + const fileSlugs = new Set(files.map(getSlug)); + const slugsToDelete = docSlugs.filter((slug) => !fileSlugs.has(slug)); + const deletedDocs = await Promise.all(slugsToDelete.map((slug) => deleteDoc(key, selectedVersion, dryRun, slug, this.cmdCategory))); + return Promise.resolve(chalk$5.green(deletedDocs.join('\n'))).then(msg => createGHA(msg, this.command, this.args, { ...opts, version: selectedVersion })); + } +} + +class GuidesCommand extends DocsCommand { + constructor() { + super(); + this.command = 'guides'; + this.usage = 'guides <path> [options]'; + this.description = 'Alias for `rdme docs`.'; + } + async run(opts) { + return super.run(opts); + } +} + +class GuidesPruneCommand extends DocsPruneCommand { + constructor() { + super(); + this.command = 'guides:prune'; + this.usage = 'guides:prune <folder> [options]'; + this.description = 'Alias for `rdme docs:prune`.'; + } + async run(opts) { + return super.run(opts); + } +} + +class LoginCommand extends Command { + constructor() { + super(); + this.command = 'login'; + this.usage = 'login [options]'; + this.description = 'Login to a ReadMe project.'; + this.cmdCategory = CommandCategories.ADMIN; + this.args = [ + { + name: 'email', + type: String, + description: 'Your email address', + }, + { + name: 'password', + type: String, + description: 'Your password', + }, + { + name: 'otp', + type: String, + description: 'Your one-time password (if you have two-factor authentication enabled)', + }, + { + name: 'project', + type: String, + description: 'The subdomain of the project you wish to log into', + }, + ]; + } + async run(opts) { + await super.run(opts); + prompts$1.override(opts); + return loginFlow(opts.otp); + } +} + +class LogoutCommand extends Command { + constructor() { + super(); + this.command = 'logout'; + this.usage = 'logout'; + this.description = 'Logs the currently authenticated user out of ReadMe.'; + this.cmdCategory = CommandCategories.ADMIN; + this.args = []; + } + async run(opts) { + await super.run(opts); + if (configstore.has('email') && configstore.has('project')) { + configstore.clear(); + } + return Promise.resolve(`You have logged out of ReadMe. Please use \`${config.cli} login\` to login again.`); + } +} + +var __decorate$2 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +}; +let OASCommand = class OASCommand extends Command { + constructor() { + super(); + this.command = 'oas'; + this.usage = 'oas'; + this.description = 'Helpful OpenAPI generation tooling. [inactive]'; + this.cmdCategory = CommandCategories.UTILITIES; + this.args = []; + } + async run(opts) { + await super.run(opts); + const message = [ + 'This `oas` integration is now inactive.', + "If you're looking to create an OpenAPI definition, we recommend https://npm.im/swagger-inline", + ]; + return Promise.reject(new Error(message.join('\n\n'))); + } +}; +OASCommand = __decorate$2([ + isHidden$1 +], OASCommand); +var OASCommand$1 = OASCommand; + +var isWsl$2 = {exports: {}}; + +const fs$6 = require$$0$8; + +let isDocker$2; + +function hasDockerEnv$1() { + try { + fs$6.statSync('/.dockerenv'); + return true; + } catch (_) { + return false; + } +} + +function hasDockerCGroup$1() { + try { + return fs$6.readFileSync('/proc/self/cgroup', 'utf8').includes('docker'); + } catch (_) { + return false; + } +} + +var isDocker_1 = () => { + if (isDocker$2 === undefined) { + isDocker$2 = hasDockerEnv$1() || hasDockerCGroup$1(); + } + + return isDocker$2; +}; + +const os$2 = require$$0$7; +const fs$5 = require$$0$8; +const isDocker$1 = isDocker_1; + +const isWsl = () => { + if (process.platform !== 'linux') { + return false; + } + + if (os$2.release().toLowerCase().includes('microsoft')) { + if (isDocker$1()) { + return false; + } + + return true; + } + + try { + return fs$5.readFileSync('/proc/version', 'utf8').toLowerCase().includes('microsoft') ? + !isDocker$1() : false; + } catch (_) { + return false; + } +}; + +if (process.env.__IS_WSL_TEST__) { + isWsl$2.exports = isWsl; +} else { + isWsl$2.exports = isWsl(); +} + +var isWslExports = isWsl$2.exports; +var isWsl$1 = /*@__PURE__*/getDefaultExportFromCjs(isWslExports); + +function defineLazyProperty(object, propertyName, valueGetter) { + const define = value => Object.defineProperty(object, propertyName, {value, enumerable: true, writable: true}); + + Object.defineProperty(object, propertyName, { + configurable: true, + enumerable: true, + get() { + const result = valueGetter(); + define(result); + return result; + }, + set(value) { + define(value); + } + }); + + return object; +} + +var bplistParser = {}; + +var BigInteger = {exports: {}}; + +(function (module) { + var bigInt = (function (undefined$1) { + + var BASE = 1e7, + LOG_BASE = 7, + MAX_INT = 9007199254740992, + MAX_INT_ARR = smallToArray(MAX_INT), + DEFAULT_ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz"; + + var supportsNativeBigInt = typeof BigInt === "function"; + + function Integer(v, radix, alphabet, caseSensitive) { + if (typeof v === "undefined") return Integer[0]; + if (typeof radix !== "undefined") return +radix === 10 && !alphabet ? parseValue(v) : parseBase(v, radix, alphabet, caseSensitive); + return parseValue(v); + } + + function BigInteger(value, sign) { + this.value = value; + this.sign = sign; + this.isSmall = false; + } + BigInteger.prototype = Object.create(Integer.prototype); + + function SmallInteger(value) { + this.value = value; + this.sign = value < 0; + this.isSmall = true; + } + SmallInteger.prototype = Object.create(Integer.prototype); + + function NativeBigInt(value) { + this.value = value; + } + NativeBigInt.prototype = Object.create(Integer.prototype); + + function isPrecise(n) { + return -MAX_INT < n && n < MAX_INT; + } + + function smallToArray(n) { // For performance reasons doesn't reference BASE, need to change this function if BASE changes + if (n < 1e7) + return [n]; + if (n < 1e14) + return [n % 1e7, Math.floor(n / 1e7)]; + return [n % 1e7, Math.floor(n / 1e7) % 1e7, Math.floor(n / 1e14)]; + } + + function arrayToSmall(arr) { // If BASE changes this function may need to change + trim(arr); + var length = arr.length; + if (length < 4 && compareAbs(arr, MAX_INT_ARR) < 0) { + switch (length) { + case 0: return 0; + case 1: return arr[0]; + case 2: return arr[0] + arr[1] * BASE; + default: return arr[0] + (arr[1] + arr[2] * BASE) * BASE; + } + } + return arr; + } + + function trim(v) { + var i = v.length; + while (v[--i] === 0); + v.length = i + 1; + } + + function createArray(length) { // function shamelessly stolen from Yaffle's library https://github.com/Yaffle/BigInteger + var x = new Array(length); + var i = -1; + while (++i < length) { + x[i] = 0; + } + return x; + } + + function truncate(n) { + if (n > 0) return Math.floor(n); + return Math.ceil(n); + } + + function add(a, b) { // assumes a and b are arrays with a.length >= b.length + var l_a = a.length, + l_b = b.length, + r = new Array(l_a), + carry = 0, + base = BASE, + sum, i; + for (i = 0; i < l_b; i++) { + sum = a[i] + b[i] + carry; + carry = sum >= base ? 1 : 0; + r[i] = sum - carry * base; + } + while (i < l_a) { + sum = a[i] + carry; + carry = sum === base ? 1 : 0; + r[i++] = sum - carry * base; + } + if (carry > 0) r.push(carry); + return r; + } + + function addAny(a, b) { + if (a.length >= b.length) return add(a, b); + return add(b, a); + } + + function addSmall(a, carry) { // assumes a is array, carry is number with 0 <= carry < MAX_INT + var l = a.length, + r = new Array(l), + base = BASE, + sum, i; + for (i = 0; i < l; i++) { + sum = a[i] - base + carry; + carry = Math.floor(sum / base); + r[i] = sum - carry * base; + carry += 1; + } + while (carry > 0) { + r[i++] = carry % base; + carry = Math.floor(carry / base); + } + return r; + } + + BigInteger.prototype.add = function (v) { + var n = parseValue(v); + if (this.sign !== n.sign) { + return this.subtract(n.negate()); + } + var a = this.value, b = n.value; + if (n.isSmall) { + return new BigInteger(addSmall(a, Math.abs(b)), this.sign); + } + return new BigInteger(addAny(a, b), this.sign); + }; + BigInteger.prototype.plus = BigInteger.prototype.add; + + SmallInteger.prototype.add = function (v) { + var n = parseValue(v); + var a = this.value; + if (a < 0 !== n.sign) { + return this.subtract(n.negate()); + } + var b = n.value; + if (n.isSmall) { + if (isPrecise(a + b)) return new SmallInteger(a + b); + b = smallToArray(Math.abs(b)); + } + return new BigInteger(addSmall(b, Math.abs(a)), a < 0); + }; + SmallInteger.prototype.plus = SmallInteger.prototype.add; + + NativeBigInt.prototype.add = function (v) { + return new NativeBigInt(this.value + parseValue(v).value); + }; + NativeBigInt.prototype.plus = NativeBigInt.prototype.add; + + function subtract(a, b) { // assumes a and b are arrays with a >= b + var a_l = a.length, + b_l = b.length, + r = new Array(a_l), + borrow = 0, + base = BASE, + i, difference; + for (i = 0; i < b_l; i++) { + difference = a[i] - borrow - b[i]; + if (difference < 0) { + difference += base; + borrow = 1; + } else borrow = 0; + r[i] = difference; + } + for (i = b_l; i < a_l; i++) { + difference = a[i] - borrow; + if (difference < 0) difference += base; + else { + r[i++] = difference; + break; + } + r[i] = difference; + } + for (; i < a_l; i++) { + r[i] = a[i]; + } + trim(r); + return r; + } + + function subtractAny(a, b, sign) { + var value; + if (compareAbs(a, b) >= 0) { + value = subtract(a, b); + } else { + value = subtract(b, a); + sign = !sign; + } + value = arrayToSmall(value); + if (typeof value === "number") { + if (sign) value = -value; + return new SmallInteger(value); + } + return new BigInteger(value, sign); + } + + function subtractSmall(a, b, sign) { // assumes a is array, b is number with 0 <= b < MAX_INT + var l = a.length, + r = new Array(l), + carry = -b, + base = BASE, + i, difference; + for (i = 0; i < l; i++) { + difference = a[i] + carry; + carry = Math.floor(difference / base); + difference %= base; + r[i] = difference < 0 ? difference + base : difference; + } + r = arrayToSmall(r); + if (typeof r === "number") { + if (sign) r = -r; + return new SmallInteger(r); + } return new BigInteger(r, sign); + } + + BigInteger.prototype.subtract = function (v) { + var n = parseValue(v); + if (this.sign !== n.sign) { + return this.add(n.negate()); + } + var a = this.value, b = n.value; + if (n.isSmall) + return subtractSmall(a, Math.abs(b), this.sign); + return subtractAny(a, b, this.sign); + }; + BigInteger.prototype.minus = BigInteger.prototype.subtract; + + SmallInteger.prototype.subtract = function (v) { + var n = parseValue(v); + var a = this.value; + if (a < 0 !== n.sign) { + return this.add(n.negate()); + } + var b = n.value; + if (n.isSmall) { + return new SmallInteger(a - b); + } + return subtractSmall(b, Math.abs(a), a >= 0); + }; + SmallInteger.prototype.minus = SmallInteger.prototype.subtract; + + NativeBigInt.prototype.subtract = function (v) { + return new NativeBigInt(this.value - parseValue(v).value); + }; + NativeBigInt.prototype.minus = NativeBigInt.prototype.subtract; + + BigInteger.prototype.negate = function () { + return new BigInteger(this.value, !this.sign); + }; + SmallInteger.prototype.negate = function () { + var sign = this.sign; + var small = new SmallInteger(-this.value); + small.sign = !sign; + return small; + }; + NativeBigInt.prototype.negate = function () { + return new NativeBigInt(-this.value); + }; + + BigInteger.prototype.abs = function () { + return new BigInteger(this.value, false); + }; + SmallInteger.prototype.abs = function () { + return new SmallInteger(Math.abs(this.value)); + }; + NativeBigInt.prototype.abs = function () { + return new NativeBigInt(this.value >= 0 ? this.value : -this.value); + }; + + + function multiplyLong(a, b) { + var a_l = a.length, + b_l = b.length, + l = a_l + b_l, + r = createArray(l), + base = BASE, + product, carry, i, a_i, b_j; + for (i = 0; i < a_l; ++i) { + a_i = a[i]; + for (var j = 0; j < b_l; ++j) { + b_j = b[j]; + product = a_i * b_j + r[i + j]; + carry = Math.floor(product / base); + r[i + j] = product - carry * base; + r[i + j + 1] += carry; + } + } + trim(r); + return r; + } + + function multiplySmall(a, b) { // assumes a is array, b is number with |b| < BASE + var l = a.length, + r = new Array(l), + base = BASE, + carry = 0, + product, i; + for (i = 0; i < l; i++) { + product = a[i] * b + carry; + carry = Math.floor(product / base); + r[i] = product - carry * base; + } + while (carry > 0) { + r[i++] = carry % base; + carry = Math.floor(carry / base); + } + return r; + } + + function shiftLeft(x, n) { + var r = []; + while (n-- > 0) r.push(0); + return r.concat(x); + } + + function multiplyKaratsuba(x, y) { + var n = Math.max(x.length, y.length); + + if (n <= 30) return multiplyLong(x, y); + n = Math.ceil(n / 2); + + var b = x.slice(n), + a = x.slice(0, n), + d = y.slice(n), + c = y.slice(0, n); + + var ac = multiplyKaratsuba(a, c), + bd = multiplyKaratsuba(b, d), + abcd = multiplyKaratsuba(addAny(a, b), addAny(c, d)); + + var product = addAny(addAny(ac, shiftLeft(subtract(subtract(abcd, ac), bd), n)), shiftLeft(bd, 2 * n)); + trim(product); + return product; + } + + // The following function is derived from a surface fit of a graph plotting the performance difference + // between long multiplication and karatsuba multiplication versus the lengths of the two arrays. + function useKaratsuba(l1, l2) { + return -0.012 * l1 - 0.012 * l2 + 0.000015 * l1 * l2 > 0; + } + + BigInteger.prototype.multiply = function (v) { + var n = parseValue(v), + a = this.value, b = n.value, + sign = this.sign !== n.sign, + abs; + if (n.isSmall) { + if (b === 0) return Integer[0]; + if (b === 1) return this; + if (b === -1) return this.negate(); + abs = Math.abs(b); + if (abs < BASE) { + return new BigInteger(multiplySmall(a, abs), sign); + } + b = smallToArray(abs); + } + if (useKaratsuba(a.length, b.length)) // Karatsuba is only faster for certain array sizes + return new BigInteger(multiplyKaratsuba(a, b), sign); + return new BigInteger(multiplyLong(a, b), sign); + }; + + BigInteger.prototype.times = BigInteger.prototype.multiply; + + function multiplySmallAndArray(a, b, sign) { // a >= 0 + if (a < BASE) { + return new BigInteger(multiplySmall(b, a), sign); + } + return new BigInteger(multiplyLong(b, smallToArray(a)), sign); + } + SmallInteger.prototype._multiplyBySmall = function (a) { + if (isPrecise(a.value * this.value)) { + return new SmallInteger(a.value * this.value); + } + return multiplySmallAndArray(Math.abs(a.value), smallToArray(Math.abs(this.value)), this.sign !== a.sign); + }; + BigInteger.prototype._multiplyBySmall = function (a) { + if (a.value === 0) return Integer[0]; + if (a.value === 1) return this; + if (a.value === -1) return this.negate(); + return multiplySmallAndArray(Math.abs(a.value), this.value, this.sign !== a.sign); + }; + SmallInteger.prototype.multiply = function (v) { + return parseValue(v)._multiplyBySmall(this); + }; + SmallInteger.prototype.times = SmallInteger.prototype.multiply; + + NativeBigInt.prototype.multiply = function (v) { + return new NativeBigInt(this.value * parseValue(v).value); + }; + NativeBigInt.prototype.times = NativeBigInt.prototype.multiply; + + function square(a) { + //console.assert(2 * BASE * BASE < MAX_INT); + var l = a.length, + r = createArray(l + l), + base = BASE, + product, carry, i, a_i, a_j; + for (i = 0; i < l; i++) { + a_i = a[i]; + carry = 0 - a_i * a_i; + for (var j = i; j < l; j++) { + a_j = a[j]; + product = 2 * (a_i * a_j) + r[i + j] + carry; + carry = Math.floor(product / base); + r[i + j] = product - carry * base; + } + r[i + l] = carry; + } + trim(r); + return r; + } + + BigInteger.prototype.square = function () { + return new BigInteger(square(this.value), false); + }; + + SmallInteger.prototype.square = function () { + var value = this.value * this.value; + if (isPrecise(value)) return new SmallInteger(value); + return new BigInteger(square(smallToArray(Math.abs(this.value))), false); + }; + + NativeBigInt.prototype.square = function (v) { + return new NativeBigInt(this.value * this.value); + }; + + function divMod1(a, b) { // Left over from previous version. Performs faster than divMod2 on smaller input sizes. + var a_l = a.length, + b_l = b.length, + base = BASE, + result = createArray(b.length), + divisorMostSignificantDigit = b[b_l - 1], + // normalization + lambda = Math.ceil(base / (2 * divisorMostSignificantDigit)), + remainder = multiplySmall(a, lambda), + divisor = multiplySmall(b, lambda), + quotientDigit, shift, carry, borrow, i, l, q; + if (remainder.length <= a_l) remainder.push(0); + divisor.push(0); + divisorMostSignificantDigit = divisor[b_l - 1]; + for (shift = a_l - b_l; shift >= 0; shift--) { + quotientDigit = base - 1; + if (remainder[shift + b_l] !== divisorMostSignificantDigit) { + quotientDigit = Math.floor((remainder[shift + b_l] * base + remainder[shift + b_l - 1]) / divisorMostSignificantDigit); + } + // quotientDigit <= base - 1 + carry = 0; + borrow = 0; + l = divisor.length; + for (i = 0; i < l; i++) { + carry += quotientDigit * divisor[i]; + q = Math.floor(carry / base); + borrow += remainder[shift + i] - (carry - q * base); + carry = q; + if (borrow < 0) { + remainder[shift + i] = borrow + base; + borrow = -1; + } else { + remainder[shift + i] = borrow; + borrow = 0; + } + } + while (borrow !== 0) { + quotientDigit -= 1; + carry = 0; + for (i = 0; i < l; i++) { + carry += remainder[shift + i] - base + divisor[i]; + if (carry < 0) { + remainder[shift + i] = carry + base; + carry = 0; + } else { + remainder[shift + i] = carry; + carry = 1; + } + } + borrow += carry; + } + result[shift] = quotientDigit; + } + // denormalization + remainder = divModSmall(remainder, lambda)[0]; + return [arrayToSmall(result), arrayToSmall(remainder)]; + } + + function divMod2(a, b) { // Implementation idea shamelessly stolen from Silent Matt's library http://silentmatt.com/biginteger/ + // Performs faster than divMod1 on larger input sizes. + var a_l = a.length, + b_l = b.length, + result = [], + part = [], + base = BASE, + guess, xlen, highx, highy, check; + while (a_l) { + part.unshift(a[--a_l]); + trim(part); + if (compareAbs(part, b) < 0) { + result.push(0); + continue; + } + xlen = part.length; + highx = part[xlen - 1] * base + part[xlen - 2]; + highy = b[b_l - 1] * base + b[b_l - 2]; + if (xlen > b_l) { + highx = (highx + 1) * base; + } + guess = Math.ceil(highx / highy); + do { + check = multiplySmall(b, guess); + if (compareAbs(check, part) <= 0) break; + guess--; + } while (guess); + result.push(guess); + part = subtract(part, check); + } + result.reverse(); + return [arrayToSmall(result), arrayToSmall(part)]; + } + + function divModSmall(value, lambda) { + var length = value.length, + quotient = createArray(length), + base = BASE, + i, q, remainder, divisor; + remainder = 0; + for (i = length - 1; i >= 0; --i) { + divisor = remainder * base + value[i]; + q = truncate(divisor / lambda); + remainder = divisor - q * lambda; + quotient[i] = q | 0; + } + return [quotient, remainder | 0]; + } + + function divModAny(self, v) { + var value, n = parseValue(v); + if (supportsNativeBigInt) { + return [new NativeBigInt(self.value / n.value), new NativeBigInt(self.value % n.value)]; + } + var a = self.value, b = n.value; + var quotient; + if (b === 0) throw new Error("Cannot divide by zero"); + if (self.isSmall) { + if (n.isSmall) { + return [new SmallInteger(truncate(a / b)), new SmallInteger(a % b)]; + } + return [Integer[0], self]; + } + if (n.isSmall) { + if (b === 1) return [self, Integer[0]]; + if (b == -1) return [self.negate(), Integer[0]]; + var abs = Math.abs(b); + if (abs < BASE) { + value = divModSmall(a, abs); + quotient = arrayToSmall(value[0]); + var remainder = value[1]; + if (self.sign) remainder = -remainder; + if (typeof quotient === "number") { + if (self.sign !== n.sign) quotient = -quotient; + return [new SmallInteger(quotient), new SmallInteger(remainder)]; + } + return [new BigInteger(quotient, self.sign !== n.sign), new SmallInteger(remainder)]; + } + b = smallToArray(abs); + } + var comparison = compareAbs(a, b); + if (comparison === -1) return [Integer[0], self]; + if (comparison === 0) return [Integer[self.sign === n.sign ? 1 : -1], Integer[0]]; + + // divMod1 is faster on smaller input sizes + if (a.length + b.length <= 200) + value = divMod1(a, b); + else value = divMod2(a, b); + + quotient = value[0]; + var qSign = self.sign !== n.sign, + mod = value[1], + mSign = self.sign; + if (typeof quotient === "number") { + if (qSign) quotient = -quotient; + quotient = new SmallInteger(quotient); + } else quotient = new BigInteger(quotient, qSign); + if (typeof mod === "number") { + if (mSign) mod = -mod; + mod = new SmallInteger(mod); + } else mod = new BigInteger(mod, mSign); + return [quotient, mod]; + } + + BigInteger.prototype.divmod = function (v) { + var result = divModAny(this, v); + return { + quotient: result[0], + remainder: result[1] + }; + }; + NativeBigInt.prototype.divmod = SmallInteger.prototype.divmod = BigInteger.prototype.divmod; + + + BigInteger.prototype.divide = function (v) { + return divModAny(this, v)[0]; + }; + NativeBigInt.prototype.over = NativeBigInt.prototype.divide = function (v) { + return new NativeBigInt(this.value / parseValue(v).value); + }; + SmallInteger.prototype.over = SmallInteger.prototype.divide = BigInteger.prototype.over = BigInteger.prototype.divide; + + BigInteger.prototype.mod = function (v) { + return divModAny(this, v)[1]; + }; + NativeBigInt.prototype.mod = NativeBigInt.prototype.remainder = function (v) { + return new NativeBigInt(this.value % parseValue(v).value); + }; + SmallInteger.prototype.remainder = SmallInteger.prototype.mod = BigInteger.prototype.remainder = BigInteger.prototype.mod; + + BigInteger.prototype.pow = function (v) { + var n = parseValue(v), + a = this.value, + b = n.value, + value, x, y; + if (b === 0) return Integer[1]; + if (a === 0) return Integer[0]; + if (a === 1) return Integer[1]; + if (a === -1) return n.isEven() ? Integer[1] : Integer[-1]; + if (n.sign) { + return Integer[0]; + } + if (!n.isSmall) throw new Error("The exponent " + n.toString() + " is too large."); + if (this.isSmall) { + if (isPrecise(value = Math.pow(a, b))) + return new SmallInteger(truncate(value)); + } + x = this; + y = Integer[1]; + while (true) { + if (b & 1 === 1) { + y = y.times(x); + --b; + } + if (b === 0) break; + b /= 2; + x = x.square(); + } + return y; + }; + SmallInteger.prototype.pow = BigInteger.prototype.pow; + + NativeBigInt.prototype.pow = function (v) { + var n = parseValue(v); + var a = this.value, b = n.value; + var _0 = BigInt(0), _1 = BigInt(1), _2 = BigInt(2); + if (b === _0) return Integer[1]; + if (a === _0) return Integer[0]; + if (a === _1) return Integer[1]; + if (a === BigInt(-1)) return n.isEven() ? Integer[1] : Integer[-1]; + if (n.isNegative()) return new NativeBigInt(_0); + var x = this; + var y = Integer[1]; + while (true) { + if ((b & _1) === _1) { + y = y.times(x); + --b; + } + if (b === _0) break; + b /= _2; + x = x.square(); + } + return y; + }; + + BigInteger.prototype.modPow = function (exp, mod) { + exp = parseValue(exp); + mod = parseValue(mod); + if (mod.isZero()) throw new Error("Cannot take modPow with modulus 0"); + var r = Integer[1], + base = this.mod(mod); + if (exp.isNegative()) { + exp = exp.multiply(Integer[-1]); + base = base.modInv(mod); + } + while (exp.isPositive()) { + if (base.isZero()) return Integer[0]; + if (exp.isOdd()) r = r.multiply(base).mod(mod); + exp = exp.divide(2); + base = base.square().mod(mod); + } + return r; + }; + NativeBigInt.prototype.modPow = SmallInteger.prototype.modPow = BigInteger.prototype.modPow; + + function compareAbs(a, b) { + if (a.length !== b.length) { + return a.length > b.length ? 1 : -1; + } + for (var i = a.length - 1; i >= 0; i--) { + if (a[i] !== b[i]) return a[i] > b[i] ? 1 : -1; + } + return 0; + } + + BigInteger.prototype.compareAbs = function (v) { + var n = parseValue(v), + a = this.value, + b = n.value; + if (n.isSmall) return 1; + return compareAbs(a, b); + }; + SmallInteger.prototype.compareAbs = function (v) { + var n = parseValue(v), + a = Math.abs(this.value), + b = n.value; + if (n.isSmall) { + b = Math.abs(b); + return a === b ? 0 : a > b ? 1 : -1; + } + return -1; + }; + NativeBigInt.prototype.compareAbs = function (v) { + var a = this.value; + var b = parseValue(v).value; + a = a >= 0 ? a : -a; + b = b >= 0 ? b : -b; + return a === b ? 0 : a > b ? 1 : -1; + }; + + BigInteger.prototype.compare = function (v) { + // See discussion about comparison with Infinity: + // https://github.com/peterolson/BigInteger.js/issues/61 + if (v === Infinity) { + return -1; + } + if (v === -Infinity) { + return 1; + } + + var n = parseValue(v), + a = this.value, + b = n.value; + if (this.sign !== n.sign) { + return n.sign ? 1 : -1; + } + if (n.isSmall) { + return this.sign ? -1 : 1; + } + return compareAbs(a, b) * (this.sign ? -1 : 1); + }; + BigInteger.prototype.compareTo = BigInteger.prototype.compare; + + SmallInteger.prototype.compare = function (v) { + if (v === Infinity) { + return -1; + } + if (v === -Infinity) { + return 1; + } + + var n = parseValue(v), + a = this.value, + b = n.value; + if (n.isSmall) { + return a == b ? 0 : a > b ? 1 : -1; + } + if (a < 0 !== n.sign) { + return a < 0 ? -1 : 1; + } + return a < 0 ? 1 : -1; + }; + SmallInteger.prototype.compareTo = SmallInteger.prototype.compare; + + NativeBigInt.prototype.compare = function (v) { + if (v === Infinity) { + return -1; + } + if (v === -Infinity) { + return 1; + } + var a = this.value; + var b = parseValue(v).value; + return a === b ? 0 : a > b ? 1 : -1; + }; + NativeBigInt.prototype.compareTo = NativeBigInt.prototype.compare; + + BigInteger.prototype.equals = function (v) { + return this.compare(v) === 0; + }; + NativeBigInt.prototype.eq = NativeBigInt.prototype.equals = SmallInteger.prototype.eq = SmallInteger.prototype.equals = BigInteger.prototype.eq = BigInteger.prototype.equals; + + BigInteger.prototype.notEquals = function (v) { + return this.compare(v) !== 0; + }; + NativeBigInt.prototype.neq = NativeBigInt.prototype.notEquals = SmallInteger.prototype.neq = SmallInteger.prototype.notEquals = BigInteger.prototype.neq = BigInteger.prototype.notEquals; + + BigInteger.prototype.greater = function (v) { + return this.compare(v) > 0; + }; + NativeBigInt.prototype.gt = NativeBigInt.prototype.greater = SmallInteger.prototype.gt = SmallInteger.prototype.greater = BigInteger.prototype.gt = BigInteger.prototype.greater; + + BigInteger.prototype.lesser = function (v) { + return this.compare(v) < 0; + }; + NativeBigInt.prototype.lt = NativeBigInt.prototype.lesser = SmallInteger.prototype.lt = SmallInteger.prototype.lesser = BigInteger.prototype.lt = BigInteger.prototype.lesser; + + BigInteger.prototype.greaterOrEquals = function (v) { + return this.compare(v) >= 0; + }; + NativeBigInt.prototype.geq = NativeBigInt.prototype.greaterOrEquals = SmallInteger.prototype.geq = SmallInteger.prototype.greaterOrEquals = BigInteger.prototype.geq = BigInteger.prototype.greaterOrEquals; + + BigInteger.prototype.lesserOrEquals = function (v) { + return this.compare(v) <= 0; + }; + NativeBigInt.prototype.leq = NativeBigInt.prototype.lesserOrEquals = SmallInteger.prototype.leq = SmallInteger.prototype.lesserOrEquals = BigInteger.prototype.leq = BigInteger.prototype.lesserOrEquals; + + BigInteger.prototype.isEven = function () { + return (this.value[0] & 1) === 0; + }; + SmallInteger.prototype.isEven = function () { + return (this.value & 1) === 0; + }; + NativeBigInt.prototype.isEven = function () { + return (this.value & BigInt(1)) === BigInt(0); + }; + + BigInteger.prototype.isOdd = function () { + return (this.value[0] & 1) === 1; + }; + SmallInteger.prototype.isOdd = function () { + return (this.value & 1) === 1; + }; + NativeBigInt.prototype.isOdd = function () { + return (this.value & BigInt(1)) === BigInt(1); + }; + + BigInteger.prototype.isPositive = function () { + return !this.sign; + }; + SmallInteger.prototype.isPositive = function () { + return this.value > 0; + }; + NativeBigInt.prototype.isPositive = SmallInteger.prototype.isPositive; + + BigInteger.prototype.isNegative = function () { + return this.sign; + }; + SmallInteger.prototype.isNegative = function () { + return this.value < 0; + }; + NativeBigInt.prototype.isNegative = SmallInteger.prototype.isNegative; + + BigInteger.prototype.isUnit = function () { + return false; + }; + SmallInteger.prototype.isUnit = function () { + return Math.abs(this.value) === 1; + }; + NativeBigInt.prototype.isUnit = function () { + return this.abs().value === BigInt(1); + }; + + BigInteger.prototype.isZero = function () { + return false; + }; + SmallInteger.prototype.isZero = function () { + return this.value === 0; + }; + NativeBigInt.prototype.isZero = function () { + return this.value === BigInt(0); + }; + + BigInteger.prototype.isDivisibleBy = function (v) { + var n = parseValue(v); + if (n.isZero()) return false; + if (n.isUnit()) return true; + if (n.compareAbs(2) === 0) return this.isEven(); + return this.mod(n).isZero(); + }; + NativeBigInt.prototype.isDivisibleBy = SmallInteger.prototype.isDivisibleBy = BigInteger.prototype.isDivisibleBy; + + function isBasicPrime(v) { + var n = v.abs(); + if (n.isUnit()) return false; + if (n.equals(2) || n.equals(3) || n.equals(5)) return true; + if (n.isEven() || n.isDivisibleBy(3) || n.isDivisibleBy(5)) return false; + if (n.lesser(49)) return true; + // we don't know if it's prime: let the other functions figure it out + } + + function millerRabinTest(n, a) { + var nPrev = n.prev(), + b = nPrev, + r = 0, + d, i, x; + while (b.isEven()) b = b.divide(2), r++; + next: for (i = 0; i < a.length; i++) { + if (n.lesser(a[i])) continue; + x = bigInt(a[i]).modPow(b, n); + if (x.isUnit() || x.equals(nPrev)) continue; + for (d = r - 1; d != 0; d--) { + x = x.square().mod(n); + if (x.isUnit()) return false; + if (x.equals(nPrev)) continue next; + } + return false; + } + return true; + } + + // Set "strict" to true to force GRH-supported lower bound of 2*log(N)^2 + BigInteger.prototype.isPrime = function (strict) { + var isPrime = isBasicPrime(this); + if (isPrime !== undefined$1) return isPrime; + var n = this.abs(); + var bits = n.bitLength(); + if (bits <= 64) + return millerRabinTest(n, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]); + var logN = Math.log(2) * bits.toJSNumber(); + var t = Math.ceil((strict === true) ? (2 * Math.pow(logN, 2)) : logN); + for (var a = [], i = 0; i < t; i++) { + a.push(bigInt(i + 2)); + } + return millerRabinTest(n, a); + }; + NativeBigInt.prototype.isPrime = SmallInteger.prototype.isPrime = BigInteger.prototype.isPrime; + + BigInteger.prototype.isProbablePrime = function (iterations, rng) { + var isPrime = isBasicPrime(this); + if (isPrime !== undefined$1) return isPrime; + var n = this.abs(); + var t = iterations === undefined$1 ? 5 : iterations; + for (var a = [], i = 0; i < t; i++) { + a.push(bigInt.randBetween(2, n.minus(2), rng)); + } + return millerRabinTest(n, a); + }; + NativeBigInt.prototype.isProbablePrime = SmallInteger.prototype.isProbablePrime = BigInteger.prototype.isProbablePrime; + + BigInteger.prototype.modInv = function (n) { + var t = bigInt.zero, newT = bigInt.one, r = parseValue(n), newR = this.abs(), q, lastT, lastR; + while (!newR.isZero()) { + q = r.divide(newR); + lastT = t; + lastR = r; + t = newT; + r = newR; + newT = lastT.subtract(q.multiply(newT)); + newR = lastR.subtract(q.multiply(newR)); + } + if (!r.isUnit()) throw new Error(this.toString() + " and " + n.toString() + " are not co-prime"); + if (t.compare(0) === -1) { + t = t.add(n); + } + if (this.isNegative()) { + return t.negate(); + } + return t; + }; + + NativeBigInt.prototype.modInv = SmallInteger.prototype.modInv = BigInteger.prototype.modInv; + + BigInteger.prototype.next = function () { + var value = this.value; + if (this.sign) { + return subtractSmall(value, 1, this.sign); + } + return new BigInteger(addSmall(value, 1), this.sign); + }; + SmallInteger.prototype.next = function () { + var value = this.value; + if (value + 1 < MAX_INT) return new SmallInteger(value + 1); + return new BigInteger(MAX_INT_ARR, false); + }; + NativeBigInt.prototype.next = function () { + return new NativeBigInt(this.value + BigInt(1)); + }; + + BigInteger.prototype.prev = function () { + var value = this.value; + if (this.sign) { + return new BigInteger(addSmall(value, 1), true); + } + return subtractSmall(value, 1, this.sign); + }; + SmallInteger.prototype.prev = function () { + var value = this.value; + if (value - 1 > -MAX_INT) return new SmallInteger(value - 1); + return new BigInteger(MAX_INT_ARR, true); + }; + NativeBigInt.prototype.prev = function () { + return new NativeBigInt(this.value - BigInt(1)); + }; + + var powersOfTwo = [1]; + while (2 * powersOfTwo[powersOfTwo.length - 1] <= BASE) powersOfTwo.push(2 * powersOfTwo[powersOfTwo.length - 1]); + var powers2Length = powersOfTwo.length, highestPower2 = powersOfTwo[powers2Length - 1]; + + function shift_isSmall(n) { + return Math.abs(n) <= BASE; + } + + BigInteger.prototype.shiftLeft = function (v) { + var n = parseValue(v).toJSNumber(); + if (!shift_isSmall(n)) { + throw new Error(String(n) + " is too large for shifting."); + } + if (n < 0) return this.shiftRight(-n); + var result = this; + if (result.isZero()) return result; + while (n >= powers2Length) { + result = result.multiply(highestPower2); + n -= powers2Length - 1; + } + return result.multiply(powersOfTwo[n]); + }; + NativeBigInt.prototype.shiftLeft = SmallInteger.prototype.shiftLeft = BigInteger.prototype.shiftLeft; + + BigInteger.prototype.shiftRight = function (v) { + var remQuo; + var n = parseValue(v).toJSNumber(); + if (!shift_isSmall(n)) { + throw new Error(String(n) + " is too large for shifting."); + } + if (n < 0) return this.shiftLeft(-n); + var result = this; + while (n >= powers2Length) { + if (result.isZero() || (result.isNegative() && result.isUnit())) return result; + remQuo = divModAny(result, highestPower2); + result = remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0]; + n -= powers2Length - 1; + } + remQuo = divModAny(result, powersOfTwo[n]); + return remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0]; + }; + NativeBigInt.prototype.shiftRight = SmallInteger.prototype.shiftRight = BigInteger.prototype.shiftRight; + + function bitwise(x, y, fn) { + y = parseValue(y); + var xSign = x.isNegative(), ySign = y.isNegative(); + var xRem = xSign ? x.not() : x, + yRem = ySign ? y.not() : y; + var xDigit = 0, yDigit = 0; + var xDivMod = null, yDivMod = null; + var result = []; + while (!xRem.isZero() || !yRem.isZero()) { + xDivMod = divModAny(xRem, highestPower2); + xDigit = xDivMod[1].toJSNumber(); + if (xSign) { + xDigit = highestPower2 - 1 - xDigit; // two's complement for negative numbers + } + + yDivMod = divModAny(yRem, highestPower2); + yDigit = yDivMod[1].toJSNumber(); + if (ySign) { + yDigit = highestPower2 - 1 - yDigit; // two's complement for negative numbers + } + + xRem = xDivMod[0]; + yRem = yDivMod[0]; + result.push(fn(xDigit, yDigit)); + } + var sum = fn(xSign ? 1 : 0, ySign ? 1 : 0) !== 0 ? bigInt(-1) : bigInt(0); + for (var i = result.length - 1; i >= 0; i -= 1) { + sum = sum.multiply(highestPower2).add(bigInt(result[i])); + } + return sum; + } + + BigInteger.prototype.not = function () { + return this.negate().prev(); + }; + NativeBigInt.prototype.not = SmallInteger.prototype.not = BigInteger.prototype.not; + + BigInteger.prototype.and = function (n) { + return bitwise(this, n, function (a, b) { return a & b; }); + }; + NativeBigInt.prototype.and = SmallInteger.prototype.and = BigInteger.prototype.and; + + BigInteger.prototype.or = function (n) { + return bitwise(this, n, function (a, b) { return a | b; }); + }; + NativeBigInt.prototype.or = SmallInteger.prototype.or = BigInteger.prototype.or; + + BigInteger.prototype.xor = function (n) { + return bitwise(this, n, function (a, b) { return a ^ b; }); + }; + NativeBigInt.prototype.xor = SmallInteger.prototype.xor = BigInteger.prototype.xor; + + var LOBMASK_I = 1 << 30, LOBMASK_BI = (BASE & -BASE) * (BASE & -BASE) | LOBMASK_I; + function roughLOB(n) { // get lowestOneBit (rough) + // SmallInteger: return Min(lowestOneBit(n), 1 << 30) + // BigInteger: return Min(lowestOneBit(n), 1 << 14) [BASE=1e7] + var v = n.value, + x = typeof v === "number" ? v | LOBMASK_I : + typeof v === "bigint" ? v | BigInt(LOBMASK_I) : + v[0] + v[1] * BASE | LOBMASK_BI; + return x & -x; + } + + function integerLogarithm(value, base) { + if (base.compareTo(value) <= 0) { + var tmp = integerLogarithm(value, base.square(base)); + var p = tmp.p; + var e = tmp.e; + var t = p.multiply(base); + return t.compareTo(value) <= 0 ? { p: t, e: e * 2 + 1 } : { p: p, e: e * 2 }; + } + return { p: bigInt(1), e: 0 }; + } + + BigInteger.prototype.bitLength = function () { + var n = this; + if (n.compareTo(bigInt(0)) < 0) { + n = n.negate().subtract(bigInt(1)); + } + if (n.compareTo(bigInt(0)) === 0) { + return bigInt(0); + } + return bigInt(integerLogarithm(n, bigInt(2)).e).add(bigInt(1)); + }; + NativeBigInt.prototype.bitLength = SmallInteger.prototype.bitLength = BigInteger.prototype.bitLength; + + function max(a, b) { + a = parseValue(a); + b = parseValue(b); + return a.greater(b) ? a : b; + } + function min(a, b) { + a = parseValue(a); + b = parseValue(b); + return a.lesser(b) ? a : b; + } + function gcd(a, b) { + a = parseValue(a).abs(); + b = parseValue(b).abs(); + if (a.equals(b)) return a; + if (a.isZero()) return b; + if (b.isZero()) return a; + var c = Integer[1], d, t; + while (a.isEven() && b.isEven()) { + d = min(roughLOB(a), roughLOB(b)); + a = a.divide(d); + b = b.divide(d); + c = c.multiply(d); + } + while (a.isEven()) { + a = a.divide(roughLOB(a)); + } + do { + while (b.isEven()) { + b = b.divide(roughLOB(b)); + } + if (a.greater(b)) { + t = b; b = a; a = t; + } + b = b.subtract(a); + } while (!b.isZero()); + return c.isUnit() ? a : a.multiply(c); + } + function lcm(a, b) { + a = parseValue(a).abs(); + b = parseValue(b).abs(); + return a.divide(gcd(a, b)).multiply(b); + } + function randBetween(a, b, rng) { + a = parseValue(a); + b = parseValue(b); + var usedRNG = rng || Math.random; + var low = min(a, b), high = max(a, b); + var range = high.subtract(low).add(1); + if (range.isSmall) return low.add(Math.floor(usedRNG() * range)); + var digits = toBase(range, BASE).value; + var result = [], restricted = true; + for (var i = 0; i < digits.length; i++) { + var top = restricted ? digits[i] + (i + 1 < digits.length ? digits[i + 1] / BASE : 0) : BASE; + var digit = truncate(usedRNG() * top); + result.push(digit); + if (digit < digits[i]) restricted = false; + } + return low.add(Integer.fromArray(result, BASE, false)); + } + + var parseBase = function (text, base, alphabet, caseSensitive) { + alphabet = alphabet || DEFAULT_ALPHABET; + text = String(text); + if (!caseSensitive) { + text = text.toLowerCase(); + alphabet = alphabet.toLowerCase(); + } + var length = text.length; + var i; + var absBase = Math.abs(base); + var alphabetValues = {}; + for (i = 0; i < alphabet.length; i++) { + alphabetValues[alphabet[i]] = i; + } + for (i = 0; i < length; i++) { + var c = text[i]; + if (c === "-") continue; + if (c in alphabetValues) { + if (alphabetValues[c] >= absBase) { + if (c === "1" && absBase === 1) continue; + throw new Error(c + " is not a valid digit in base " + base + "."); + } + } + } + base = parseValue(base); + var digits = []; + var isNegative = text[0] === "-"; + for (i = isNegative ? 1 : 0; i < text.length; i++) { + var c = text[i]; + if (c in alphabetValues) digits.push(parseValue(alphabetValues[c])); + else if (c === "<") { + var start = i; + do { i++; } while (text[i] !== ">" && i < text.length); + digits.push(parseValue(text.slice(start + 1, i))); + } + else throw new Error(c + " is not a valid character"); + } + return parseBaseFromArray(digits, base, isNegative); + }; + + function parseBaseFromArray(digits, base, isNegative) { + var val = Integer[0], pow = Integer[1], i; + for (i = digits.length - 1; i >= 0; i--) { + val = val.add(digits[i].times(pow)); + pow = pow.times(base); + } + return isNegative ? val.negate() : val; + } + + function stringify(digit, alphabet) { + alphabet = alphabet || DEFAULT_ALPHABET; + if (digit < alphabet.length) { + return alphabet[digit]; + } + return "<" + digit + ">"; + } + + function toBase(n, base) { + base = bigInt(base); + if (base.isZero()) { + if (n.isZero()) return { value: [0], isNegative: false }; + throw new Error("Cannot convert nonzero numbers to base 0."); + } + if (base.equals(-1)) { + if (n.isZero()) return { value: [0], isNegative: false }; + if (n.isNegative()) + return { + value: [].concat.apply([], Array.apply(null, Array(-n.toJSNumber())) + .map(Array.prototype.valueOf, [1, 0]) + ), + isNegative: false + }; + + var arr = Array.apply(null, Array(n.toJSNumber() - 1)) + .map(Array.prototype.valueOf, [0, 1]); + arr.unshift([1]); + return { + value: [].concat.apply([], arr), + isNegative: false + }; + } + + var neg = false; + if (n.isNegative() && base.isPositive()) { + neg = true; + n = n.abs(); + } + if (base.isUnit()) { + if (n.isZero()) return { value: [0], isNegative: false }; + + return { + value: Array.apply(null, Array(n.toJSNumber())) + .map(Number.prototype.valueOf, 1), + isNegative: neg + }; + } + var out = []; + var left = n, divmod; + while (left.isNegative() || left.compareAbs(base) >= 0) { + divmod = left.divmod(base); + left = divmod.quotient; + var digit = divmod.remainder; + if (digit.isNegative()) { + digit = base.minus(digit).abs(); + left = left.next(); + } + out.push(digit.toJSNumber()); + } + out.push(left.toJSNumber()); + return { value: out.reverse(), isNegative: neg }; + } + + function toBaseString(n, base, alphabet) { + var arr = toBase(n, base); + return (arr.isNegative ? "-" : "") + arr.value.map(function (x) { + return stringify(x, alphabet); + }).join(''); + } + + BigInteger.prototype.toArray = function (radix) { + return toBase(this, radix); + }; + + SmallInteger.prototype.toArray = function (radix) { + return toBase(this, radix); + }; + + NativeBigInt.prototype.toArray = function (radix) { + return toBase(this, radix); + }; + + BigInteger.prototype.toString = function (radix, alphabet) { + if (radix === undefined$1) radix = 10; + if (radix !== 10) return toBaseString(this, radix, alphabet); + var v = this.value, l = v.length, str = String(v[--l]), zeros = "0000000", digit; + while (--l >= 0) { + digit = String(v[l]); + str += zeros.slice(digit.length) + digit; + } + var sign = this.sign ? "-" : ""; + return sign + str; + }; + + SmallInteger.prototype.toString = function (radix, alphabet) { + if (radix === undefined$1) radix = 10; + if (radix != 10) return toBaseString(this, radix, alphabet); + return String(this.value); + }; + + NativeBigInt.prototype.toString = SmallInteger.prototype.toString; + + NativeBigInt.prototype.toJSON = BigInteger.prototype.toJSON = SmallInteger.prototype.toJSON = function () { return this.toString(); }; + + BigInteger.prototype.valueOf = function () { + return parseInt(this.toString(), 10); + }; + BigInteger.prototype.toJSNumber = BigInteger.prototype.valueOf; + + SmallInteger.prototype.valueOf = function () { + return this.value; + }; + SmallInteger.prototype.toJSNumber = SmallInteger.prototype.valueOf; + NativeBigInt.prototype.valueOf = NativeBigInt.prototype.toJSNumber = function () { + return parseInt(this.toString(), 10); + }; + + function parseStringValue(v) { + if (isPrecise(+v)) { + var x = +v; + if (x === truncate(x)) + return supportsNativeBigInt ? new NativeBigInt(BigInt(x)) : new SmallInteger(x); + throw new Error("Invalid integer: " + v); + } + var sign = v[0] === "-"; + if (sign) v = v.slice(1); + var split = v.split(/e/i); + if (split.length > 2) throw new Error("Invalid integer: " + split.join("e")); + if (split.length === 2) { + var exp = split[1]; + if (exp[0] === "+") exp = exp.slice(1); + exp = +exp; + if (exp !== truncate(exp) || !isPrecise(exp)) throw new Error("Invalid integer: " + exp + " is not a valid exponent."); + var text = split[0]; + var decimalPlace = text.indexOf("."); + if (decimalPlace >= 0) { + exp -= text.length - decimalPlace - 1; + text = text.slice(0, decimalPlace) + text.slice(decimalPlace + 1); + } + if (exp < 0) throw new Error("Cannot include negative exponent part for integers"); + text += (new Array(exp + 1)).join("0"); + v = text; + } + var isValid = /^([0-9][0-9]*)$/.test(v); + if (!isValid) throw new Error("Invalid integer: " + v); + if (supportsNativeBigInt) { + return new NativeBigInt(BigInt(sign ? "-" + v : v)); + } + var r = [], max = v.length, l = LOG_BASE, min = max - l; + while (max > 0) { + r.push(+v.slice(min, max)); + min -= l; + if (min < 0) min = 0; + max -= l; + } + trim(r); + return new BigInteger(r, sign); + } + + function parseNumberValue(v) { + if (supportsNativeBigInt) { + return new NativeBigInt(BigInt(v)); + } + if (isPrecise(v)) { + if (v !== truncate(v)) throw new Error(v + " is not an integer."); + return new SmallInteger(v); + } + return parseStringValue(v.toString()); + } + + function parseValue(v) { + if (typeof v === "number") { + return parseNumberValue(v); + } + if (typeof v === "string") { + return parseStringValue(v); + } + if (typeof v === "bigint") { + return new NativeBigInt(v); + } + return v; + } + // Pre-define numbers in range [-999,999] + for (var i = 0; i < 1000; i++) { + Integer[i] = parseValue(i); + if (i > 0) Integer[-i] = parseValue(-i); + } + // Backwards compatibility + Integer.one = Integer[1]; + Integer.zero = Integer[0]; + Integer.minusOne = Integer[-1]; + Integer.max = max; + Integer.min = min; + Integer.gcd = gcd; + Integer.lcm = lcm; + Integer.isInstance = function (x) { return x instanceof BigInteger || x instanceof SmallInteger || x instanceof NativeBigInt; }; + Integer.randBetween = randBetween; + + Integer.fromArray = function (digits, base, isNegative) { + return parseBaseFromArray(digits.map(parseValue), parseValue(base || 10), isNegative); + }; + + return Integer; + })(); + + // Node.js check + if (module.hasOwnProperty("exports")) { + module.exports = bigInt; + } +} (BigInteger)); + +var BigIntegerExports = BigInteger.exports; + +(function (exports) { + + // adapted from http://code.google.com/p/plist/source/browse/trunk/src/com/dd/plist/BinaryPropertyListParser.java + + const fs = require$$0$8; + const bigInt = BigIntegerExports; + + exports.maxObjectSize = 100 * 1000 * 1000; // 100Meg + exports.maxObjectCount = 32768; + + // EPOCH = new SimpleDateFormat("yyyy MM dd zzz").parse("2001 01 01 GMT").getTime(); + // ...but that's annoying in a static initializer because it can throw exceptions, ick. + // So we just hardcode the correct value. + const EPOCH = 978307200000; + + // UID object definition + const UID = exports.UID = function(id) { + this.UID = id; + }; + + exports.parseFile = function (fileNameOrBuffer, callback) { + return new Promise(function (resolve, reject) { + function tryParseBuffer(buffer) { + let err = null; + let result; + try { + result = parseBuffer(buffer); + resolve(result); + } catch (ex) { + err = ex; + reject(err); + } finally { + if (callback) callback(err, result); + } + } + + if (Buffer.isBuffer(fileNameOrBuffer)) { + return tryParseBuffer(fileNameOrBuffer); + } + fs.readFile(fileNameOrBuffer, function (err, data) { + if (err) { + reject(err); + return callback(err); + } + tryParseBuffer(data); + }); + }); + }; + + const parseBuffer = exports.parseBuffer = function (buffer) { + // check header + const header = buffer.slice(0, 'bplist'.length).toString('utf8'); + if (header !== 'bplist') { + throw new Error("Invalid binary plist. Expected 'bplist' at offset 0."); + } + + // Handle trailer, last 32 bytes of the file + const trailer = buffer.slice(buffer.length - 32, buffer.length); + // 6 null bytes (index 0 to 5) + const offsetSize = trailer.readUInt8(6); + const objectRefSize = trailer.readUInt8(7); + const numObjects = readUInt64BE(trailer, 8); + const topObject = readUInt64BE(trailer, 16); + const offsetTableOffset = readUInt64BE(trailer, 24); + + if (numObjects > exports.maxObjectCount) { + throw new Error("maxObjectCount exceeded"); + } + + // Handle offset table + const offsetTable = []; + + for (let i = 0; i < numObjects; i++) { + const offsetBytes = buffer.slice(offsetTableOffset + i * offsetSize, offsetTableOffset + (i + 1) * offsetSize); + offsetTable[i] = readUInt(offsetBytes, 0); + } + + // Parses an object inside the currently parsed binary property list. + // For the format specification check + // <a href="http://www.opensource.apple.com/source/CF/CF-635/CFBinaryPList.c"> + // Apple's binary property list parser implementation</a>. + function parseObject(tableOffset) { + const offset = offsetTable[tableOffset]; + const type = buffer[offset]; + const objType = (type & 0xF0) >> 4; //First 4 bits + const objInfo = (type & 0x0F); //Second 4 bits + switch (objType) { + case 0x0: + return parseSimple(); + case 0x1: + return parseInteger(); + case 0x8: + return parseUID(); + case 0x2: + return parseReal(); + case 0x3: + return parseDate(); + case 0x4: + return parseData(); + case 0x5: // ASCII + return parsePlistString(); + case 0x6: // UTF-16 + return parsePlistString(true); + case 0xA: + return parseArray(); + case 0xD: + return parseDictionary(); + default: + throw new Error("Unhandled type 0x" + objType.toString(16)); + } + + function parseSimple() { + //Simple + switch (objInfo) { + case 0x0: // null + return null; + case 0x8: // false + return false; + case 0x9: // true + return true; + case 0xF: // filler byte + return null; + default: + throw new Error("Unhandled simple type 0x" + objType.toString(16)); + } + } + + function bufferToHexString(buffer) { + let str = ''; + let i; + for (i = 0; i < buffer.length; i++) { + if (buffer[i] != 0x00) { + break; + } + } + for (; i < buffer.length; i++) { + const part = '00' + buffer[i].toString(16); + str += part.substr(part.length - 2); + } + return str; + } + + function parseInteger() { + const length = Math.pow(2, objInfo); + + if (objInfo == 0x4) { + const data = buffer.slice(offset + 1, offset + 1 + length); + const str = bufferToHexString(data); + return bigInt(str, 16); + } + if (objInfo == 0x3) { + return buffer.readInt32BE(offset + 1); + } + if (length < exports.maxObjectSize) { + return readUInt(buffer.slice(offset + 1, offset + 1 + length)); + } + throw new Error("To little heap space available! Wanted to read " + length + " bytes, but only " + exports.maxObjectSize + " are available."); + } + + function parseUID() { + const length = objInfo + 1; + if (length < exports.maxObjectSize) { + return new UID(readUInt(buffer.slice(offset + 1, offset + 1 + length))); + } + throw new Error("To little heap space available! Wanted to read " + length + " bytes, but only " + exports.maxObjectSize + " are available."); + } + + function parseReal() { + const length = Math.pow(2, objInfo); + if (length < exports.maxObjectSize) { + const realBuffer = buffer.slice(offset + 1, offset + 1 + length); + if (length === 4) { + return realBuffer.readFloatBE(0); + } + if (length === 8) { + return realBuffer.readDoubleBE(0); + } + } else { + throw new Error("To little heap space available! Wanted to read " + length + " bytes, but only " + exports.maxObjectSize + " are available."); + } + } + + function parseDate() { + if (objInfo != 0x3) { + console.error("Unknown date type :" + objInfo + ". Parsing anyway..."); + } + const dateBuffer = buffer.slice(offset + 1, offset + 9); + return new Date(EPOCH + (1000 * dateBuffer.readDoubleBE(0))); + } + + function parseData() { + let dataoffset = 1; + let length = objInfo; + if (objInfo == 0xF) { + const int_type = buffer[offset + 1]; + const intType = (int_type & 0xF0) / 0x10; + if (intType != 0x1) { + console.error("0x4: UNEXPECTED LENGTH-INT TYPE! " + intType); + } + const intInfo = int_type & 0x0F; + const intLength = Math.pow(2, intInfo); + dataoffset = 2 + intLength; + if (intLength < 3) { + length = readUInt(buffer.slice(offset + 2, offset + 2 + intLength)); + } else { + length = readUInt(buffer.slice(offset + 2, offset + 2 + intLength)); + } + } + if (length < exports.maxObjectSize) { + return buffer.slice(offset + dataoffset, offset + dataoffset + length); + } + throw new Error("To little heap space available! Wanted to read " + length + " bytes, but only " + exports.maxObjectSize + " are available."); + } + + function parsePlistString (isUtf16) { + isUtf16 = isUtf16 || 0; + let enc = "utf8"; + let length = objInfo; + let stroffset = 1; + if (objInfo == 0xF) { + const int_type = buffer[offset + 1]; + const intType = (int_type & 0xF0) / 0x10; + if (intType != 0x1) { + console.err("UNEXPECTED LENGTH-INT TYPE! " + intType); + } + const intInfo = int_type & 0x0F; + const intLength = Math.pow(2, intInfo); + stroffset = 2 + intLength; + if (intLength < 3) { + length = readUInt(buffer.slice(offset + 2, offset + 2 + intLength)); + } else { + length = readUInt(buffer.slice(offset + 2, offset + 2 + intLength)); + } + } + // length is String length -> to get byte length multiply by 2, as 1 character takes 2 bytes in UTF-16 + length *= (isUtf16 + 1); + if (length < exports.maxObjectSize) { + let plistString = Buffer.from(buffer.slice(offset + stroffset, offset + stroffset + length)); + if (isUtf16) { + plistString = swapBytes(plistString); + enc = "ucs2"; + } + return plistString.toString(enc); + } + throw new Error("To little heap space available! Wanted to read " + length + " bytes, but only " + exports.maxObjectSize + " are available."); + } + + function parseArray() { + let length = objInfo; + let arrayoffset = 1; + if (objInfo == 0xF) { + const int_type = buffer[offset + 1]; + const intType = (int_type & 0xF0) / 0x10; + if (intType != 0x1) { + console.error("0xa: UNEXPECTED LENGTH-INT TYPE! " + intType); + } + const intInfo = int_type & 0x0F; + const intLength = Math.pow(2, intInfo); + arrayoffset = 2 + intLength; + if (intLength < 3) { + length = readUInt(buffer.slice(offset + 2, offset + 2 + intLength)); + } else { + length = readUInt(buffer.slice(offset + 2, offset + 2 + intLength)); + } + } + if (length * objectRefSize > exports.maxObjectSize) { + throw new Error("To little heap space available!"); + } + const array = []; + for (let i = 0; i < length; i++) { + const objRef = readUInt(buffer.slice(offset + arrayoffset + i * objectRefSize, offset + arrayoffset + (i + 1) * objectRefSize)); + array[i] = parseObject(objRef); + } + return array; + } + + function parseDictionary() { + let length = objInfo; + let dictoffset = 1; + if (objInfo == 0xF) { + const int_type = buffer[offset + 1]; + const intType = (int_type & 0xF0) / 0x10; + if (intType != 0x1) { + console.error("0xD: UNEXPECTED LENGTH-INT TYPE! " + intType); + } + const intInfo = int_type & 0x0F; + const intLength = Math.pow(2, intInfo); + dictoffset = 2 + intLength; + if (intLength < 3) { + length = readUInt(buffer.slice(offset + 2, offset + 2 + intLength)); + } else { + length = readUInt(buffer.slice(offset + 2, offset + 2 + intLength)); + } + } + if (length * 2 * objectRefSize > exports.maxObjectSize) { + throw new Error("To little heap space available!"); + } + const dict = {}; + for (let i = 0; i < length; i++) { + const keyRef = readUInt(buffer.slice(offset + dictoffset + i * objectRefSize, offset + dictoffset + (i + 1) * objectRefSize)); + const valRef = readUInt(buffer.slice(offset + dictoffset + (length * objectRefSize) + i * objectRefSize, offset + dictoffset + (length * objectRefSize) + (i + 1) * objectRefSize)); + const key = parseObject(keyRef); + const val = parseObject(valRef); + dict[key] = val; + } + return dict; + } + } + + return [ parseObject(topObject) ]; + }; + + function readUInt(buffer, start) { + start = start || 0; + + let l = 0; + for (let i = start; i < buffer.length; i++) { + l <<= 8; + l |= buffer[i] & 0xFF; + } + return l; + } + + // we're just going to toss the high order bits because javascript doesn't have 64-bit ints + function readUInt64BE(buffer, start) { + const data = buffer.slice(start, start + 8); + return data.readUInt32BE(4, 8); + } + + function swapBytes(buffer) { + const len = buffer.length; + for (let i = 0; i < len; i += 2) { + const a = buffer[i]; + buffer[i] = buffer[i+1]; + buffer[i+1] = a; + } + return buffer; + } +} (bplistParser)); + +var bplist = /*@__PURE__*/getDefaultExportFromCjs(bplistParser); + +const os$1 = require$$0$7; + +const homeDirectory = os$1.homedir(); + +var untildify = pathWithTilde => { + if (typeof pathWithTilde !== 'string') { + throw new TypeError(`Expected a string, got ${typeof pathWithTilde}`); + } + + return homeDirectory ? pathWithTilde.replace(/^~(?=$|\/|\\)/, homeDirectory) : pathWithTilde; +}; + +var untildify$1 = /*@__PURE__*/getDefaultExportFromCjs(untildify); + +const macOsVersion = Number(require$$0$7.release().split('.')[0]); +const filePath = untildify$1(macOsVersion >= 14 ? '~/Library/Preferences/com.apple.LaunchServices/com.apple.launchservices.secure.plist' : '~/Library/Preferences/com.apple.LaunchServices.plist'); + +async function defaultBrowserId() { + if (process.platform !== 'darwin') { + throw new Error('macOS only'); + } + + let bundleId = 'com.apple.Safari'; + + let buffer; + try { + buffer = await require$$0$8.promises.readFile(filePath); + } catch (error) { + if (error.code === 'ENOENT') { + return bundleId; + } + + throw error; + } + + const data = bplist.parseBuffer(buffer); + const handlers = data && data[0].LSHandlers; + + if (!handlers || handlers.length === 0) { + return bundleId; + } + + for (const handler of handlers) { + if (handler.LSHandlerURLScheme === 'http' && handler.LSHandlerRoleAll) { + bundleId = handler.LSHandlerRoleAll; + break; + } + } + + return bundleId; +} + +var execa$3 = {exports: {}}; + +var crossSpawn$2 = {exports: {}}; + +var windows; +var hasRequiredWindows; + +function requireWindows () { + if (hasRequiredWindows) return windows; + hasRequiredWindows = 1; + windows = isexe; + isexe.sync = sync; + + var fs = require$$0$8; + + function checkPathExt (path, options) { + var pathext = options.pathExt !== undefined ? + options.pathExt : process.env.PATHEXT; + + if (!pathext) { + return true + } + + pathext = pathext.split(';'); + if (pathext.indexOf('') !== -1) { + return true + } + for (var i = 0; i < pathext.length; i++) { + var p = pathext[i].toLowerCase(); + if (p && path.substr(-p.length).toLowerCase() === p) { + return true + } + } + return false + } + + function checkStat (stat, path, options) { + if (!stat.isSymbolicLink() && !stat.isFile()) { + return false + } + return checkPathExt(path, options) + } + + function isexe (path, options, cb) { + fs.stat(path, function (er, stat) { + cb(er, er ? false : checkStat(stat, path, options)); + }); + } + + function sync (path, options) { + return checkStat(fs.statSync(path), path, options) + } + return windows; +} + +var mode; +var hasRequiredMode; + +function requireMode () { + if (hasRequiredMode) return mode; + hasRequiredMode = 1; + mode = isexe; + isexe.sync = sync; + + var fs = require$$0$8; + + function isexe (path, options, cb) { + fs.stat(path, function (er, stat) { + cb(er, er ? false : checkStat(stat, options)); + }); + } + + function sync (path, options) { + return checkStat(fs.statSync(path), options) + } + + function checkStat (stat, options) { + return stat.isFile() && checkMode(stat, options) + } + + function checkMode (stat, options) { + var mod = stat.mode; + var uid = stat.uid; + var gid = stat.gid; + + var myUid = options.uid !== undefined ? + options.uid : process.getuid && process.getuid(); + var myGid = options.gid !== undefined ? + options.gid : process.getgid && process.getgid(); + + var u = parseInt('100', 8); + var g = parseInt('010', 8); + var o = parseInt('001', 8); + var ug = u | g; + + var ret = (mod & o) || + (mod & g) && gid === myGid || + (mod & u) && uid === myUid || + (mod & ug) && myUid === 0; + + return ret + } + return mode; +} + +var core$a; +if (process.platform === 'win32' || commonjsGlobal.TESTING_WINDOWS) { + core$a = requireWindows(); +} else { + core$a = requireMode(); +} + +var isexe_1 = isexe$1; +isexe$1.sync = sync$1; + +function isexe$1 (path, options, cb) { + if (typeof options === 'function') { + cb = options; + options = {}; + } + + if (!cb) { + if (typeof Promise !== 'function') { + throw new TypeError('callback not provided') + } + + return new Promise(function (resolve, reject) { + isexe$1(path, options || {}, function (er, is) { + if (er) { + reject(er); + } else { + resolve(is); + } + }); + }) + } + + core$a(path, options || {}, function (er, is) { + // ignore EACCES because that just means we aren't allowed to run it + if (er) { + if (er.code === 'EACCES' || options && options.ignoreErrors) { + er = null; + is = false; + } + } + cb(er, is); + }); +} + +function sync$1 (path, options) { + // my kingdom for a filtered catch + try { + return core$a.sync(path, options || {}) + } catch (er) { + if (options && options.ignoreErrors || er.code === 'EACCES') { + return false + } else { + throw er + } + } +} + +const isWindows$1 = process.platform === 'win32' || + process.env.OSTYPE === 'cygwin' || + process.env.OSTYPE === 'msys'; + +const path$5 = require$$0$b; +const COLON$2 = isWindows$1 ? ';' : ':'; +const isexe = isexe_1; + +const getNotFoundError = (cmd) => + Object.assign(new Error(`not found: ${cmd}`), { code: 'ENOENT' }); + +const getPathInfo = (cmd, opt) => { + const colon = opt.colon || COLON$2; + + // If it has a slash, then we don't bother searching the pathenv. + // just check the file itself, and that's it. + const pathEnv = cmd.match(/\//) || isWindows$1 && cmd.match(/\\/) ? [''] + : ( + [ + // windows always checks the cwd first + ...(isWindows$1 ? [process.cwd()] : []), + ...(opt.path || process.env.PATH || + /* istanbul ignore next: very unusual */ '').split(colon), + ] + ); + const pathExtExe = isWindows$1 + ? opt.pathExt || process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM' + : ''; + const pathExt = isWindows$1 ? pathExtExe.split(colon) : ['']; + + if (isWindows$1) { + if (cmd.indexOf('.') !== -1 && pathExt[0] !== '') + pathExt.unshift(''); + } + + return { + pathEnv, + pathExt, + pathExtExe, + } +}; + +const which$1 = (cmd, opt, cb) => { + if (typeof opt === 'function') { + cb = opt; + opt = {}; + } + if (!opt) + opt = {}; + + const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt); + const found = []; + + const step = i => new Promise((resolve, reject) => { + if (i === pathEnv.length) + return opt.all && found.length ? resolve(found) + : reject(getNotFoundError(cmd)) + + const ppRaw = pathEnv[i]; + const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw; + + const pCmd = path$5.join(pathPart, cmd); + const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd + : pCmd; + + resolve(subStep(p, i, 0)); + }); + + const subStep = (p, i, ii) => new Promise((resolve, reject) => { + if (ii === pathExt.length) + return resolve(step(i + 1)) + const ext = pathExt[ii]; + isexe(p + ext, { pathExt: pathExtExe }, (er, is) => { + if (!er && is) { + if (opt.all) + found.push(p + ext); + else + return resolve(p + ext) + } + return resolve(subStep(p, i, ii + 1)) + }); + }); + + return cb ? step(0).then(res => cb(null, res), cb) : step(0) +}; + +const whichSync = (cmd, opt) => { + opt = opt || {}; + + const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt); + const found = []; + + for (let i = 0; i < pathEnv.length; i ++) { + const ppRaw = pathEnv[i]; + const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw; + + const pCmd = path$5.join(pathPart, cmd); + const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd + : pCmd; + + for (let j = 0; j < pathExt.length; j ++) { + const cur = p + pathExt[j]; + try { + const is = isexe.sync(cur, { pathExt: pathExtExe }); + if (is) { + if (opt.all) + found.push(cur); + else + return cur + } + } catch (ex) {} + } + } + + if (opt.all && found.length) + return found + + if (opt.nothrow) + return null + + throw getNotFoundError(cmd) +}; + +var which_1 = which$1; +which$1.sync = whichSync; + +var pathKey$2 = {exports: {}}; + +const pathKey$1 = (options = {}) => { + const environment = options.env || process.env; + const platform = options.platform || process.platform; + + if (platform !== 'win32') { + return 'PATH'; + } + + return Object.keys(environment).reverse().find(key => key.toUpperCase() === 'PATH') || 'Path'; +}; + +pathKey$2.exports = pathKey$1; +// TODO: Remove this for the next major release +pathKey$2.exports.default = pathKey$1; + +var pathKeyExports = pathKey$2.exports; + +const path$4 = require$$0$b; +const which = which_1; +const getPathKey = pathKeyExports; + +function resolveCommandAttempt(parsed, withoutPathExt) { + const env = parsed.options.env || process.env; + const cwd = process.cwd(); + const hasCustomCwd = parsed.options.cwd != null; + // Worker threads do not have process.chdir() + const shouldSwitchCwd = hasCustomCwd && process.chdir !== undefined && !process.chdir.disabled; + + // If a custom `cwd` was specified, we need to change the process cwd + // because `which` will do stat calls but does not support a custom cwd + if (shouldSwitchCwd) { + try { + process.chdir(parsed.options.cwd); + } catch (err) { + /* Empty */ + } + } + + let resolved; + + try { + resolved = which.sync(parsed.command, { + path: env[getPathKey({ env })], + pathExt: withoutPathExt ? path$4.delimiter : undefined, + }); + } catch (e) { + /* Empty */ + } finally { + if (shouldSwitchCwd) { + process.chdir(cwd); + } + } + + // If we successfully resolved, ensure that an absolute path is returned + // Note that when a custom `cwd` was used, we need to resolve to an absolute path based on it + if (resolved) { + resolved = path$4.resolve(hasCustomCwd ? parsed.options.cwd : '', resolved); + } + + return resolved; +} + +function resolveCommand$1(parsed) { + return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true); +} + +var resolveCommand_1 = resolveCommand$1; + +var _escape = {}; + +// See http://www.robvanderwoude.com/escapechars.php +const metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g; + +function escapeCommand(arg) { + // Escape meta chars + arg = arg.replace(metaCharsRegExp, '^$1'); + + return arg; +} + +function escapeArgument(arg, doubleEscapeMetaChars) { + // Convert to string + arg = `${arg}`; + + // Algorithm below is based on https://qntm.org/cmd + + // Sequence of backslashes followed by a double quote: + // double up all the backslashes and escape the double quote + arg = arg.replace(/(\\*)"/g, '$1$1\\"'); + + // Sequence of backslashes followed by the end of the string + // (which will become a double quote later): + // double up all the backslashes + arg = arg.replace(/(\\*)$/, '$1$1'); + + // All other backslashes occur literally + + // Quote the whole thing: + arg = `"${arg}"`; + + // Escape meta chars + arg = arg.replace(metaCharsRegExp, '^$1'); + + // Double escape meta chars if necessary + if (doubleEscapeMetaChars) { + arg = arg.replace(metaCharsRegExp, '^$1'); + } + + return arg; +} + +_escape.command = escapeCommand; +_escape.argument = escapeArgument; + +var shebangRegex$1 = /^#!(.*)/; + +const shebangRegex = shebangRegex$1; + +var shebangCommand$1 = (string = '') => { + const match = string.match(shebangRegex); + + if (!match) { + return null; + } + + const [path, argument] = match[0].replace(/#! ?/, '').split(' '); + const binary = path.split('/').pop(); + + if (binary === 'env') { + return argument; + } + + return argument ? `${binary} ${argument}` : binary; +}; + +const fs$4 = require$$0$8; +const shebangCommand = shebangCommand$1; + +function readShebang$1(command) { + // Read the first 150 bytes from the file + const size = 150; + const buffer = Buffer.alloc(size); + + let fd; + + try { + fd = fs$4.openSync(command, 'r'); + fs$4.readSync(fd, buffer, 0, size, 0); + fs$4.closeSync(fd); + } catch (e) { /* Empty */ } + + // Attempt to extract shebang (null is returned if not a shebang) + return shebangCommand(buffer.toString()); +} + +var readShebang_1 = readShebang$1; + +const path$3 = require$$0$b; +const resolveCommand = resolveCommand_1; +const escape = _escape; +const readShebang = readShebang_1; + +const isWin$1 = process.platform === 'win32'; +const isExecutableRegExp = /\.(?:com|exe)$/i; +const isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i; + +function detectShebang(parsed) { + parsed.file = resolveCommand(parsed); + + const shebang = parsed.file && readShebang(parsed.file); + + if (shebang) { + parsed.args.unshift(parsed.file); + parsed.command = shebang; + + return resolveCommand(parsed); + } + + return parsed.file; +} + +function parseNonShell(parsed) { + if (!isWin$1) { + return parsed; + } + + // Detect & add support for shebangs + const commandFile = detectShebang(parsed); + + // We don't need a shell if the command filename is an executable + const needsShell = !isExecutableRegExp.test(commandFile); + + // If a shell is required, use cmd.exe and take care of escaping everything correctly + // Note that `forceShell` is an hidden option used only in tests + if (parsed.options.forceShell || needsShell) { + // Need to double escape meta chars if the command is a cmd-shim located in `node_modules/.bin/` + // The cmd-shim simply calls execute the package bin file with NodeJS, proxying any argument + // Because the escape of metachars with ^ gets interpreted when the cmd.exe is first called, + // we need to double escape them + const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile); + + // Normalize posix paths into OS compatible paths (e.g.: foo/bar -> foo\bar) + // This is necessary otherwise it will always fail with ENOENT in those cases + parsed.command = path$3.normalize(parsed.command); + + // Escape command & arguments + parsed.command = escape.command(parsed.command); + parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars)); + + const shellCommand = [parsed.command].concat(parsed.args).join(' '); + + parsed.args = ['/d', '/s', '/c', `"${shellCommand}"`]; + parsed.command = process.env.comspec || 'cmd.exe'; + parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped + } + + return parsed; +} + +function parse$a(command, args, options) { + // Normalize arguments, similar to nodejs + if (args && !Array.isArray(args)) { + options = args; + args = null; + } + + args = args ? args.slice(0) : []; // Clone array to avoid changing the original + options = Object.assign({}, options); // Clone object to avoid changing the original + + // Build our parsed object + const parsed = { + command, + args, + options, + file: undefined, + original: { + command, + args, + }, + }; + + // Delegate further parsing to shell or non-shell + return options.shell ? parsed : parseNonShell(parsed); +} + +var parse_1 = parse$a; + +const isWin = process.platform === 'win32'; + +function notFoundError(original, syscall) { + return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), { + code: 'ENOENT', + errno: 'ENOENT', + syscall: `${syscall} ${original.command}`, + path: original.command, + spawnargs: original.args, + }); +} + +function hookChildProcess(cp, parsed) { + if (!isWin) { + return; + } + + const originalEmit = cp.emit; + + cp.emit = function (name, arg1) { + // If emitting "exit" event and exit code is 1, we need to check if + // the command exists and emit an "error" instead + // See https://github.com/IndigoUnited/node-cross-spawn/issues/16 + if (name === 'exit') { + const err = verifyENOENT(arg1, parsed); + + if (err) { + return originalEmit.call(cp, 'error', err); + } + } + + return originalEmit.apply(cp, arguments); // eslint-disable-line prefer-rest-params + }; +} + +function verifyENOENT(status, parsed) { + if (isWin && status === 1 && !parsed.file) { + return notFoundError(parsed.original, 'spawn'); + } + + return null; +} + +function verifyENOENTSync(status, parsed) { + if (isWin && status === 1 && !parsed.file) { + return notFoundError(parsed.original, 'spawnSync'); + } + + return null; +} + +var enoent$1 = { + hookChildProcess, + verifyENOENT, + verifyENOENTSync, + notFoundError, +}; + +const cp = require$$0$h; +const parse$9 = parse_1; +const enoent = enoent$1; + +function spawn(command, args, options) { + // Parse the arguments + const parsed = parse$9(command, args, options); + + // Spawn the child process + const spawned = cp.spawn(parsed.command, parsed.args, parsed.options); + + // Hook into child process "exit" event to emit an error if the command + // does not exists, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16 + enoent.hookChildProcess(spawned, parsed); + + return spawned; +} + +function spawnSync(command, args, options) { + // Parse the arguments + const parsed = parse$9(command, args, options); + + // Spawn the child process + const result = cp.spawnSync(parsed.command, parsed.args, parsed.options); + + // Analyze if the command does not exist, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16 + result.error = result.error || enoent.verifyENOENTSync(result.status, parsed); + + return result; +} + +crossSpawn$2.exports = spawn; +crossSpawn$2.exports.spawn = spawn; +crossSpawn$2.exports.sync = spawnSync; + +crossSpawn$2.exports._parse = parse$9; +crossSpawn$2.exports._enoent = enoent; + +var crossSpawnExports = crossSpawn$2.exports; +var crossSpawn$1 = /*@__PURE__*/getDefaultExportFromCjs(crossSpawnExports); + +var stripFinalNewline$2 = input => { + const LF = typeof input === 'string' ? '\n' : '\n'.charCodeAt(); + const CR = typeof input === 'string' ? '\r' : '\r'.charCodeAt(); + + if (input[input.length - 1] === LF) { + input = input.slice(0, input.length - 1); + } + + if (input[input.length - 1] === CR) { + input = input.slice(0, input.length - 1); + } + + return input; +}; + +var npmRunPath$2 = {exports: {}}; + +npmRunPath$2.exports; + +(function (module) { + const path = require$$0$b; + const pathKey = pathKeyExports; + + const npmRunPath = options => { + options = { + cwd: process.cwd(), + path: process.env[pathKey()], + execPath: process.execPath, + ...options + }; + + let previous; + let cwdPath = path.resolve(options.cwd); + const result = []; + + while (previous !== cwdPath) { + result.push(path.join(cwdPath, 'node_modules/.bin')); + previous = cwdPath; + cwdPath = path.resolve(cwdPath, '..'); + } + + // Ensure the running `node` binary is used + const execPathDir = path.resolve(options.cwd, options.execPath, '..'); + result.push(execPathDir); + + return result.concat(options.path).join(path.delimiter); + }; + + module.exports = npmRunPath; + // TODO: Remove this for the next major release + module.exports.default = npmRunPath; + + module.exports.env = options => { + options = { + env: process.env, + ...options + }; + + const env = {...options.env}; + const path = pathKey({env}); + + options.path = env[path]; + env[path] = module.exports(options); + + return env; + }; +} (npmRunPath$2)); + +var npmRunPathExports = npmRunPath$2.exports; + +var onetime$4 = {exports: {}}; + +var mimicFn$2 = {exports: {}}; + +const mimicFn$1 = (to, from) => { + for (const prop of Reflect.ownKeys(from)) { + Object.defineProperty(to, prop, Object.getOwnPropertyDescriptor(from, prop)); + } + + return to; +}; + +mimicFn$2.exports = mimicFn$1; +// TODO: Remove this for the next major release +mimicFn$2.exports.default = mimicFn$1; + +var mimicFnExports = mimicFn$2.exports; + +const mimicFn = mimicFnExports; + +const calledFunctions$1 = new WeakMap(); + +const onetime$2 = (function_, options = {}) => { + if (typeof function_ !== 'function') { + throw new TypeError('Expected a function'); + } + + let returnValue; + let callCount = 0; + const functionName = function_.displayName || function_.name || '<anonymous>'; + + const onetime = function (...arguments_) { + calledFunctions$1.set(onetime, ++callCount); + + if (callCount === 1) { + returnValue = function_.apply(this, arguments_); + function_ = null; + } else if (options.throw === true) { + throw new Error(`Function \`${functionName}\` can only be called once`); + } + + return returnValue; + }; + + mimicFn(onetime, function_); + calledFunctions$1.set(onetime, callCount); + + return onetime; +}; + +onetime$4.exports = onetime$2; +// TODO: Remove this for the next major release +onetime$4.exports.default = onetime$2; + +onetime$4.exports.callCount = function_ => { + if (!calledFunctions$1.has(function_)) { + throw new Error(`The given function \`${function_.name}\` is not wrapped by the \`onetime\` package`); + } + + return calledFunctions$1.get(function_); +}; + +var onetimeExports = onetime$4.exports; +var onetime$3 = /*@__PURE__*/getDefaultExportFromCjs(onetimeExports); + +var main$4 = {}; + +var signals = {}; + +var core$9 = {}; + +Object.defineProperty(core$9,"__esModule",{value:true});core$9.SIGNALS=void 0; + +const SIGNALS$1=[ +{ +name:"SIGHUP", +number:1, +action:"terminate", +description:"Terminal closed", +standard:"posix"}, + +{ +name:"SIGINT", +number:2, +action:"terminate", +description:"User interruption with CTRL-C", +standard:"ansi"}, + +{ +name:"SIGQUIT", +number:3, +action:"core", +description:"User interruption with CTRL-\\", +standard:"posix"}, + +{ +name:"SIGILL", +number:4, +action:"core", +description:"Invalid machine instruction", +standard:"ansi"}, + +{ +name:"SIGTRAP", +number:5, +action:"core", +description:"Debugger breakpoint", +standard:"posix"}, + +{ +name:"SIGABRT", +number:6, +action:"core", +description:"Aborted", +standard:"ansi"}, + +{ +name:"SIGIOT", +number:6, +action:"core", +description:"Aborted", +standard:"bsd"}, + +{ +name:"SIGBUS", +number:7, +action:"core", +description: +"Bus error due to misaligned, non-existing address or paging error", +standard:"bsd"}, + +{ +name:"SIGEMT", +number:7, +action:"terminate", +description:"Command should be emulated but is not implemented", +standard:"other"}, + +{ +name:"SIGFPE", +number:8, +action:"core", +description:"Floating point arithmetic error", +standard:"ansi"}, + +{ +name:"SIGKILL", +number:9, +action:"terminate", +description:"Forced termination", +standard:"posix", +forced:true}, + +{ +name:"SIGUSR1", +number:10, +action:"terminate", +description:"Application-specific signal", +standard:"posix"}, + +{ +name:"SIGSEGV", +number:11, +action:"core", +description:"Segmentation fault", +standard:"ansi"}, + +{ +name:"SIGUSR2", +number:12, +action:"terminate", +description:"Application-specific signal", +standard:"posix"}, + +{ +name:"SIGPIPE", +number:13, +action:"terminate", +description:"Broken pipe or socket", +standard:"posix"}, + +{ +name:"SIGALRM", +number:14, +action:"terminate", +description:"Timeout or timer", +standard:"posix"}, + +{ +name:"SIGTERM", +number:15, +action:"terminate", +description:"Termination", +standard:"ansi"}, + +{ +name:"SIGSTKFLT", +number:16, +action:"terminate", +description:"Stack is empty or overflowed", +standard:"other"}, + +{ +name:"SIGCHLD", +number:17, +action:"ignore", +description:"Child process terminated, paused or unpaused", +standard:"posix"}, + +{ +name:"SIGCLD", +number:17, +action:"ignore", +description:"Child process terminated, paused or unpaused", +standard:"other"}, + +{ +name:"SIGCONT", +number:18, +action:"unpause", +description:"Unpaused", +standard:"posix", +forced:true}, + +{ +name:"SIGSTOP", +number:19, +action:"pause", +description:"Paused", +standard:"posix", +forced:true}, + +{ +name:"SIGTSTP", +number:20, +action:"pause", +description:"Paused using CTRL-Z or \"suspend\"", +standard:"posix"}, + +{ +name:"SIGTTIN", +number:21, +action:"pause", +description:"Background process cannot read terminal input", +standard:"posix"}, + +{ +name:"SIGBREAK", +number:21, +action:"terminate", +description:"User interruption with CTRL-BREAK", +standard:"other"}, + +{ +name:"SIGTTOU", +number:22, +action:"pause", +description:"Background process cannot write to terminal output", +standard:"posix"}, + +{ +name:"SIGURG", +number:23, +action:"ignore", +description:"Socket received out-of-band data", +standard:"bsd"}, + +{ +name:"SIGXCPU", +number:24, +action:"core", +description:"Process timed out", +standard:"bsd"}, + +{ +name:"SIGXFSZ", +number:25, +action:"core", +description:"File too big", +standard:"bsd"}, + +{ +name:"SIGVTALRM", +number:26, +action:"terminate", +description:"Timeout or timer", +standard:"bsd"}, + +{ +name:"SIGPROF", +number:27, +action:"terminate", +description:"Timeout or timer", +standard:"bsd"}, + +{ +name:"SIGWINCH", +number:28, +action:"ignore", +description:"Terminal window size changed", +standard:"bsd"}, + +{ +name:"SIGIO", +number:29, +action:"terminate", +description:"I/O is available", +standard:"other"}, + +{ +name:"SIGPOLL", +number:29, +action:"terminate", +description:"Watched event", +standard:"other"}, + +{ +name:"SIGINFO", +number:29, +action:"ignore", +description:"Request for process information", +standard:"other"}, + +{ +name:"SIGPWR", +number:30, +action:"terminate", +description:"Device running out of power", +standard:"systemv"}, + +{ +name:"SIGSYS", +number:31, +action:"core", +description:"Invalid system call", +standard:"other"}, + +{ +name:"SIGUNUSED", +number:31, +action:"terminate", +description:"Invalid system call", +standard:"other"}];core$9.SIGNALS=SIGNALS$1; + +var realtime = {}; + +Object.defineProperty(realtime,"__esModule",{value:true});realtime.SIGRTMAX=realtime.getRealtimeSignals=void 0; +const getRealtimeSignals$1=function(){ +const length=SIGRTMAX$1-SIGRTMIN$1+1; +return Array.from({length},getRealtimeSignal$1); +};realtime.getRealtimeSignals=getRealtimeSignals$1; + +const getRealtimeSignal$1=function(value,index){ +return { +name:`SIGRT${index+1}`, +number:SIGRTMIN$1+index, +action:"terminate", +description:"Application-specific signal (realtime)", +standard:"posix"}; + +}; + +const SIGRTMIN$1=34; +const SIGRTMAX$1=64;realtime.SIGRTMAX=SIGRTMAX$1; + +Object.defineProperty(signals,"__esModule",{value:true});signals.getSignals=void 0;var _os$1=require$$0$7; + +var _core=core$9; +var _realtime$1=realtime; + + + +const getSignals$1=function(){ +const realtimeSignals=(0, _realtime$1.getRealtimeSignals)(); +const signals=[..._core.SIGNALS,...realtimeSignals].map(normalizeSignal$1); +return signals; +};signals.getSignals=getSignals$1; + + + + + + + +const normalizeSignal$1=function({ +name, +number:defaultNumber, +description, +action, +forced=false, +standard}) +{ +const{ +signals:{[name]:constantSignal}}= +_os$1.constants; +const supported=constantSignal!==undefined; +const number=supported?constantSignal:defaultNumber; +return {name,number,description,supported,action,forced,standard}; +}; + +Object.defineProperty(main$4,"__esModule",{value:true});main$4.signalsByNumber=main$4.signalsByName=void 0;var _os=require$$0$7; + +var _signals=signals; +var _realtime=realtime; + + + +const getSignalsByName$1=function(){ +const signals=(0, _signals.getSignals)(); +return signals.reduce(getSignalByName$1,{}); +}; + +const getSignalByName$1=function( +signalByNameMemo, +{name,number,description,supported,action,forced,standard}) +{ +return { +...signalByNameMemo, +[name]:{name,number,description,supported,action,forced,standard}}; + +}; + +const signalsByName$2=getSignalsByName$1();main$4.signalsByName=signalsByName$2; + + + + +const getSignalsByNumber$1=function(){ +const signals=(0, _signals.getSignals)(); +const length=_realtime.SIGRTMAX+1; +const signalsA=Array.from({length},(value,number)=> +getSignalByNumber$1(number,signals)); + +return Object.assign({},...signalsA); +}; + +const getSignalByNumber$1=function(number,signals){ +const signal=findSignalByNumber$1(number,signals); + +if(signal===undefined){ +return {}; +} + +const{name,description,supported,action,forced,standard}=signal; +return { +[number]:{ +name, +number, +description, +supported, +action, +forced, +standard}}; + + +}; + + + +const findSignalByNumber$1=function(number,signals){ +const signal=signals.find(({name})=>_os.constants.signals[name]===number); + +if(signal!==undefined){ +return signal; +} + +return signals.find(signalA=>signalA.number===number); +}; + +const signalsByNumber=getSignalsByNumber$1();main$4.signalsByNumber=signalsByNumber; + +const {signalsByName: signalsByName$1} = main$4; + +const getErrorPrefix$1 = ({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled}) => { + if (timedOut) { + return `timed out after ${timeout} milliseconds`; + } + + if (isCanceled) { + return 'was canceled'; + } + + if (errorCode !== undefined) { + return `failed with ${errorCode}`; + } + + if (signal !== undefined) { + return `was killed with ${signal} (${signalDescription})`; + } + + if (exitCode !== undefined) { + return `failed with exit code ${exitCode}`; + } + + return 'failed'; +}; + +const makeError$2 = ({ + stdout, + stderr, + all, + error, + signal, + exitCode, + command, + escapedCommand, + timedOut, + isCanceled, + killed, + parsed: {options: {timeout}} +}) => { + // `signal` and `exitCode` emitted on `spawned.on('exit')` event can be `null`. + // We normalize them to `undefined` + exitCode = exitCode === null ? undefined : exitCode; + signal = signal === null ? undefined : signal; + const signalDescription = signal === undefined ? undefined : signalsByName$1[signal].description; + + const errorCode = error && error.code; + + const prefix = getErrorPrefix$1({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled}); + const execaMessage = `Command ${prefix}: ${command}`; + const isError = Object.prototype.toString.call(error) === '[object Error]'; + const shortMessage = isError ? `${execaMessage}\n${error.message}` : execaMessage; + const message = [shortMessage, stderr, stdout].filter(Boolean).join('\n'); + + if (isError) { + error.originalMessage = error.message; + error.message = message; + } else { + error = new Error(message); + } + + error.shortMessage = shortMessage; + error.command = command; + error.escapedCommand = escapedCommand; + error.exitCode = exitCode; + error.signal = signal; + error.signalDescription = signalDescription; + error.stdout = stdout; + error.stderr = stderr; + + if (all !== undefined) { + error.all = all; + } + + if ('bufferedData' in error) { + delete error.bufferedData; + } + + error.failed = true; + error.timedOut = Boolean(timedOut); + error.isCanceled = isCanceled; + error.killed = killed && !timedOut; + + return error; +}; + +var error$m = makeError$2; + +var stdio = {exports: {}}; + +const aliases$1 = ['stdin', 'stdout', 'stderr']; + +const hasAlias$1 = options => aliases$1.some(alias => options[alias] !== undefined); + +const normalizeStdio$2 = options => { + if (!options) { + return; + } + + const {stdio} = options; + + if (stdio === undefined) { + return aliases$1.map(alias => options[alias]); + } + + if (hasAlias$1(options)) { + throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${aliases$1.map(alias => `\`${alias}\``).join(', ')}`); + } + + if (typeof stdio === 'string') { + return stdio; + } + + if (!Array.isArray(stdio)) { + throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof stdio}\``); + } + + const length = Math.max(stdio.length, aliases$1.length); + return Array.from({length}, (value, index) => stdio[index]); +}; + +stdio.exports = normalizeStdio$2; + +// `ipc` is pushed unless it is already present +stdio.exports.node = options => { + const stdio = normalizeStdio$2(options); + + if (stdio === 'ipc') { + return 'ipc'; + } + + if (stdio === undefined || typeof stdio === 'string') { + return [stdio, stdio, stdio, 'ipc']; + } + + if (stdio.includes('ipc')) { + return stdio; + } + + return [...stdio, 'ipc']; +}; + +var stdioExports = stdio.exports; + +const os = require$$0$7; +const onExit = signalExitExports; + +const DEFAULT_FORCE_KILL_TIMEOUT$1 = 1000 * 5; + +// Monkey-patches `childProcess.kill()` to add `forceKillAfterTimeout` behavior +const spawnedKill$2 = (kill, signal = 'SIGTERM', options = {}) => { + const killResult = kill(signal); + setKillTimeout$1(kill, signal, options, killResult); + return killResult; +}; + +const setKillTimeout$1 = (kill, signal, options, killResult) => { + if (!shouldForceKill$1(signal, options, killResult)) { + return; + } + + const timeout = getForceKillAfterTimeout$1(options); + const t = setTimeout(() => { + kill('SIGKILL'); + }, timeout); + + // Guarded because there's no `.unref()` when `execa` is used in the renderer + // process in Electron. This cannot be tested since we don't run tests in + // Electron. + // istanbul ignore else + if (t.unref) { + t.unref(); + } +}; + +const shouldForceKill$1 = (signal, {forceKillAfterTimeout}, killResult) => { + return isSigterm$1(signal) && forceKillAfterTimeout !== false && killResult; +}; + +const isSigterm$1 = signal => { + return signal === os.constants.signals.SIGTERM || + (typeof signal === 'string' && signal.toUpperCase() === 'SIGTERM'); +}; + +const getForceKillAfterTimeout$1 = ({forceKillAfterTimeout = true}) => { + if (forceKillAfterTimeout === true) { + return DEFAULT_FORCE_KILL_TIMEOUT$1; + } + + if (!Number.isFinite(forceKillAfterTimeout) || forceKillAfterTimeout < 0) { + throw new TypeError(`Expected the \`forceKillAfterTimeout\` option to be a non-negative integer, got \`${forceKillAfterTimeout}\` (${typeof forceKillAfterTimeout})`); + } + + return forceKillAfterTimeout; +}; + +// `childProcess.cancel()` +const spawnedCancel$2 = (spawned, context) => { + const killResult = spawned.kill(); + + if (killResult) { + context.isCanceled = true; + } +}; + +const timeoutKill$1 = (spawned, signal, reject) => { + spawned.kill(signal); + reject(Object.assign(new Error('Timed out'), {timedOut: true, signal})); +}; + +// `timeout` option handling +const setupTimeout$2 = (spawned, {timeout, killSignal = 'SIGTERM'}, spawnedPromise) => { + if (timeout === 0 || timeout === undefined) { + return spawnedPromise; + } + + let timeoutId; + const timeoutPromise = new Promise((resolve, reject) => { + timeoutId = setTimeout(() => { + timeoutKill$1(spawned, killSignal, reject); + }, timeout); + }); + + const safeSpawnedPromise = spawnedPromise.finally(() => { + clearTimeout(timeoutId); + }); + + return Promise.race([timeoutPromise, safeSpawnedPromise]); +}; + +const validateTimeout$2 = ({timeout}) => { + if (timeout !== undefined && (!Number.isFinite(timeout) || timeout < 0)) { + throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${timeout}\` (${typeof timeout})`); + } +}; + +// `cleanup` option handling +const setExitHandler$2 = async (spawned, {cleanup, detached}, timedPromise) => { + if (!cleanup || detached) { + return timedPromise; + } + + const removeExitHandler = onExit(() => { + spawned.kill(); + }); + + return timedPromise.finally(() => { + removeExitHandler(); + }); +}; + +var kill = { + spawnedKill: spawnedKill$2, + spawnedCancel: spawnedCancel$2, + setupTimeout: setupTimeout$2, + validateTimeout: validateTimeout$2, + setExitHandler: setExitHandler$2 +}; + +const isStream$2 = stream => + stream !== null && + typeof stream === 'object' && + typeof stream.pipe === 'function'; + +isStream$2.writable = stream => + isStream$2(stream) && + stream.writable !== false && + typeof stream._write === 'function' && + typeof stream._writableState === 'object'; + +isStream$2.readable = stream => + isStream$2(stream) && + stream.readable !== false && + typeof stream._read === 'function' && + typeof stream._readableState === 'object'; + +isStream$2.duplex = stream => + isStream$2.writable(stream) && + isStream$2.readable(stream); + +isStream$2.transform = stream => + isStream$2.duplex(stream) && + typeof stream._transform === 'function'; + +var isStream_1 = isStream$2; + +const { PassThrough: PassThrough$2 } = Stream$3; + +var mergeStream$1 = function (/*streams...*/) { + var sources = []; + var output = new PassThrough$2({objectMode: true}); + + output.setMaxListeners(0); + + output.add = add; + output.isEmpty = isEmpty; + + output.on('unpipe', remove); + + Array.prototype.slice.call(arguments).forEach(add); + + return output + + function add (source) { + if (Array.isArray(source)) { + source.forEach(add); + return this + } + + sources.push(source); + source.once('end', remove.bind(null, source)); + source.once('error', output.emit.bind(output, 'error')); + source.pipe(output, {end: false}); + return this + } + + function isEmpty () { + return sources.length == 0; + } + + function remove (source) { + sources = sources.filter(function (it) { return it !== source }); + if (!sources.length && output.readable) { output.end(); } + } +}; + +var mergeStream$2 = /*@__PURE__*/getDefaultExportFromCjs(mergeStream$1); + +const isStream$1 = isStream_1; +const getStream = getStreamExports; +const mergeStream = mergeStream$1; + +// `input` option +const handleInput$2 = (spawned, input) => { + // Checking for stdin is workaround for https://github.com/nodejs/node/issues/26852 + // @todo remove `|| spawned.stdin === undefined` once we drop support for Node.js <=12.2.0 + if (input === undefined || spawned.stdin === undefined) { + return; + } + + if (isStream$1(input)) { + input.pipe(spawned.stdin); + } else { + spawned.stdin.end(input); + } +}; + +// `all` interleaves `stdout` and `stderr` +const makeAllStream$2 = (spawned, {all}) => { + if (!all || (!spawned.stdout && !spawned.stderr)) { + return; + } + + const mixed = mergeStream(); + + if (spawned.stdout) { + mixed.add(spawned.stdout); + } + + if (spawned.stderr) { + mixed.add(spawned.stderr); + } + + return mixed; +}; + +// On failure, `result.stdout|stderr|all` should contain the currently buffered stream +const getBufferedData$1 = async (stream, streamPromise) => { + if (!stream) { + return; + } + + stream.destroy(); + + try { + return await streamPromise; + } catch (error) { + return error.bufferedData; + } +}; + +const getStreamPromise$1 = (stream, {encoding, buffer, maxBuffer}) => { + if (!stream || !buffer) { + return; + } + + if (encoding) { + return getStream(stream, {encoding, maxBuffer}); + } + + return getStream.buffer(stream, {maxBuffer}); +}; + +// Retrieve result of child process: exit code, signal, error, streams (stdout/stderr/all) +const getSpawnedResult$2 = async ({stdout, stderr, all}, {encoding, buffer, maxBuffer}, processDone) => { + const stdoutPromise = getStreamPromise$1(stdout, {encoding, buffer, maxBuffer}); + const stderrPromise = getStreamPromise$1(stderr, {encoding, buffer, maxBuffer}); + const allPromise = getStreamPromise$1(all, {encoding, buffer, maxBuffer: maxBuffer * 2}); + + try { + return await Promise.all([processDone, stdoutPromise, stderrPromise, allPromise]); + } catch (error) { + return Promise.all([ + {error, signal: error.signal, timedOut: error.timedOut}, + getBufferedData$1(stdout, stdoutPromise), + getBufferedData$1(stderr, stderrPromise), + getBufferedData$1(all, allPromise) + ]); + } +}; + +const validateInputSync$1 = ({input}) => { + if (isStream$1(input)) { + throw new TypeError('The `input` option cannot be a stream in sync mode'); + } +}; + +var stream$1 = { + handleInput: handleInput$2, + makeAllStream: makeAllStream$2, + getSpawnedResult: getSpawnedResult$2, + validateInputSync: validateInputSync$1 +}; + +const nativePromisePrototype$1 = (async () => {})().constructor.prototype; +const descriptors$1 = ['then', 'catch', 'finally'].map(property => [ + property, + Reflect.getOwnPropertyDescriptor(nativePromisePrototype$1, property) +]); + +// The return value is a mixin of `childProcess` and `Promise` +const mergePromise$2 = (spawned, promise) => { + for (const [property, descriptor] of descriptors$1) { + // Starting the main `promise` is deferred to avoid consuming streams + const value = typeof promise === 'function' ? + (...args) => Reflect.apply(descriptor.value, promise(), args) : + descriptor.value.bind(promise); + + Reflect.defineProperty(spawned, property, {...descriptor, value}); + } + + return spawned; +}; + +// Use promises instead of `child_process` events +const getSpawnedPromise$2 = spawned => { + return new Promise((resolve, reject) => { + spawned.on('exit', (exitCode, signal) => { + resolve({exitCode, signal}); + }); + + spawned.on('error', error => { + reject(error); + }); + + if (spawned.stdin) { + spawned.stdin.on('error', error => { + reject(error); + }); + } + }); +}; + +var promise$1 = { + mergePromise: mergePromise$2, + getSpawnedPromise: getSpawnedPromise$2 +}; + +const normalizeArgs$5 = (file, args = []) => { + if (!Array.isArray(args)) { + return [file]; + } + + return [file, ...args]; +}; + +const NO_ESCAPE_REGEXP$1 = /^[\w.-]+$/; +const DOUBLE_QUOTES_REGEXP$1 = /"/g; + +const escapeArg$1 = arg => { + if (typeof arg !== 'string' || NO_ESCAPE_REGEXP$1.test(arg)) { + return arg; + } + + return `"${arg.replace(DOUBLE_QUOTES_REGEXP$1, '\\"')}"`; +}; + +const joinCommand$2 = (file, args) => { + return normalizeArgs$5(file, args).join(' '); +}; + +const getEscapedCommand$2 = (file, args) => { + return normalizeArgs$5(file, args).map(arg => escapeArg$1(arg)).join(' '); +}; + +const SPACES_REGEXP = / +/g; + +// Handle `execa.command()` +const parseCommand$1 = command => { + const tokens = []; + for (const token of command.trim().split(SPACES_REGEXP)) { + // Allow spaces to be escaped by a backslash if not meant as a delimiter + const previousToken = tokens[tokens.length - 1]; + if (previousToken && previousToken.endsWith('\\')) { + // Merge previous token with current one + tokens[tokens.length - 1] = `${previousToken.slice(0, -1)} ${token}`; + } else { + tokens.push(token); + } + } + + return tokens; +}; + +var command = { + joinCommand: joinCommand$2, + getEscapedCommand: getEscapedCommand$2, + parseCommand: parseCommand$1 +}; + +const path$2 = require$$0$b; +const childProcess = require$$0$h; +const crossSpawn = crossSpawnExports; +const stripFinalNewline$1 = stripFinalNewline$2; +const npmRunPath$1 = npmRunPathExports; +const onetime$1 = onetimeExports; +const makeError$1 = error$m; +const normalizeStdio$1 = stdioExports; +const {spawnedKill: spawnedKill$1, spawnedCancel: spawnedCancel$1, setupTimeout: setupTimeout$1, validateTimeout: validateTimeout$1, setExitHandler: setExitHandler$1} = kill; +const {handleInput: handleInput$1, getSpawnedResult: getSpawnedResult$1, makeAllStream: makeAllStream$1, validateInputSync} = stream$1; +const {mergePromise: mergePromise$1, getSpawnedPromise: getSpawnedPromise$1} = promise$1; +const {joinCommand: joinCommand$1, parseCommand, getEscapedCommand: getEscapedCommand$1} = command; + +const DEFAULT_MAX_BUFFER$1 = 1000 * 1000 * 100; + +const getEnv$1 = ({env: envOption, extendEnv, preferLocal, localDir, execPath}) => { + const env = extendEnv ? {...process.env, ...envOption} : envOption; + + if (preferLocal) { + return npmRunPath$1.env({env, cwd: localDir, execPath}); + } + + return env; +}; + +const handleArguments$1 = (file, args, options = {}) => { + const parsed = crossSpawn._parse(file, args, options); + file = parsed.command; + args = parsed.args; + options = parsed.options; + + options = { + maxBuffer: DEFAULT_MAX_BUFFER$1, + buffer: true, + stripFinalNewline: true, + extendEnv: true, + preferLocal: false, + localDir: options.cwd || process.cwd(), + execPath: process.execPath, + encoding: 'utf8', + reject: true, + cleanup: true, + all: false, + windowsHide: true, + ...options + }; + + options.env = getEnv$1(options); + + options.stdio = normalizeStdio$1(options); + + if (process.platform === 'win32' && path$2.basename(file, '.exe') === 'cmd') { + // #116 + args.unshift('/q'); + } + + return {file, args, options, parsed}; +}; + +const handleOutput$1 = (options, value, error) => { + if (typeof value !== 'string' && !Buffer.isBuffer(value)) { + // When `execa.sync()` errors, we normalize it to '' to mimic `execa()` + return error === undefined ? undefined : ''; + } + + if (options.stripFinalNewline) { + return stripFinalNewline$1(value); + } + + return value; +}; + +const execa$1 = (file, args, options) => { + const parsed = handleArguments$1(file, args, options); + const command = joinCommand$1(file, args); + const escapedCommand = getEscapedCommand$1(file, args); + + validateTimeout$1(parsed.options); + + let spawned; + try { + spawned = childProcess.spawn(parsed.file, parsed.args, parsed.options); + } catch (error) { + // Ensure the returned error is always both a promise and a child process + const dummySpawned = new childProcess.ChildProcess(); + const errorPromise = Promise.reject(makeError$1({ + error, + stdout: '', + stderr: '', + all: '', + command, + escapedCommand, + parsed, + timedOut: false, + isCanceled: false, + killed: false + })); + return mergePromise$1(dummySpawned, errorPromise); + } + + const spawnedPromise = getSpawnedPromise$1(spawned); + const timedPromise = setupTimeout$1(spawned, parsed.options, spawnedPromise); + const processDone = setExitHandler$1(spawned, parsed.options, timedPromise); + + const context = {isCanceled: false}; + + spawned.kill = spawnedKill$1.bind(null, spawned.kill.bind(spawned)); + spawned.cancel = spawnedCancel$1.bind(null, spawned, context); + + const handlePromise = async () => { + const [{error, exitCode, signal, timedOut}, stdoutResult, stderrResult, allResult] = await getSpawnedResult$1(spawned, parsed.options, processDone); + const stdout = handleOutput$1(parsed.options, stdoutResult); + const stderr = handleOutput$1(parsed.options, stderrResult); + const all = handleOutput$1(parsed.options, allResult); + + if (error || exitCode !== 0 || signal !== null) { + const returnedError = makeError$1({ + error, + exitCode, + signal, + stdout, + stderr, + all, + command, + escapedCommand, + parsed, + timedOut, + isCanceled: context.isCanceled, + killed: spawned.killed + }); + + if (!parsed.options.reject) { + return returnedError; + } + + throw returnedError; + } + + return { + command, + escapedCommand, + exitCode: 0, + stdout, + stderr, + all, + failed: false, + timedOut: false, + isCanceled: false, + killed: false + }; + }; + + const handlePromiseOnce = onetime$1(handlePromise); + + handleInput$1(spawned, parsed.options.input); + + spawned.all = makeAllStream$1(spawned, parsed.options); + + return mergePromise$1(spawned, handlePromiseOnce); +}; + +execa$3.exports = execa$1; + +execa$3.exports.sync = (file, args, options) => { + const parsed = handleArguments$1(file, args, options); + const command = joinCommand$1(file, args); + const escapedCommand = getEscapedCommand$1(file, args); + + validateInputSync(parsed.options); + + let result; + try { + result = childProcess.spawnSync(parsed.file, parsed.args, parsed.options); + } catch (error) { + throw makeError$1({ + error, + stdout: '', + stderr: '', + all: '', + command, + escapedCommand, + parsed, + timedOut: false, + isCanceled: false, + killed: false + }); + } + + const stdout = handleOutput$1(parsed.options, result.stdout, result.error); + const stderr = handleOutput$1(parsed.options, result.stderr, result.error); + + if (result.error || result.status !== 0 || result.signal !== null) { + const error = makeError$1({ + stdout, + stderr, + error: result.error, + signal: result.signal, + exitCode: result.status, + command, + escapedCommand, + parsed, + timedOut: result.error && result.error.code === 'ETIMEDOUT', + isCanceled: false, + killed: result.signal !== null + }); + + if (!parsed.options.reject) { + return error; + } + + throw error; + } + + return { + command, + escapedCommand, + exitCode: 0, + stdout, + stderr, + failed: false, + timedOut: false, + isCanceled: false, + killed: false + }; +}; + +execa$3.exports.command = (command, options) => { + const [file, ...args] = parseCommand(command); + return execa$1(file, args, options); +}; + +execa$3.exports.commandSync = (command, options) => { + const [file, ...args] = parseCommand(command); + return execa$1.sync(file, args, options); +}; + +execa$3.exports.node = (scriptPath, args, options = {}) => { + if (args && !Array.isArray(args) && typeof args === 'object') { + options = args; + args = []; + } + + const stdio = normalizeStdio$1.node(options); + const defaultExecArgv = process.execArgv.filter(arg => !arg.startsWith('--inspect')); + + const { + nodePath = process.execPath, + nodeOptions = defaultExecArgv + } = options; + + return execa$1( + nodePath, + [ + ...nodeOptions, + scriptPath, + ...(Array.isArray(args) ? args : []) + ], + { + ...options, + stdin: undefined, + stdout: undefined, + stderr: undefined, + stdio, + shell: false + } + ); +}; + +var execaExports = execa$3.exports; +var execa$2 = /*@__PURE__*/getDefaultExportFromCjs(execaExports); + +async function runAppleScriptAsync(script) { + if (process.platform !== 'darwin') { + throw new Error('macOS only'); + } + + const {stdout} = await execa$2('osascript', ['-e', script]); + return stdout; +} + +async function bundleName(bundleId) { + return runAppleScriptAsync(`tell application "Finder" to set app_path to application file id "${bundleId}" as string\ntell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`); +} + +function titleize(string) { + if (typeof string !== 'string') { + throw new TypeError('Expected a string'); + } + + return string.toLowerCase().replace(/(?:^|\s|-)\S/g, x => x.toUpperCase()); +} + +function stripFinalNewline(input) { + const LF = typeof input === 'string' ? '\n' : '\n'.charCodeAt(); + const CR = typeof input === 'string' ? '\r' : '\r'.charCodeAt(); + + if (input[input.length - 1] === LF) { + input = input.slice(0, -1); + } + + if (input[input.length - 1] === CR) { + input = input.slice(0, -1); + } + + return input; +} + +function pathKey(options = {}) { + const { + env = process.env, + platform = process.platform + } = options; + + if (platform !== 'win32') { + return 'PATH'; + } + + return Object.keys(env).reverse().find(key => key.toUpperCase() === 'PATH') || 'Path'; +} + +function npmRunPath(options = {}) { + const { + cwd = process$3.cwd(), + path: path_ = process$3.env[pathKey()], + execPath = process$3.execPath, + } = options; + + let previous; + const cwdString = cwd instanceof URL ? urlLib.fileURLToPath(cwd) : cwd; + let cwdPath = path$c.resolve(cwdString); + const result = []; + + while (previous !== cwdPath) { + result.push(path$c.join(cwdPath, 'node_modules/.bin')); + previous = cwdPath; + cwdPath = path$c.resolve(cwdPath, '..'); + } + + // Ensure the running `node` binary is used. + result.push(path$c.resolve(cwdString, execPath, '..')); + + return [...result, path_].join(path$c.delimiter); +} + +function npmRunPathEnv({env = process$3.env, ...options} = {}) { + env = {...env}; + + const path = pathKey({env}); + options.path = env[path]; + env[path] = npmRunPath(options); + + return env; +} + +const copyProperty = (to, from, property, ignoreNonConfigurable) => { + // `Function#length` should reflect the parameters of `to` not `from` since we keep its body. + // `Function#prototype` is non-writable and non-configurable so can never be modified. + if (property === 'length' || property === 'prototype') { + return; + } + + // `Function#arguments` and `Function#caller` should not be copied. They were reported to be present in `Reflect.ownKeys` for some devices in React Native (#41), so we explicitly ignore them here. + if (property === 'arguments' || property === 'caller') { + return; + } + + const toDescriptor = Object.getOwnPropertyDescriptor(to, property); + const fromDescriptor = Object.getOwnPropertyDescriptor(from, property); + + if (!canCopyProperty(toDescriptor, fromDescriptor) && ignoreNonConfigurable) { + return; + } + + Object.defineProperty(to, property, fromDescriptor); +}; + +// `Object.defineProperty()` throws if the property exists, is not configurable and either: +// - one its descriptors is changed +// - it is non-writable and its value is changed +const canCopyProperty = function (toDescriptor, fromDescriptor) { + return toDescriptor === undefined || toDescriptor.configurable || ( + toDescriptor.writable === fromDescriptor.writable && + toDescriptor.enumerable === fromDescriptor.enumerable && + toDescriptor.configurable === fromDescriptor.configurable && + (toDescriptor.writable || toDescriptor.value === fromDescriptor.value) + ); +}; + +const changePrototype = (to, from) => { + const fromPrototype = Object.getPrototypeOf(from); + if (fromPrototype === Object.getPrototypeOf(to)) { + return; + } + + Object.setPrototypeOf(to, fromPrototype); +}; + +const wrappedToString = (withName, fromBody) => `/* Wrapped ${withName}*/\n${fromBody}`; + +const toStringDescriptor = Object.getOwnPropertyDescriptor(Function.prototype, 'toString'); +const toStringName = Object.getOwnPropertyDescriptor(Function.prototype.toString, 'name'); + +// We call `from.toString()` early (not lazily) to ensure `from` can be garbage collected. +// We use `bind()` instead of a closure for the same reason. +// Calling `from.toString()` early also allows caching it in case `to.toString()` is called several times. +const changeToString = (to, from, name) => { + const withName = name === '' ? '' : `with ${name.trim()}() `; + const newToString = wrappedToString.bind(null, withName, from.toString()); + // Ensure `to.toString.toString` is non-enumerable and has the same `same` + Object.defineProperty(newToString, 'name', toStringName); + Object.defineProperty(to, 'toString', {...toStringDescriptor, value: newToString}); +}; + +function mimicFunction(to, from, {ignoreNonConfigurable = false} = {}) { + const {name} = to; + + for (const property of Reflect.ownKeys(from)) { + copyProperty(to, from, property, ignoreNonConfigurable); + } + + changePrototype(to, from); + changeToString(to, from, name); + + return to; +} + +const calledFunctions = new WeakMap(); + +const onetime = (function_, options = {}) => { + if (typeof function_ !== 'function') { + throw new TypeError('Expected a function'); + } + + let returnValue; + let callCount = 0; + const functionName = function_.displayName || function_.name || '<anonymous>'; + + const onetime = function (...arguments_) { + calledFunctions.set(onetime, ++callCount); + + if (callCount === 1) { + returnValue = function_.apply(this, arguments_); + function_ = null; + } else if (options.throw === true) { + throw new Error(`Function \`${functionName}\` can only be called once`); + } + + return returnValue; + }; + + mimicFunction(onetime, function_); + calledFunctions.set(onetime, callCount); + + return onetime; +}; + +onetime.callCount = function_ => { + if (!calledFunctions.has(function_)) { + throw new Error(`The given function \`${function_.name}\` is not wrapped by the \`onetime\` package`); + } + + return calledFunctions.get(function_); +}; + +const getRealtimeSignals=()=>{ +const length=SIGRTMAX-SIGRTMIN+1; +return Array.from({length},getRealtimeSignal); +}; + +const getRealtimeSignal=(value,index)=>({ +name:`SIGRT${index+1}`, +number:SIGRTMIN+index, +action:"terminate", +description:"Application-specific signal (realtime)", +standard:"posix" +}); + +const SIGRTMIN=34; +const SIGRTMAX=64; + +const SIGNALS=[ +{ +name:"SIGHUP", +number:1, +action:"terminate", +description:"Terminal closed", +standard:"posix" +}, +{ +name:"SIGINT", +number:2, +action:"terminate", +description:"User interruption with CTRL-C", +standard:"ansi" +}, +{ +name:"SIGQUIT", +number:3, +action:"core", +description:"User interruption with CTRL-\\", +standard:"posix" +}, +{ +name:"SIGILL", +number:4, +action:"core", +description:"Invalid machine instruction", +standard:"ansi" +}, +{ +name:"SIGTRAP", +number:5, +action:"core", +description:"Debugger breakpoint", +standard:"posix" +}, +{ +name:"SIGABRT", +number:6, +action:"core", +description:"Aborted", +standard:"ansi" +}, +{ +name:"SIGIOT", +number:6, +action:"core", +description:"Aborted", +standard:"bsd" +}, +{ +name:"SIGBUS", +number:7, +action:"core", +description: +"Bus error due to misaligned, non-existing address or paging error", +standard:"bsd" +}, +{ +name:"SIGEMT", +number:7, +action:"terminate", +description:"Command should be emulated but is not implemented", +standard:"other" +}, +{ +name:"SIGFPE", +number:8, +action:"core", +description:"Floating point arithmetic error", +standard:"ansi" +}, +{ +name:"SIGKILL", +number:9, +action:"terminate", +description:"Forced termination", +standard:"posix", +forced:true +}, +{ +name:"SIGUSR1", +number:10, +action:"terminate", +description:"Application-specific signal", +standard:"posix" +}, +{ +name:"SIGSEGV", +number:11, +action:"core", +description:"Segmentation fault", +standard:"ansi" +}, +{ +name:"SIGUSR2", +number:12, +action:"terminate", +description:"Application-specific signal", +standard:"posix" +}, +{ +name:"SIGPIPE", +number:13, +action:"terminate", +description:"Broken pipe or socket", +standard:"posix" +}, +{ +name:"SIGALRM", +number:14, +action:"terminate", +description:"Timeout or timer", +standard:"posix" +}, +{ +name:"SIGTERM", +number:15, +action:"terminate", +description:"Termination", +standard:"ansi" +}, +{ +name:"SIGSTKFLT", +number:16, +action:"terminate", +description:"Stack is empty or overflowed", +standard:"other" +}, +{ +name:"SIGCHLD", +number:17, +action:"ignore", +description:"Child process terminated, paused or unpaused", +standard:"posix" +}, +{ +name:"SIGCLD", +number:17, +action:"ignore", +description:"Child process terminated, paused or unpaused", +standard:"other" +}, +{ +name:"SIGCONT", +number:18, +action:"unpause", +description:"Unpaused", +standard:"posix", +forced:true +}, +{ +name:"SIGSTOP", +number:19, +action:"pause", +description:"Paused", +standard:"posix", +forced:true +}, +{ +name:"SIGTSTP", +number:20, +action:"pause", +description:"Paused using CTRL-Z or \"suspend\"", +standard:"posix" +}, +{ +name:"SIGTTIN", +number:21, +action:"pause", +description:"Background process cannot read terminal input", +standard:"posix" +}, +{ +name:"SIGBREAK", +number:21, +action:"terminate", +description:"User interruption with CTRL-BREAK", +standard:"other" +}, +{ +name:"SIGTTOU", +number:22, +action:"pause", +description:"Background process cannot write to terminal output", +standard:"posix" +}, +{ +name:"SIGURG", +number:23, +action:"ignore", +description:"Socket received out-of-band data", +standard:"bsd" +}, +{ +name:"SIGXCPU", +number:24, +action:"core", +description:"Process timed out", +standard:"bsd" +}, +{ +name:"SIGXFSZ", +number:25, +action:"core", +description:"File too big", +standard:"bsd" +}, +{ +name:"SIGVTALRM", +number:26, +action:"terminate", +description:"Timeout or timer", +standard:"bsd" +}, +{ +name:"SIGPROF", +number:27, +action:"terminate", +description:"Timeout or timer", +standard:"bsd" +}, +{ +name:"SIGWINCH", +number:28, +action:"ignore", +description:"Terminal window size changed", +standard:"bsd" +}, +{ +name:"SIGIO", +number:29, +action:"terminate", +description:"I/O is available", +standard:"other" +}, +{ +name:"SIGPOLL", +number:29, +action:"terminate", +description:"Watched event", +standard:"other" +}, +{ +name:"SIGINFO", +number:29, +action:"ignore", +description:"Request for process information", +standard:"other" +}, +{ +name:"SIGPWR", +number:30, +action:"terminate", +description:"Device running out of power", +standard:"systemv" +}, +{ +name:"SIGSYS", +number:31, +action:"core", +description:"Invalid system call", +standard:"other" +}, +{ +name:"SIGUNUSED", +number:31, +action:"terminate", +description:"Invalid system call", +standard:"other" +}]; + +const getSignals=()=>{ +const realtimeSignals=getRealtimeSignals(); +const signals=[...SIGNALS,...realtimeSignals].map(normalizeSignal); +return signals; +}; + + + + + + + +const normalizeSignal=({ +name, +number:defaultNumber, +description, +action, +forced=false, +standard +})=>{ +const{ +signals:{[name]:constantSignal} +}=os$5.constants; +const supported=constantSignal!==undefined; +const number=supported?constantSignal:defaultNumber; +return {name,number,description,supported,action,forced,standard}; +}; + +const getSignalsByName=()=>{ +const signals=getSignals(); +return Object.fromEntries(signals.map(getSignalByName)); +}; + +const getSignalByName=({ +name, +number, +description, +supported, +action, +forced, +standard +})=>[name,{name,number,description,supported,action,forced,standard}]; + +const signalsByName=getSignalsByName(); + + + + +const getSignalsByNumber=()=>{ +const signals=getSignals(); +const length=SIGRTMAX+1; +const signalsA=Array.from({length},(value,number)=> +getSignalByNumber(number,signals)); + +return Object.assign({},...signalsA); +}; + +const getSignalByNumber=(number,signals)=>{ +const signal=findSignalByNumber(number,signals); + +if(signal===undefined){ +return {}; +} + +const{name,description,supported,action,forced,standard}=signal; +return { +[number]:{ +name, +number, +description, +supported, +action, +forced, +standard +} +}; +}; + + + +const findSignalByNumber=(number,signals)=>{ +const signal=signals.find(({name})=>os$5.constants.signals[name]===number); + +if(signal!==undefined){ +return signal; +} + +return signals.find((signalA)=>signalA.number===number); +}; + +getSignalsByNumber(); + +const getErrorPrefix = ({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled}) => { + if (timedOut) { + return `timed out after ${timeout} milliseconds`; + } + + if (isCanceled) { + return 'was canceled'; + } + + if (errorCode !== undefined) { + return `failed with ${errorCode}`; + } + + if (signal !== undefined) { + return `was killed with ${signal} (${signalDescription})`; + } + + if (exitCode !== undefined) { + return `failed with exit code ${exitCode}`; + } + + return 'failed'; +}; + +const makeError = ({ + stdout, + stderr, + all, + error, + signal, + exitCode, + command, + escapedCommand, + timedOut, + isCanceled, + killed, + parsed: {options: {timeout, cwd = process$3.cwd()}}, +}) => { + // `signal` and `exitCode` emitted on `spawned.on('exit')` event can be `null`. + // We normalize them to `undefined` + exitCode = exitCode === null ? undefined : exitCode; + signal = signal === null ? undefined : signal; + const signalDescription = signal === undefined ? undefined : signalsByName[signal].description; + + const errorCode = error && error.code; + + const prefix = getErrorPrefix({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled}); + const execaMessage = `Command ${prefix}: ${command}`; + const isError = Object.prototype.toString.call(error) === '[object Error]'; + const shortMessage = isError ? `${execaMessage}\n${error.message}` : execaMessage; + const message = [shortMessage, stderr, stdout].filter(Boolean).join('\n'); + + if (isError) { + error.originalMessage = error.message; + error.message = message; + } else { + error = new Error(message); + } + + error.shortMessage = shortMessage; + error.command = command; + error.escapedCommand = escapedCommand; + error.exitCode = exitCode; + error.signal = signal; + error.signalDescription = signalDescription; + error.stdout = stdout; + error.stderr = stderr; + error.cwd = cwd; + + if (all !== undefined) { + error.all = all; + } + + if ('bufferedData' in error) { + delete error.bufferedData; + } + + error.failed = true; + error.timedOut = Boolean(timedOut); + error.isCanceled = isCanceled; + error.killed = killed && !timedOut; + + return error; +}; + +const aliases = ['stdin', 'stdout', 'stderr']; + +const hasAlias = options => aliases.some(alias => options[alias] !== undefined); + +const normalizeStdio = options => { + if (!options) { + return; + } + + const {stdio} = options; + + if (stdio === undefined) { + return aliases.map(alias => options[alias]); + } + + if (hasAlias(options)) { + throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${aliases.map(alias => `\`${alias}\``).join(', ')}`); + } + + if (typeof stdio === 'string') { + return stdio; + } + + if (!Array.isArray(stdio)) { + throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof stdio}\``); + } + + const length = Math.max(stdio.length, aliases.length); + return Array.from({length}, (value, index) => stdio[index]); +}; + +const DEFAULT_FORCE_KILL_TIMEOUT = 1000 * 5; + +// Monkey-patches `childProcess.kill()` to add `forceKillAfterTimeout` behavior +const spawnedKill = (kill, signal = 'SIGTERM', options = {}) => { + const killResult = kill(signal); + setKillTimeout(kill, signal, options, killResult); + return killResult; +}; + +const setKillTimeout = (kill, signal, options, killResult) => { + if (!shouldForceKill(signal, options, killResult)) { + return; + } + + const timeout = getForceKillAfterTimeout(options); + const t = setTimeout(() => { + kill('SIGKILL'); + }, timeout); + + // Guarded because there's no `.unref()` when `execa` is used in the renderer + // process in Electron. This cannot be tested since we don't run tests in + // Electron. + // istanbul ignore else + if (t.unref) { + t.unref(); + } +}; + +const shouldForceKill = (signal, {forceKillAfterTimeout}, killResult) => isSigterm(signal) && forceKillAfterTimeout !== false && killResult; + +const isSigterm = signal => signal === os$5.constants.signals.SIGTERM + || (typeof signal === 'string' && signal.toUpperCase() === 'SIGTERM'); + +const getForceKillAfterTimeout = ({forceKillAfterTimeout = true}) => { + if (forceKillAfterTimeout === true) { + return DEFAULT_FORCE_KILL_TIMEOUT; + } + + if (!Number.isFinite(forceKillAfterTimeout) || forceKillAfterTimeout < 0) { + throw new TypeError(`Expected the \`forceKillAfterTimeout\` option to be a non-negative integer, got \`${forceKillAfterTimeout}\` (${typeof forceKillAfterTimeout})`); + } + + return forceKillAfterTimeout; +}; + +// `childProcess.cancel()` +const spawnedCancel = (spawned, context) => { + const killResult = spawned.kill(); + + if (killResult) { + context.isCanceled = true; + } +}; + +const timeoutKill = (spawned, signal, reject) => { + spawned.kill(signal); + reject(Object.assign(new Error('Timed out'), {timedOut: true, signal})); +}; + +// `timeout` option handling +const setupTimeout = (spawned, {timeout, killSignal = 'SIGTERM'}, spawnedPromise) => { + if (timeout === 0 || timeout === undefined) { + return spawnedPromise; + } + + let timeoutId; + const timeoutPromise = new Promise((resolve, reject) => { + timeoutId = setTimeout(() => { + timeoutKill(spawned, killSignal, reject); + }, timeout); + }); + + const safeSpawnedPromise = spawnedPromise.finally(() => { + clearTimeout(timeoutId); + }); + + return Promise.race([timeoutPromise, safeSpawnedPromise]); +}; + +const validateTimeout = ({timeout}) => { + if (timeout !== undefined && (!Number.isFinite(timeout) || timeout < 0)) { + throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${timeout}\` (${typeof timeout})`); + } +}; + +// `cleanup` option handling +const setExitHandler = async (spawned, {cleanup, detached}, timedPromise) => { + if (!cleanup || detached) { + return timedPromise; + } + + const removeExitHandler = signalExit(() => { + spawned.kill(); + }); + + return timedPromise.finally(() => { + removeExitHandler(); + }); +}; + +function isStream(stream) { + return stream !== null + && typeof stream === 'object' + && typeof stream.pipe === 'function'; +} + +function isWritableStream(stream) { + return isStream(stream) + && stream.writable !== false + && typeof stream._write === 'function' + && typeof stream._writableState === 'object'; +} + +const isExecaChildProcess = target => target instanceof childProcess$1.ChildProcess && typeof target.then === 'function'; + +const pipeToTarget = (spawned, streamName, target) => { + if (typeof target === 'string') { + spawned[streamName].pipe(fs$i.createWriteStream(target)); + return spawned; + } + + if (isWritableStream(target)) { + spawned[streamName].pipe(target); + return spawned; + } + + if (!isExecaChildProcess(target)) { + throw new TypeError('The second argument must be a string, a stream or an Execa child process.'); + } + + if (!isWritableStream(target.stdin)) { + throw new TypeError('The target child process\'s stdin must be available.'); + } + + spawned[streamName].pipe(target.stdin); + return target; +}; + +const addPipeMethods = spawned => { + if (spawned.stdout !== null) { + spawned.pipeStdout = pipeToTarget.bind(undefined, spawned, 'stdout'); + } + + if (spawned.stderr !== null) { + spawned.pipeStderr = pipeToTarget.bind(undefined, spawned, 'stderr'); + } + + if (spawned.all !== undefined) { + spawned.pipeAll = pipeToTarget.bind(undefined, spawned, 'all'); + } +}; + +const validateInputOptions = input => { + if (input !== undefined) { + throw new TypeError('The `input` and `inputFile` options cannot be both set.'); + } +}; + +const getInput = ({input, inputFile}) => { + if (typeof inputFile !== 'string') { + return input; + } + + validateInputOptions(input); + return fs$i.createReadStream(inputFile); +}; + +// `input` and `inputFile` option in async mode +const handleInput = (spawned, options) => { + const input = getInput(options); + + if (input === undefined) { + return; + } + + if (isStream(input)) { + input.pipe(spawned.stdin); + } else { + spawned.stdin.end(input); + } +}; + +// `all` interleaves `stdout` and `stderr` +const makeAllStream = (spawned, {all}) => { + if (!all || (!spawned.stdout && !spawned.stderr)) { + return; + } + + const mixed = mergeStream$2(); + + if (spawned.stdout) { + mixed.add(spawned.stdout); + } + + if (spawned.stderr) { + mixed.add(spawned.stderr); + } + + return mixed; +}; + +// On failure, `result.stdout|stderr|all` should contain the currently buffered stream +const getBufferedData = async (stream, streamPromise) => { + // When `buffer` is `false`, `streamPromise` is `undefined` and there is no buffered data to retrieve + if (!stream || streamPromise === undefined) { + return; + } + + stream.destroy(); + + try { + return await streamPromise; + } catch (error) { + return error.bufferedData; + } +}; + +const getStreamPromise = (stream, {encoding, buffer, maxBuffer}) => { + if (!stream || !buffer) { + return; + } + + if (encoding) { + return getStream$3(stream, {encoding, maxBuffer}); + } + + return getStream$3.buffer(stream, {maxBuffer}); +}; + +// Retrieve result of child process: exit code, signal, error, streams (stdout/stderr/all) +const getSpawnedResult = async ({stdout, stderr, all}, {encoding, buffer, maxBuffer}, processDone) => { + const stdoutPromise = getStreamPromise(stdout, {encoding, buffer, maxBuffer}); + const stderrPromise = getStreamPromise(stderr, {encoding, buffer, maxBuffer}); + const allPromise = getStreamPromise(all, {encoding, buffer, maxBuffer: maxBuffer * 2}); + + try { + return await Promise.all([processDone, stdoutPromise, stderrPromise, allPromise]); + } catch (error) { + return Promise.all([ + {error, signal: error.signal, timedOut: error.timedOut}, + getBufferedData(stdout, stdoutPromise), + getBufferedData(stderr, stderrPromise), + getBufferedData(all, allPromise), + ]); + } +}; + +// eslint-disable-next-line unicorn/prefer-top-level-await +const nativePromisePrototype = (async () => {})().constructor.prototype; + +const descriptors = ['then', 'catch', 'finally'].map(property => [ + property, + Reflect.getOwnPropertyDescriptor(nativePromisePrototype, property), +]); + +// The return value is a mixin of `childProcess` and `Promise` +const mergePromise = (spawned, promise) => { + for (const [property, descriptor] of descriptors) { + // Starting the main `promise` is deferred to avoid consuming streams + const value = typeof promise === 'function' + ? (...args) => Reflect.apply(descriptor.value, promise(), args) + : descriptor.value.bind(promise); + + Reflect.defineProperty(spawned, property, {...descriptor, value}); + } +}; + +// Use promises instead of `child_process` events +const getSpawnedPromise = spawned => new Promise((resolve, reject) => { + spawned.on('exit', (exitCode, signal) => { + resolve({exitCode, signal}); + }); + + spawned.on('error', error => { + reject(error); + }); + + if (spawned.stdin) { + spawned.stdin.on('error', error => { + reject(error); + }); + } +}); + +const normalizeArgs$4 = (file, args = []) => { + if (!Array.isArray(args)) { + return [file]; + } + + return [file, ...args]; +}; + +const NO_ESCAPE_REGEXP = /^[\w.-]+$/; +const DOUBLE_QUOTES_REGEXP = /"/g; + +const escapeArg = arg => { + if (typeof arg !== 'string' || NO_ESCAPE_REGEXP.test(arg)) { + return arg; + } + + return `"${arg.replace(DOUBLE_QUOTES_REGEXP, '\\"')}"`; +}; + +const joinCommand = (file, args) => normalizeArgs$4(file, args).join(' '); + +const getEscapedCommand = (file, args) => normalizeArgs$4(file, args).map(arg => escapeArg(arg)).join(' '); + +const verboseDefault = node_util.debuglog('execa').enabled; + +const padField = (field, padding) => String(field).padStart(padding, '0'); + +const getTimestamp = () => { + const date = new Date(); + return `${padField(date.getHours(), 2)}:${padField(date.getMinutes(), 2)}:${padField(date.getSeconds(), 2)}.${padField(date.getMilliseconds(), 3)}`; +}; + +const logCommand = (escapedCommand, {verbose}) => { + if (!verbose) { + return; + } + + process$3.stderr.write(`[${getTimestamp()}] ${escapedCommand}\n`); +}; + +const DEFAULT_MAX_BUFFER = 1000 * 1000 * 100; + +const getEnv = ({env: envOption, extendEnv, preferLocal, localDir, execPath}) => { + const env = extendEnv ? {...process$3.env, ...envOption} : envOption; + + if (preferLocal) { + return npmRunPathEnv({env, cwd: localDir, execPath}); + } + + return env; +}; + +const handleArguments = (file, args, options = {}) => { + const parsed = crossSpawn$1._parse(file, args, options); + file = parsed.command; + args = parsed.args; + options = parsed.options; + + options = { + maxBuffer: DEFAULT_MAX_BUFFER, + buffer: true, + stripFinalNewline: true, + extendEnv: true, + preferLocal: false, + localDir: options.cwd || process$3.cwd(), + execPath: process$3.execPath, + encoding: 'utf8', + reject: true, + cleanup: true, + all: false, + windowsHide: true, + verbose: verboseDefault, + ...options, + }; + + options.env = getEnv(options); + + options.stdio = normalizeStdio(options); + + if (process$3.platform === 'win32' && path$c.basename(file, '.exe') === 'cmd') { + // #116 + args.unshift('/q'); + } + + return {file, args, options, parsed}; +}; + +const handleOutput = (options, value, error) => { + if (typeof value !== 'string' && !node_buffer.Buffer.isBuffer(value)) { + // When `execaSync()` errors, we normalize it to '' to mimic `execa()` + return error === undefined ? undefined : ''; + } + + if (options.stripFinalNewline) { + return stripFinalNewline(value); + } + + return value; +}; + +function execa(file, args, options) { + const parsed = handleArguments(file, args, options); + const command = joinCommand(file, args); + const escapedCommand = getEscapedCommand(file, args); + logCommand(escapedCommand, parsed.options); + + validateTimeout(parsed.options); + + let spawned; + try { + spawned = childProcess$1.spawn(parsed.file, parsed.args, parsed.options); + } catch (error) { + // Ensure the returned error is always both a promise and a child process + const dummySpawned = new childProcess$1.ChildProcess(); + const errorPromise = Promise.reject(makeError({ + error, + stdout: '', + stderr: '', + all: '', + command, + escapedCommand, + parsed, + timedOut: false, + isCanceled: false, + killed: false, + })); + mergePromise(dummySpawned, errorPromise); + return dummySpawned; + } + + const spawnedPromise = getSpawnedPromise(spawned); + const timedPromise = setupTimeout(spawned, parsed.options, spawnedPromise); + const processDone = setExitHandler(spawned, parsed.options, timedPromise); + + const context = {isCanceled: false}; + + spawned.kill = spawnedKill.bind(null, spawned.kill.bind(spawned)); + spawned.cancel = spawnedCancel.bind(null, spawned, context); + + const handlePromise = async () => { + const [{error, exitCode, signal, timedOut}, stdoutResult, stderrResult, allResult] = await getSpawnedResult(spawned, parsed.options, processDone); + const stdout = handleOutput(parsed.options, stdoutResult); + const stderr = handleOutput(parsed.options, stderrResult); + const all = handleOutput(parsed.options, allResult); + + if (error || exitCode !== 0 || signal !== null) { + const returnedError = makeError({ + error, + exitCode, + signal, + stdout, + stderr, + all, + command, + escapedCommand, + parsed, + timedOut, + isCanceled: (parsed.options.signal ? parsed.options.signal.aborted : false), + killed: spawned.killed, + }); + + if (!parsed.options.reject) { + return returnedError; + } + + throw returnedError; + } + + return { + command, + escapedCommand, + exitCode: 0, + stdout, + stderr, + all, + failed: false, + timedOut: false, + isCanceled: false, + killed: false, + }; + }; + + const handlePromiseOnce = onetime(handlePromise); + + handleInput(spawned, parsed.options); + + spawned.all = makeAllStream(spawned, parsed.options); + + addPipeMethods(spawned); + mergePromise(spawned, handlePromiseOnce); + return spawned; +} + +// Windows doesn't have browser IDs in the same way macOS/Linux does so we give fake +// ones that look real and match the macOS/Linux versions for cross-platform apps. +const windowsBrowserProgIds = { + AppXq0fevzme2pys62n3e0fbqa7peapykr8v: {name: 'Edge', id: 'com.microsoft.edge.old'}, + MSEdgeDHTML: {name: 'Edge', id: 'com.microsoft.edge'}, // On macOS, it's "com.microsoft.edgemac" + MSEdgeHTM: {name: 'Edge', id: 'com.microsoft.edge'}, // Newer Edge/Win10 releases + 'IE.HTTP': {name: 'Internet Explorer', id: 'com.microsoft.ie'}, + FirefoxURL: {name: 'Firefox', id: 'org.mozilla.firefox'}, + ChromeHTML: {name: 'Chrome', id: 'com.google.chrome'}, +}; + +class UnknownBrowserError extends Error {} + +async function defaultBrowser$1(_execa = execa) { + const result = await _execa('reg', [ + 'QUERY', + ' HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice', + '/v', + 'ProgId', + ]); + + const match = /ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(result.stdout); + if (!match) { + throw new UnknownBrowserError(`Cannot find Windows browser in stdout: ${JSON.stringify(result.stdout)}`); + } + + const {id} = match.groups; + + const browser = windowsBrowserProgIds[id]; + if (!browser) { + throw new UnknownBrowserError(`Unknown browser ID: ${id}`); + } + + return browser; +} + +async function defaultBrowser() { + if (process$3.platform === 'linux') { + const {stdout} = await execa('xdg-mime', ['query', 'default', 'x-scheme-handler/http']); + const name = titleize(stdout.trim().replace(/.desktop$/, '').replace('-', ' ')); + + return { + name, + id: stdout, + }; + } + + if (process$3.platform === 'darwin') { + const id = await defaultBrowserId(); + const name = await bundleName(id); + return {name, id}; + } + + if (process$3.platform === 'win32') { + return defaultBrowser$1(); + } + + throw new Error('Only macOS, Linux, and Windows are supported'); +} + +let isDockerCached; + +function hasDockerEnv() { + try { + fs$i.statSync('/.dockerenv'); + return true; + } catch { + return false; + } +} + +function hasDockerCGroup() { + try { + return fs$i.readFileSync('/proc/self/cgroup', 'utf8').includes('docker'); + } catch { + return false; + } +} + +function isDocker() { + // TODO: Use `??=` when targeting Node.js 16. + if (isDockerCached === undefined) { + isDockerCached = hasDockerEnv() || hasDockerCGroup(); + } + + return isDockerCached; +} + +let cachedResult; + +// Podman detection +const hasContainerEnv = () => { + try { + fs$i.statSync('/run/.containerenv'); + return true; + } catch { + return false; + } +}; + +function isInsideContainer() { + // TODO: Use `??=` when targeting Node.js 16. + if (cachedResult === undefined) { + cachedResult = hasContainerEnv() || isDocker(); + } + + return cachedResult; +} + +// Path to included `xdg-open`. +const __dirname$1 = path$c.dirname(urlLib.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('rollup-output.cjs', document.baseURI).href)))); +const localXdgOpenPath = path$c.join(__dirname$1, 'xdg-open'); + +const {platform, arch} = process$3; + +/** +Get the mount point for fixed drives in WSL. + +@inner +@returns {string} The mount point. +*/ +const getWslDrivesMountPoint = (() => { + // Default value for "root" param + // according to https://docs.microsoft.com/en-us/windows/wsl/wsl-config + const defaultMountPoint = '/mnt/'; + + let mountPoint; + + return async function () { + if (mountPoint) { + // Return memoized mount point value + return mountPoint; + } + + const configFilePath = '/etc/wsl.conf'; + + let isConfigFileExists = false; + try { + await fs$j.access(configFilePath, fs$i.constants.F_OK); + isConfigFileExists = true; + } catch {} + + if (!isConfigFileExists) { + return defaultMountPoint; + } + + const configContent = await fs$j.readFile(configFilePath, {encoding: 'utf8'}); + const configMountPoint = /(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(configContent); + + if (!configMountPoint) { + return defaultMountPoint; + } + + mountPoint = configMountPoint.groups.mountPoint.trim(); + mountPoint = mountPoint.endsWith('/') ? mountPoint : `${mountPoint}/`; + + return mountPoint; + }; +})(); + +const pTryEach = async (array, mapper) => { + let latestError; + + for (const item of array) { + try { + return await mapper(item); // eslint-disable-line no-await-in-loop + } catch (error) { + latestError = error; + } + } + + throw latestError; +}; + +const baseOpen = async options => { + options = { + wait: false, + background: false, + newInstance: false, + allowNonzeroExitCode: false, + ...options, + }; + + if (Array.isArray(options.app)) { + return pTryEach(options.app, singleApp => baseOpen({ + ...options, + app: singleApp, + })); + } + + let {name: app, arguments: appArguments = []} = options.app ?? {}; + appArguments = [...appArguments]; + + if (Array.isArray(app)) { + return pTryEach(app, appName => baseOpen({ + ...options, + app: { + name: appName, + arguments: appArguments, + }, + })); + } + + if (app === 'browser' || app === 'browserPrivate') { + // IDs from default-browser for macOS and windows are the same + const ids = { + 'com.google.chrome': 'chrome', + 'google-chrome.desktop': 'chrome', + 'org.mozilla.firefox': 'firefox', + 'firefox.desktop': 'firefox', + 'com.microsoft.msedge': 'edge', + 'com.microsoft.edge': 'edge', + 'microsoft-edge.desktop': 'edge', + }; + + // Incognito flags for each browser in `apps`. + const flags = { + chrome: '--incognito', + firefox: '--private-window', + edge: '--inPrivate', + }; + + const browser = await defaultBrowser(); + if (browser.id in ids) { + const browserName = ids[browser.id]; + + if (app === 'browserPrivate') { + appArguments.push(flags[browserName]); + } + + return baseOpen({ + ...options, + app: { + name: apps[browserName], + arguments: appArguments, + }, + }); + } + + throw new Error(`${browser.name} is not supported as a default browser`); + } + + let command; + const cliArguments = []; + const childProcessOptions = {}; + + if (platform === 'darwin') { + command = 'open'; + + if (options.wait) { + cliArguments.push('--wait-apps'); + } + + if (options.background) { + cliArguments.push('--background'); + } + + if (options.newInstance) { + cliArguments.push('--new'); + } + + if (app) { + cliArguments.push('-a', app); + } + } else if (platform === 'win32' || (isWsl$1 && !isInsideContainer() && !app)) { + const mountPoint = await getWslDrivesMountPoint(); + + command = isWsl$1 + ? `${mountPoint}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe` + : `${process$3.env.SYSTEMROOT}\\System32\\WindowsPowerShell\\v1.0\\powershell`; + + cliArguments.push( + '-NoProfile', + '-NonInteractive', + '-ExecutionPolicy', + 'Bypass', + '-EncodedCommand', + ); + + if (!isWsl$1) { + childProcessOptions.windowsVerbatimArguments = true; + } + + const encodedArguments = ['Start']; + + if (options.wait) { + encodedArguments.push('-Wait'); + } + + if (app) { + // Double quote with double quotes to ensure the inner quotes are passed through. + // Inner quotes are delimited for PowerShell interpretation with backticks. + encodedArguments.push(`"\`"${app}\`""`); + if (options.target) { + appArguments.push(options.target); + } + } else if (options.target) { + encodedArguments.push(`"${options.target}"`); + } + + if (appArguments.length > 0) { + appArguments = appArguments.map(arg => `"\`"${arg}\`""`); + encodedArguments.push('-ArgumentList', appArguments.join(',')); + } + + // Using Base64-encoded command, accepted by PowerShell, to allow special characters. + options.target = node_buffer.Buffer.from(encodedArguments.join(' '), 'utf16le').toString('base64'); + } else { + if (app) { + command = app; + } else { + // When bundled by Webpack, there's no actual package file path and no local `xdg-open`. + const isBundled = !__dirname$1 || __dirname$1 === '/'; + + // Check if local `xdg-open` exists and is executable. + let exeLocalXdgOpen = false; + try { + await fs$j.access(localXdgOpenPath, fs$i.constants.X_OK); + exeLocalXdgOpen = true; + } catch {} + + const useSystemXdgOpen = process$3.versions.electron + ?? (platform === 'android' || isBundled || !exeLocalXdgOpen); + command = useSystemXdgOpen ? 'xdg-open' : localXdgOpenPath; + } + + if (appArguments.length > 0) { + cliArguments.push(...appArguments); + } + + if (!options.wait) { + // `xdg-open` will block the process unless stdio is ignored + // and it's detached from the parent even if it's unref'd. + childProcessOptions.stdio = 'ignore'; + childProcessOptions.detached = true; + } + } + + if (options.target) { + cliArguments.push(options.target); + } + + if (platform === 'darwin' && appArguments.length > 0) { + cliArguments.push('--args', ...appArguments); + } + + const subprocess = childProcess$1.spawn(command, cliArguments, childProcessOptions); + + if (options.wait) { + return new Promise((resolve, reject) => { + subprocess.once('error', reject); + + subprocess.once('close', exitCode => { + if (!options.allowNonzeroExitCode && exitCode > 0) { + reject(new Error(`Exited with code ${exitCode}`)); + return; + } + + resolve(subprocess); + }); + }); + } + + subprocess.unref(); + + return subprocess; +}; + +const open = (target, options) => { + if (typeof target !== 'string') { + throw new TypeError('Expected a `target`'); + } + + return baseOpen({ + ...options, + target, + }); +}; + +function detectArchBinary(binary) { + if (typeof binary === 'string' || Array.isArray(binary)) { + return binary; + } + + const {[arch]: archBinary} = binary; + + if (!archBinary) { + throw new Error(`${arch} is not supported`); + } + + return archBinary; +} + +function detectPlatformBinary({[platform]: platformBinary}, {wsl}) { + if (wsl && isWsl$1) { + return detectArchBinary(wsl); + } + + if (!platformBinary) { + throw new Error(`${platform} is not supported`); + } + + return detectArchBinary(platformBinary); +} + +const apps = {}; + +defineLazyProperty(apps, 'chrome', () => detectPlatformBinary({ + darwin: 'google chrome', + win32: 'chrome', + linux: ['google-chrome', 'google-chrome-stable', 'chromium'], +}, { + wsl: { + ia32: '/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe', + x64: ['/mnt/c/Program Files/Google/Chrome/Application/chrome.exe', '/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe'], + }, +})); + +defineLazyProperty(apps, 'firefox', () => detectPlatformBinary({ + darwin: 'firefox', + win32: 'C:\\Program Files\\Mozilla Firefox\\firefox.exe', + linux: 'firefox', +}, { + wsl: '/mnt/c/Program Files/Mozilla Firefox/firefox.exe', +})); + +defineLazyProperty(apps, 'edge', () => detectPlatformBinary({ + darwin: 'microsoft edge', + win32: 'msedge', + linux: ['microsoft-edge', 'microsoft-edge-dev'], +}, { + wsl: '/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe', +})); + +defineLazyProperty(apps, 'browser', () => 'browser'); + +defineLazyProperty(apps, 'browserPrivate', () => 'browserPrivate'); + +class OpenCommand extends Command { + constructor() { + super(); + this.command = 'open'; + this.usage = 'open'; + this.description = 'Open your current ReadMe project in the browser.'; + this.cmdCategory = CommandCategories.UTILITIES; + this.args = [ + { + name: 'dash', + type: Boolean, + description: 'Opens your current ReadMe project dashboard.', + }, + ]; + } + async run(opts) { + await super.run(opts); + const { dash } = opts; + const { apiKey, project } = getCurrentConfig(); + Command.debug(`project: ${project}`); + if (!project) { + return Promise.reject(new Error(`Please login using \`${config.cli} login\`.`)); + } + let url; + if (dash) { + if (!apiKey) { + return Promise.reject(new Error(`Please login using \`${config.cli} login\`.`)); + } + const selectedVersion = await getProjectVersion(undefined, apiKey, true); + const dashURL = config.host; + url = `${dashURL}/project/${project}/v${selectedVersion}/overview`; + } + else { + const hubURL = config.hub; + url = hubURL.replace('{project}', project); + } + return (opts.mockOpen || open)(url, { + wait: false, + }).then(() => Promise.resolve(`Opening ${chalk$5.green(url)} in your browser...`)); + } +} + +/*! js-yaml 4.1.0 https://github.com/nodeca/js-yaml @license MIT */ +function isNothing$1(subject) { + return (typeof subject === 'undefined') || (subject === null); +} + + +function isObject$l(subject) { + return (typeof subject === 'object') && (subject !== null); +} + + +function toArray$3(sequence) { + if (Array.isArray(sequence)) return sequence; + else if (isNothing$1(sequence)) return []; + + return [ sequence ]; +} + + +function extend$2(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$2(string, count) { + var result = '', cycle; + + for (cycle = 0; cycle < count; cycle += 1) { + result += string; + } + + return result; +} + + +function isNegativeZero$1(number) { + return (number === 0) && (Number.NEGATIVE_INFINITY === 1 / number); +} + + +var isNothing_1 = isNothing$1; +var isObject_1$1 = isObject$l; +var toArray_1 = toArray$3; +var repeat_1 = repeat$2; +var isNegativeZero_1 = isNegativeZero$1; +var extend_1 = extend$2; + +var common$a = { + isNothing: isNothing_1, + isObject: isObject_1$1, + toArray: toArray_1, + repeat: repeat_1, + isNegativeZero: isNegativeZero_1, + extend: extend_1 +}; + +// YAML error class. http://stackoverflow.com/questions/8458984 + + +function formatError$1(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$1$1(reason, mark) { + // Super constructor + Error.call(this); + + this.name = 'YAMLException'; + this.reason = reason; + this.mark = mark; + this.message = formatError$1(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$1$1.prototype = Object.create(Error.prototype); +YAMLException$1$1.prototype.constructor = YAMLException$1$1; + + +YAMLException$1$1.prototype.toString = function toString(compact) { + return this.name + ': ' + formatError$1(this, compact); +}; + + +var exception$1 = YAMLException$1$1; + +// get snippet for a single line, respecting maxLength +function getLine$2(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$1(string, max) { + return common$a.repeat(' ', max - string.length) + string; +} + + +function makeSnippet$2(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$2( + mark.buffer, + lineStarts[foundLineNo - i], + lineEnds[foundLineNo - i], + mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i]), + maxLineLength + ); + result = common$a.repeat(' ', options.indent) + padStart$1((mark.line - i + 1).toString(), lineNoLength) + + ' | ' + line.str + '\n' + result; + } + + line = getLine$2(mark.buffer, lineStarts[foundLineNo], lineEnds[foundLineNo], mark.position, maxLineLength); + result += common$a.repeat(' ', options.indent) + padStart$1((mark.line + 1).toString(), lineNoLength) + + ' | ' + line.str + '\n'; + result += common$a.repeat('-', options.indent + lineNoLength + 3 + line.pos) + '^' + '\n'; + + for (i = 1; i <= options.linesAfter; i++) { + if (foundLineNo + i >= lineEnds.length) break; + line = getLine$2( + mark.buffer, + lineStarts[foundLineNo + i], + lineEnds[foundLineNo + i], + mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i]), + maxLineLength + ); + result += common$a.repeat(' ', options.indent) + padStart$1((mark.line + i + 1).toString(), lineNoLength) + + ' | ' + line.str + '\n'; + } + + return result.replace(/\n$/, ''); +} + + +var snippet$1 = makeSnippet$2; + +var TYPE_CONSTRUCTOR_OPTIONS$1 = [ + 'kind', + 'multi', + 'resolve', + 'construct', + 'instanceOf', + 'predicate', + 'represent', + 'representName', + 'defaultStyle', + 'styleAliases' +]; + +var YAML_NODE_KINDS$1 = [ + 'scalar', + 'sequence', + 'mapping' +]; + +function compileStyleAliases$1(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$1$1(tag, options) { + options = options || {}; + + Object.keys(options).forEach(function (name) { + if (TYPE_CONSTRUCTOR_OPTIONS$1.indexOf(name) === -1) { + throw new exception$1('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$1(options['styleAliases'] || null); + + if (YAML_NODE_KINDS$1.indexOf(this.kind) === -1) { + throw new exception$1('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.'); + } +} + +var type$f = Type$1$1; + +/*eslint-disable max-len*/ + + + + + +function compileList$1(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$1(/* 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$1$1(definition) { + return this.extend(definition); +} + + +Schema$1$1.prototype.extend = function extend(definition) { + var implicit = []; + var explicit = []; + + if (definition instanceof type$f) { + // 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 exception$1('Schema.extend argument should be a Type, [ Type ], ' + + 'or a schema definition ({ implicit: [...], explicit: [...] })'); + } + + implicit.forEach(function (type$1) { + if (!(type$1 instanceof type$f)) { + throw new exception$1('Specified list of YAML types (or a single Type object) contains a non-Type object.'); + } + + if (type$1.loadKind && type$1.loadKind !== 'scalar') { + throw new exception$1('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.'); + } + + if (type$1.multi) { + throw new exception$1('There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.'); + } + }); + + explicit.forEach(function (type$1) { + if (!(type$1 instanceof type$f)) { + throw new exception$1('Specified list of YAML types (or a single Type object) contains a non-Type object.'); + } + }); + + var result = Object.create(Schema$1$1.prototype); + + result.implicit = (this.implicit || []).concat(implicit); + result.explicit = (this.explicit || []).concat(explicit); + + result.compiledImplicit = compileList$1(result, 'implicit'); + result.compiledExplicit = compileList$1(result, 'explicit'); + result.compiledTypeMap = compileMap$1(result.compiledImplicit, result.compiledExplicit); + + return result; +}; + + +var schema$2 = Schema$1$1; + +var str$1 = new type$f('tag:yaml.org,2002:str', { + kind: 'scalar', + construct: function (data) { return data !== null ? data : ''; } +}); + +var seq$2 = new type$f('tag:yaml.org,2002:seq', { + kind: 'sequence', + construct: function (data) { return data !== null ? data : []; } +}); + +var map$4 = new type$f('tag:yaml.org,2002:map', { + kind: 'mapping', + construct: function (data) { return data !== null ? data : {}; } +}); + +var failsafe$2 = new schema$2({ + explicit: [ + str$1, + seq$2, + map$4 + ] +}); + +function resolveYamlNull$1(data) { + if (data === null) return true; + + var max = data.length; + + return (max === 1 && data === '~') || + (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL')); +} + +function constructYamlNull$1() { + return null; +} + +function isNull$3(object) { + return object === null; +} + +var _null$1 = new type$f('tag:yaml.org,2002:null', { + kind: 'scalar', + resolve: resolveYamlNull$1, + construct: constructYamlNull$1, + predicate: isNull$3, + represent: { + canonical: function () { return '~'; }, + lowercase: function () { return 'null'; }, + uppercase: function () { return 'NULL'; }, + camelcase: function () { return 'Null'; }, + empty: function () { return ''; } + }, + defaultStyle: 'lowercase' +}); + +function resolveYamlBoolean$1(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$1(data) { + return data === 'true' || + data === 'True' || + data === 'TRUE'; +} + +function isBoolean$3(object) { + return Object.prototype.toString.call(object) === '[object Boolean]'; +} + +var bool$1 = new type$f('tag:yaml.org,2002:bool', { + kind: 'scalar', + resolve: resolveYamlBoolean$1, + construct: constructYamlBoolean$1, + predicate: isBoolean$3, + represent: { + lowercase: function (object) { return object ? 'true' : 'false'; }, + uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; }, + camelcase: function (object) { return object ? 'True' : 'False'; } + }, + defaultStyle: 'lowercase' +}); + +function isHexCode$1(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) || + ((0x41/* A */ <= c) && (c <= 0x46/* F */)) || + ((0x61/* a */ <= c) && (c <= 0x66/* f */)); +} + +function isOctCode$1(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */)); +} + +function isDecCode$1(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)); +} + +function resolveYamlInteger$1(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$1(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$1(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$1(data.charCodeAt(index))) { + return false; + } + hasDigits = true; + } + + // Should have digits and should not end with `_` + if (!hasDigits || ch === '_') return false; + + return true; +} + +function constructYamlInteger$1(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$3(object) { + return (Object.prototype.toString.call(object)) === '[object Number]' && + (object % 1 === 0 && !common$a.isNegativeZero(object)); +} + +var int$1 = new type$f('tag:yaml.org,2002:int', { + kind: 'scalar', + resolve: resolveYamlInteger$1, + construct: constructYamlInteger$1, + predicate: isInteger$3, + 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' ] + } +}); + +var YAML_FLOAT_PATTERN$1 = 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$1(data) { + if (data === null) return false; + + if (!YAML_FLOAT_PATTERN$1.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$1(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$1 = /^[-+]?[0-9]+e/; + +function representYamlFloat$1(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$a.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$1.test(res) ? res.replace('e', '.e') : res; +} + +function isFloat$1(object) { + return (Object.prototype.toString.call(object) === '[object Number]') && + (object % 1 !== 0 || common$a.isNegativeZero(object)); +} + +var float$1 = new type$f('tag:yaml.org,2002:float', { + kind: 'scalar', + resolve: resolveYamlFloat$1, + construct: constructYamlFloat$1, + predicate: isFloat$1, + represent: representYamlFloat$1, + defaultStyle: 'lowercase' +}); + +var json$4 = failsafe$2.extend({ + implicit: [ + _null$1, + bool$1, + int$1, + float$1 + ] +}); + +var core$8 = json$4; + +var YAML_DATE_REGEXP$1 = 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$1 = 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$1(data) { + if (data === null) return false; + if (YAML_DATE_REGEXP$1.exec(data) !== null) return true; + if (YAML_TIMESTAMP_REGEXP$1.exec(data) !== null) return true; + return false; +} + +function constructYamlTimestamp$1(data) { + var match, year, month, day, hour, minute, second, fraction = 0, + delta = null, tz_hour, tz_minute, date; + + match = YAML_DATE_REGEXP$1.exec(data); + if (match === null) match = YAML_TIMESTAMP_REGEXP$1.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$1(object /*, style*/) { + return object.toISOString(); +} + +var timestamp$2 = new type$f('tag:yaml.org,2002:timestamp', { + kind: 'scalar', + resolve: resolveYamlTimestamp$1, + construct: constructYamlTimestamp$1, + instanceOf: Date, + represent: representYamlTimestamp$1 +}); + +function resolveYamlMerge$1(data) { + return data === '<<' || data === null; +} + +var merge$2 = new type$f('tag:yaml.org,2002:merge', { + kind: 'scalar', + resolve: resolveYamlMerge$1 +}); + +/*eslint-disable no-bitwise*/ + + + + + +// [ 64, 65, 66 ] -> [ padding, CR, LF ] +var BASE64_MAP$1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r'; + + +function resolveYamlBinary$1(data) { + if (data === null) return false; + + var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP$1; + + // 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$1(data) { + var idx, tailbits, + input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to simplify scan + max = input.length, + map = BASE64_MAP$1, + 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$1(object /*, style*/) { + var result = '', bits = 0, idx, tail, + max = object.length, + map = BASE64_MAP$1; + + // 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$1(obj) { + return Object.prototype.toString.call(obj) === '[object Uint8Array]'; +} + +var binary$4 = new type$f('tag:yaml.org,2002:binary', { + kind: 'scalar', + resolve: resolveYamlBinary$1, + construct: constructYamlBinary$1, + predicate: isBinary$1, + represent: representYamlBinary$1 +}); + +var _hasOwnProperty$3$1 = Object.prototype.hasOwnProperty; +var _toString$2$1 = Object.prototype.toString; + +function resolveYamlOmap$1(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$1.call(pair) !== '[object Object]') return false; + + for (pairKey in pair) { + if (_hasOwnProperty$3$1.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$1(data) { + return data !== null ? data : []; +} + +var omap$2 = new type$f('tag:yaml.org,2002:omap', { + kind: 'sequence', + resolve: resolveYamlOmap$1, + construct: constructYamlOmap$1 +}); + +var _toString$1$1 = Object.prototype.toString; + +function resolveYamlPairs$1(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$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$1(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$2 = new type$f('tag:yaml.org,2002:pairs', { + kind: 'sequence', + resolve: resolveYamlPairs$1, + construct: constructYamlPairs$1 +}); + +var _hasOwnProperty$2$1 = Object.prototype.hasOwnProperty; + +function resolveYamlSet$1(data) { + if (data === null) return true; + + var key, object = data; + + for (key in object) { + if (_hasOwnProperty$2$1.call(object, key)) { + if (object[key] !== null) return false; + } + } + + return true; +} + +function constructYamlSet$1(data) { + return data !== null ? data : {}; +} + +var set$3 = new type$f('tag:yaml.org,2002:set', { + kind: 'mapping', + resolve: resolveYamlSet$1, + construct: constructYamlSet$1 +}); + +var _default$2 = core$8.extend({ + implicit: [ + timestamp$2, + merge$2 + ], + explicit: [ + binary$4, + omap$2, + pairs$2, + set$3 + ] +}); + +/*eslint-disable max-len,no-use-before-define*/ + + + + + + + +var _hasOwnProperty$1$1 = Object.prototype.hasOwnProperty; + + +var CONTEXT_FLOW_IN$1 = 1; +var CONTEXT_FLOW_OUT$1 = 2; +var CONTEXT_BLOCK_IN$1 = 3; +var CONTEXT_BLOCK_OUT$1 = 4; + + +var CHOMPING_CLIP$1 = 1; +var CHOMPING_STRIP$1 = 2; +var CHOMPING_KEEP$1 = 3; + + +var PATTERN_NON_PRINTABLE$1 = /[\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$1 = /[\x85\u2028\u2029]/; +var PATTERN_FLOW_INDICATORS$1 = /[,\[\]\{\}]/; +var PATTERN_TAG_HANDLE$1 = /^(?:!|!!|![a-z\-]+!)$/i; +var PATTERN_TAG_URI$1 = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i; + + +function _class$1(obj) { return Object.prototype.toString.call(obj); } + +function is_EOL$1(c) { + return (c === 0x0A/* LF */) || (c === 0x0D/* CR */); +} + +function is_WHITE_SPACE$1(c) { + return (c === 0x09/* Tab */) || (c === 0x20/* Space */); +} + +function is_WS_OR_EOL$1(c) { + return (c === 0x09/* Tab */) || + (c === 0x20/* Space */) || + (c === 0x0A/* LF */) || + (c === 0x0D/* CR */); +} + +function is_FLOW_INDICATOR$1(c) { + return c === 0x2C/* , */ || + c === 0x5B/* [ */ || + c === 0x5D/* ] */ || + c === 0x7B/* { */ || + c === 0x7D/* } */; +} + +function fromHexCode$1(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$1(c) { + if (c === 0x78/* x */) { return 2; } + if (c === 0x75/* u */) { return 4; } + if (c === 0x55/* U */) { return 8; } + return 0; +} + +function fromDecimalCode$1(c) { + if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { + return c - 0x30; + } + + return -1; +} + +function simpleEscapeSequence$1(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$1(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$1 = new Array(256); // integer, for fast access +var simpleEscapeMap$1 = new Array(256); +for (var i$2 = 0; i$2 < 256; i$2++) { + simpleEscapeCheck$1[i$2] = simpleEscapeSequence$1(i$2) ? 1 : 0; + simpleEscapeMap$1[i$2] = simpleEscapeSequence$1(i$2); +} + + +function State$1$1(input, options) { + this.input = input; + + this.filename = options['filename'] || null; + this.schema = options['schema'] || _default$2; + 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$1(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 = snippet$1(mark); + + return new exception$1(message, mark); +} + +function throwError$2(state, message) { + throw generateError$1(state, message); +} + +function throwWarning$1(state, message) { + if (state.onWarning) { + state.onWarning.call(null, generateError$1(state, message)); + } +} + + +var directiveHandlers$1 = { + + YAML: function handleYamlDirective(state, name, args) { + + var match, major, minor; + + if (state.version !== null) { + throwError$2(state, 'duplication of %YAML directive'); + } + + if (args.length !== 1) { + throwError$2(state, 'YAML directive accepts exactly one argument'); + } + + match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]); + + if (match === null) { + throwError$2(state, 'ill-formed argument of the YAML directive'); + } + + major = parseInt(match[1], 10); + minor = parseInt(match[2], 10); + + if (major !== 1) { + throwError$2(state, 'unacceptable YAML version of the document'); + } + + state.version = args[0]; + state.checkLineBreaks = (minor < 2); + + if (minor !== 1 && minor !== 2) { + throwWarning$1(state, 'unsupported YAML version of the document'); + } + }, + + TAG: function handleTagDirective(state, name, args) { + + var handle, prefix; + + if (args.length !== 2) { + throwError$2(state, 'TAG directive accepts exactly two arguments'); + } + + handle = args[0]; + prefix = args[1]; + + if (!PATTERN_TAG_HANDLE$1.test(handle)) { + throwError$2(state, 'ill-formed tag handle (first argument) of the TAG directive'); + } + + if (_hasOwnProperty$1$1.call(state.tagMap, handle)) { + throwError$2(state, 'there is a previously declared suffix for "' + handle + '" tag handle'); + } + + if (!PATTERN_TAG_URI$1.test(prefix)) { + throwError$2(state, 'ill-formed tag prefix (second argument) of the TAG directive'); + } + + try { + prefix = decodeURIComponent(prefix); + } catch (err) { + throwError$2(state, 'tag prefix is malformed: ' + prefix); + } + + state.tagMap[handle] = prefix; + } +}; + + +function captureSegment$1(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$2(state, 'expected valid JSON character'); + } + } + } else if (PATTERN_NON_PRINTABLE$1.test(_result)) { + throwError$2(state, 'the stream contains non-printable characters'); + } + + state.result += _result; + } +} + +function mergeMappings$1(state, destination, source, overridableKeys) { + var sourceKeys, key, index, quantity; + + if (!common$a.isObject(source)) { + throwError$2(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$1.call(destination, key)) { + destination[key] = source[key]; + overridableKeys[key] = true; + } + } +} + +function storeMappingPair$1(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$2(state, 'nested arrays are not supported inside keys'); + } + + if (typeof keyNode === 'object' && _class$1(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$1(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$1(state, _result, valueNode[index], overridableKeys); + } + } else { + mergeMappings$1(state, _result, valueNode, overridableKeys); + } + } else { + if (!state.json && + !_hasOwnProperty$1$1.call(overridableKeys, keyNode) && + _hasOwnProperty$1$1.call(_result, keyNode)) { + state.line = startLine || state.line; + state.lineStart = startLineStart || state.lineStart; + state.position = startPos || state.position; + throwError$2(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$1(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$2(state, 'a line break is expected'); + } + + state.line += 1; + state.lineStart = state.position; + state.firstTabInLine = -1; +} + +function skipSeparationSpace$1(state, allowComments, checkIndent) { + var lineBreaks = 0, + ch = state.input.charCodeAt(state.position); + + while (ch !== 0) { + while (is_WHITE_SPACE$1(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$1(ch)) { + readLineBreak$1(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$1(state, 'deficient indentation'); + } + + return lineBreaks; +} + +function testDocumentSeparator$1(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$1(ch)) { + return true; + } + } + + return false; +} + +function writeFoldedLines$1(state, count) { + if (count === 1) { + state.result += ' '; + } else if (count > 1) { + state.result += common$a.repeat('\n', count - 1); + } +} + + +function readPlainScalar$1(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$1(ch) || + is_FLOW_INDICATOR$1(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$1(following) || + withinFlowCollection && is_FLOW_INDICATOR$1(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$1(following) || + withinFlowCollection && is_FLOW_INDICATOR$1(following)) { + break; + } + + } else if (ch === 0x23/* # */) { + preceding = state.input.charCodeAt(state.position - 1); + + if (is_WS_OR_EOL$1(preceding)) { + break; + } + + } else if ((state.position === state.lineStart && testDocumentSeparator$1(state)) || + withinFlowCollection && is_FLOW_INDICATOR$1(ch)) { + break; + + } else if (is_EOL$1(ch)) { + _line = state.line; + _lineStart = state.lineStart; + _lineIndent = state.lineIndent; + skipSeparationSpace$1(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$1(state, captureStart, captureEnd, false); + writeFoldedLines$1(state, state.line - _line); + captureStart = captureEnd = state.position; + hasPendingContent = false; + } + + if (!is_WHITE_SPACE$1(ch)) { + captureEnd = state.position + 1; + } + + ch = state.input.charCodeAt(++state.position); + } + + captureSegment$1(state, captureStart, captureEnd, false); + + if (state.result) { + return true; + } + + state.kind = _kind; + state.result = _result; + return false; +} + +function readSingleQuotedScalar$1(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$1(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$1(ch)) { + captureSegment$1(state, captureStart, captureEnd, true); + writeFoldedLines$1(state, skipSeparationSpace$1(state, false, nodeIndent)); + captureStart = captureEnd = state.position; + + } else if (state.position === state.lineStart && testDocumentSeparator$1(state)) { + throwError$2(state, 'unexpected end of the document within a single quoted scalar'); + + } else { + state.position++; + captureEnd = state.position; + } + } + + throwError$2(state, 'unexpected end of the stream within a single quoted scalar'); +} + +function readDoubleQuotedScalar$1(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$1(state, captureStart, state.position, true); + state.position++; + return true; + + } else if (ch === 0x5C/* \ */) { + captureSegment$1(state, captureStart, state.position, true); + ch = state.input.charCodeAt(++state.position); + + if (is_EOL$1(ch)) { + skipSeparationSpace$1(state, false, nodeIndent); + + // TODO: rework to inline fn with no type cast? + } else if (ch < 256 && simpleEscapeCheck$1[ch]) { + state.result += simpleEscapeMap$1[ch]; + state.position++; + + } else if ((tmp = escapedHexLen$1(ch)) > 0) { + hexLength = tmp; + hexResult = 0; + + for (; hexLength > 0; hexLength--) { + ch = state.input.charCodeAt(++state.position); + + if ((tmp = fromHexCode$1(ch)) >= 0) { + hexResult = (hexResult << 4) + tmp; + + } else { + throwError$2(state, 'expected hexadecimal character'); + } + } + + state.result += charFromCodepoint$1(hexResult); + + state.position++; + + } else { + throwError$2(state, 'unknown escape sequence'); + } + + captureStart = captureEnd = state.position; + + } else if (is_EOL$1(ch)) { + captureSegment$1(state, captureStart, captureEnd, true); + writeFoldedLines$1(state, skipSeparationSpace$1(state, false, nodeIndent)); + captureStart = captureEnd = state.position; + + } else if (state.position === state.lineStart && testDocumentSeparator$1(state)) { + throwError$2(state, 'unexpected end of the document within a double quoted scalar'); + + } else { + state.position++; + captureEnd = state.position; + } + } + + throwError$2(state, 'unexpected end of the stream within a double quoted scalar'); +} + +function readFlowCollection$1(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$1(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$2(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$2(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$1(following)) { + isPair = isExplicitPair = true; + state.position++; + skipSeparationSpace$1(state, true, nodeIndent); + } + } + + _line = state.line; // Save the current line. + _lineStart = state.lineStart; + _pos = state.position; + composeNode$1(state, nodeIndent, CONTEXT_FLOW_IN$1, false, true); + keyTag = state.tag; + keyNode = state.result; + skipSeparationSpace$1(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$1(state, true, nodeIndent); + composeNode$1(state, nodeIndent, CONTEXT_FLOW_IN$1, false, true); + valueNode = state.result; + } + + if (isMapping) { + storeMappingPair$1(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos); + } else if (isPair) { + _result.push(storeMappingPair$1(state, null, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos)); + } else { + _result.push(keyNode); + } + + skipSeparationSpace$1(state, true, nodeIndent); + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x2C/* , */) { + readNext = true; + ch = state.input.charCodeAt(++state.position); + } else { + readNext = false; + } + } + + throwError$2(state, 'unexpected end of the stream within a flow collection'); +} + +function readBlockScalar$1(state, nodeIndent) { + var captureStart, + folding, + chomping = CHOMPING_CLIP$1, + 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$1 === chomping) { + chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP$1 : CHOMPING_STRIP$1; + } else { + throwError$2(state, 'repeat of a chomping mode identifier'); + } + + } else if ((tmp = fromDecimalCode$1(ch)) >= 0) { + if (tmp === 0) { + throwError$2(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$2(state, 'repeat of an indentation width identifier'); + } + + } else { + break; + } + } + + if (is_WHITE_SPACE$1(ch)) { + do { ch = state.input.charCodeAt(++state.position); } + while (is_WHITE_SPACE$1(ch)); + + if (ch === 0x23/* # */) { + do { ch = state.input.charCodeAt(++state.position); } + while (!is_EOL$1(ch) && (ch !== 0)); + } + } + + while (ch !== 0) { + readLineBreak$1(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$1(ch)) { + emptyLines++; + continue; + } + + // End of the scalar. + if (state.lineIndent < textIndent) { + + // Perform the chomping. + if (chomping === CHOMPING_KEEP$1) { + state.result += common$a.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + } else if (chomping === CHOMPING_CLIP$1) { + 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$1(ch)) { + atMoreIndented = true; + // except for the first content line (cf. Example 8.1) + state.result += common$a.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + + // End of more-indented block. + } else if (atMoreIndented) { + atMoreIndented = false; + state.result += common$a.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$a.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$a.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + } + + didReadContent = true; + detectedIndent = true; + emptyLines = 0; + captureStart = state.position; + + while (!is_EOL$1(ch) && (ch !== 0)) { + ch = state.input.charCodeAt(++state.position); + } + + captureSegment$1(state, captureStart, state.position, false); + } + + return true; +} + +function readBlockSequence$1(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$2(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$1(following)) { + break; + } + + detected = true; + state.position++; + + if (skipSeparationSpace$1(state, true, -1)) { + if (state.lineIndent <= nodeIndent) { + _result.push(null); + ch = state.input.charCodeAt(state.position); + continue; + } + } + + _line = state.line; + composeNode$1(state, nodeIndent, CONTEXT_BLOCK_IN$1, false, true); + _result.push(state.result); + skipSeparationSpace$1(state, true, -1); + + ch = state.input.charCodeAt(state.position); + + if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { + throwError$2(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$1(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$2(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$1(following)) { + + if (ch === 0x3F/* ? */) { + if (atExplicitKey) { + storeMappingPair$1(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$2(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$1(state, flowIndent, CONTEXT_FLOW_OUT$1, 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$1(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (ch === 0x3A/* : */) { + ch = state.input.charCodeAt(++state.position); + + if (!is_WS_OR_EOL$1(ch)) { + throwError$2(state, 'a whitespace character is expected after the key-value separator within a block mapping'); + } + + if (atExplicitKey) { + storeMappingPair$1(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$2(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$2(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$1(state, nodeIndent, CONTEXT_BLOCK_OUT$1, true, allowCompact)) { + if (atExplicitKey) { + keyNode = state.result; + } else { + valueNode = state.result; + } + } + + if (!atExplicitKey) { + storeMappingPair$1(state, _result, overridableKeys, keyTag, keyNode, valueNode, _keyLine, _keyLineStart, _keyPos); + keyTag = keyNode = valueNode = null; + } + + skipSeparationSpace$1(state, true, -1); + ch = state.input.charCodeAt(state.position); + } + + if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { + throwError$2(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$1(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$1(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$2(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$2(state, 'unexpected end of the stream within a verbatim tag'); + } + } else { + while (ch !== 0 && !is_WS_OR_EOL$1(ch)) { + + if (ch === 0x21/* ! */) { + if (!isNamed) { + tagHandle = state.input.slice(_position - 1, state.position + 1); + + if (!PATTERN_TAG_HANDLE$1.test(tagHandle)) { + throwError$2(state, 'named tag handle cannot contain such characters'); + } + + isNamed = true; + _position = state.position + 1; + } else { + throwError$2(state, 'tag suffix cannot contain exclamation marks'); + } + } + + ch = state.input.charCodeAt(++state.position); + } + + tagName = state.input.slice(_position, state.position); + + if (PATTERN_FLOW_INDICATORS$1.test(tagName)) { + throwError$2(state, 'tag suffix cannot contain flow indicator characters'); + } + } + + if (tagName && !PATTERN_TAG_URI$1.test(tagName)) { + throwError$2(state, 'tag name cannot contain such characters: ' + tagName); + } + + try { + tagName = decodeURIComponent(tagName); + } catch (err) { + throwError$2(state, 'tag name is malformed: ' + tagName); + } + + if (isVerbatim) { + state.tag = tagName; + + } else if (_hasOwnProperty$1$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$2(state, 'undeclared tag handle "' + tagHandle + '"'); + } + + return true; +} + +function readAnchorProperty$1(state) { + var _position, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x26/* & */) return false; + + if (state.anchor !== null) { + throwError$2(state, 'duplication of an anchor property'); + } + + ch = state.input.charCodeAt(++state.position); + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL$1(ch) && !is_FLOW_INDICATOR$1(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (state.position === _position) { + throwError$2(state, 'name of an anchor node must contain at least one character'); + } + + state.anchor = state.input.slice(_position, state.position); + return true; +} + +function readAlias$1(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$1(ch) && !is_FLOW_INDICATOR$1(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (state.position === _position) { + throwError$2(state, 'name of an alias node must contain at least one character'); + } + + alias = state.input.slice(_position, state.position); + + if (!_hasOwnProperty$1$1.call(state.anchorMap, alias)) { + throwError$2(state, 'unidentified alias "' + alias + '"'); + } + + state.result = state.anchorMap[alias]; + skipSeparationSpace$1(state, true, -1); + return true; +} + +function composeNode$1(state, parentIndent, nodeContext, allowToSeek, allowCompact) { + var allowBlockStyles, + allowBlockScalars, + allowBlockCollections, + indentStatus = 1, // 1: this>parent, 0: this=parent, -1: this<parent + atNewLine = false, + hasContent = false, + typeIndex, + typeQuantity, + typeList, + type, + flowIndent, + blockIndent; + + if (state.listener !== null) { + state.listener('open', state); + } + + state.tag = null; + state.anchor = null; + state.kind = null; + state.result = null; + + allowBlockStyles = allowBlockScalars = allowBlockCollections = + CONTEXT_BLOCK_OUT$1 === nodeContext || + CONTEXT_BLOCK_IN$1 === nodeContext; + + if (allowToSeek) { + if (skipSeparationSpace$1(state, true, -1)) { + atNewLine = true; + + if (state.lineIndent > parentIndent) { + indentStatus = 1; + } else if (state.lineIndent === parentIndent) { + indentStatus = 0; + } else if (state.lineIndent < parentIndent) { + indentStatus = -1; + } + } + } + + if (indentStatus === 1) { + while (readTagProperty$1(state) || readAnchorProperty$1(state)) { + if (skipSeparationSpace$1(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$1 === nodeContext) { + if (CONTEXT_FLOW_IN$1 === nodeContext || CONTEXT_FLOW_OUT$1 === nodeContext) { + flowIndent = parentIndent; + } else { + flowIndent = parentIndent + 1; + } + + blockIndent = state.position - state.lineStart; + + if (indentStatus === 1) { + if (allowBlockCollections && + (readBlockSequence$1(state, blockIndent) || + readBlockMapping$1(state, blockIndent, flowIndent)) || + readFlowCollection$1(state, flowIndent)) { + hasContent = true; + } else { + if ((allowBlockScalars && readBlockScalar$1(state, flowIndent)) || + readSingleQuotedScalar$1(state, flowIndent) || + readDoubleQuotedScalar$1(state, flowIndent)) { + hasContent = true; + + } else if (readAlias$1(state)) { + hasContent = true; + + if (state.tag !== null || state.anchor !== null) { + throwError$2(state, 'alias node should not have any properties'); + } + + } else if (readPlainScalar$1(state, flowIndent, CONTEXT_FLOW_IN$1 === 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$1(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$2(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$1$1.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$2(state, 'unknown tag !<' + state.tag + '>'); + } + + if (state.result !== null && type.kind !== state.kind) { + throwError$2(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$2(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$1(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$1(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$1(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + directiveName = state.input.slice(_position, state.position); + directiveArgs = []; + + if (directiveName.length < 1) { + throwError$2(state, 'directive name must not be less than one character in length'); + } + + while (ch !== 0) { + while (is_WHITE_SPACE$1(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (ch === 0x23/* # */) { + do { ch = state.input.charCodeAt(++state.position); } + while (ch !== 0 && !is_EOL$1(ch)); + break; + } + + if (is_EOL$1(ch)) break; + + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL$1(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + directiveArgs.push(state.input.slice(_position, state.position)); + } + + if (ch !== 0) readLineBreak$1(state); + + if (_hasOwnProperty$1$1.call(directiveHandlers$1, directiveName)) { + directiveHandlers$1[directiveName](state, directiveName, directiveArgs); + } else { + throwWarning$1(state, 'unknown document directive "' + directiveName + '"'); + } + } + + skipSeparationSpace$1(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$1(state, true, -1); + + } else if (hasDirectives) { + throwError$2(state, 'directives end mark is expected'); + } + + composeNode$1(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT$1, false, true); + skipSeparationSpace$1(state, true, -1); + + if (state.checkLineBreaks && + PATTERN_NON_ASCII_LINE_BREAKS$1.test(state.input.slice(documentStart, state.position))) { + throwWarning$1(state, 'non-ASCII line breaks are interpreted as content'); + } + + state.documents.push(state.result); + + if (state.position === state.lineStart && testDocumentSeparator$1(state)) { + + if (state.input.charCodeAt(state.position) === 0x2E/* . */) { + state.position += 3; + skipSeparationSpace$1(state, true, -1); + } + return; + } + + if (state.position < (state.length - 1)) { + throwError$2(state, 'end of the stream or a document separator is expected'); + } else { + return; + } +} + + +function loadDocuments$1(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$1(input, options); + + var nullpos = input.indexOf('\0'); + + if (nullpos !== -1) { + state.position = nullpos; + throwError$2(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$1(state); + } + + return state.documents; +} + + +function loadAll$1(input, iterator, options) { + if (iterator !== null && typeof iterator === 'object' && typeof options === 'undefined') { + options = iterator; + iterator = null; + } + + var documents = loadDocuments$1(input, options); + + if (typeof iterator !== 'function') { + return documents; + } + + for (var index = 0, length = documents.length; index < length; index += 1) { + iterator(documents[index]); + } +} + + +function load$1$1(input, options) { + var documents = loadDocuments$1(input, options); + + if (documents.length === 0) { + /*eslint-disable no-undefined*/ + return undefined; + } else if (documents.length === 1) { + return documents[0]; + } + throw new exception$1('expected a single document in the stream, but found more'); +} + + +var loadAll_1 = loadAll$1; +var load_1 = load$1$1; + +var loader$2 = { + loadAll: loadAll_1, + load: load_1 +}; + +/*eslint-disable no-use-before-define*/ + + + + + +var _toString$3 = Object.prototype.toString; +var _hasOwnProperty$4 = Object.prototype.hasOwnProperty; + +var CHAR_BOM$1 = 0xFEFF; +var CHAR_TAB$1 = 0x09; /* Tab */ +var CHAR_LINE_FEED$1 = 0x0A; /* LF */ +var CHAR_CARRIAGE_RETURN$1 = 0x0D; /* CR */ +var CHAR_SPACE$1 = 0x20; /* Space */ +var CHAR_EXCLAMATION$1 = 0x21; /* ! */ +var CHAR_DOUBLE_QUOTE$1 = 0x22; /* " */ +var CHAR_SHARP$1 = 0x23; /* # */ +var CHAR_PERCENT$1 = 0x25; /* % */ +var CHAR_AMPERSAND$1 = 0x26; /* & */ +var CHAR_SINGLE_QUOTE$1 = 0x27; /* ' */ +var CHAR_ASTERISK$1 = 0x2A; /* * */ +var CHAR_COMMA$1 = 0x2C; /* , */ +var CHAR_MINUS$1 = 0x2D; /* - */ +var CHAR_COLON$1 = 0x3A; /* : */ +var CHAR_EQUALS$1 = 0x3D; /* = */ +var CHAR_GREATER_THAN$1 = 0x3E; /* > */ +var CHAR_QUESTION$1 = 0x3F; /* ? */ +var CHAR_COMMERCIAL_AT$1 = 0x40; /* @ */ +var CHAR_LEFT_SQUARE_BRACKET$1 = 0x5B; /* [ */ +var CHAR_RIGHT_SQUARE_BRACKET$1 = 0x5D; /* ] */ +var CHAR_GRAVE_ACCENT$1 = 0x60; /* ` */ +var CHAR_LEFT_CURLY_BRACKET$1 = 0x7B; /* { */ +var CHAR_VERTICAL_LINE$1 = 0x7C; /* | */ +var CHAR_RIGHT_CURLY_BRACKET$1 = 0x7D; /* } */ + +var ESCAPE_SEQUENCES$1 = {}; + +ESCAPE_SEQUENCES$1[0x00] = '\\0'; +ESCAPE_SEQUENCES$1[0x07] = '\\a'; +ESCAPE_SEQUENCES$1[0x08] = '\\b'; +ESCAPE_SEQUENCES$1[0x09] = '\\t'; +ESCAPE_SEQUENCES$1[0x0A] = '\\n'; +ESCAPE_SEQUENCES$1[0x0B] = '\\v'; +ESCAPE_SEQUENCES$1[0x0C] = '\\f'; +ESCAPE_SEQUENCES$1[0x0D] = '\\r'; +ESCAPE_SEQUENCES$1[0x1B] = '\\e'; +ESCAPE_SEQUENCES$1[0x22] = '\\"'; +ESCAPE_SEQUENCES$1[0x5C] = '\\\\'; +ESCAPE_SEQUENCES$1[0x85] = '\\N'; +ESCAPE_SEQUENCES$1[0xA0] = '\\_'; +ESCAPE_SEQUENCES$1[0x2028] = '\\L'; +ESCAPE_SEQUENCES$1[0x2029] = '\\P'; + +var DEPRECATED_BOOLEANS_SYNTAX$1 = [ + 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON', + 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF' +]; + +var DEPRECATED_BASE60_SYNTAX$1 = /^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/; + +function compileStyleMap$1(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$4.call(type.styleAliases, style)) { + style = type.styleAliases[style]; + } + + result[tag] = style; + } + + return result; +} + +function encodeHex$1(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 exception$1('code point within a string may not be greater than 0xFFFFFFFF'); + } + + return '\\' + handle + common$a.repeat('0', length - string.length) + string; +} + + +var QUOTING_TYPE_SINGLE$1 = 1, + QUOTING_TYPE_DOUBLE$1 = 2; + +function State$2(options) { + this.schema = options['schema'] || _default$2; + this.indent = Math.max(1, (options['indent'] || 2)); + this.noArrayIndent = options['noArrayIndent'] || false; + this.skipInvalid = options['skipInvalid'] || false; + this.flowLevel = (common$a.isNothing(options['flowLevel']) ? -1 : options['flowLevel']); + this.styleMap = compileStyleMap$1(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$1 : QUOTING_TYPE_SINGLE$1; + 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$1(string, spaces) { + var ind = common$a.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$1(state, level) { + return '\n' + common$a.repeat(' ', state.indent * level); +} + +function testImplicitResolving$1(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$2(c) { + return c === CHAR_SPACE$1 || c === CHAR_TAB$1; +} + +// 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$1(c) { + return (0x00020 <= c && c <= 0x00007E) + || ((0x000A1 <= c && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029) + || ((0x0E000 <= c && c <= 0x00FFFD) && c !== CHAR_BOM$1) + || (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$1(c) { + return isPrintable$1(c) + && c !== CHAR_BOM$1 + // - b-char + && c !== CHAR_CARRIAGE_RETURN$1 + && c !== CHAR_LINE_FEED$1; +} + +// [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$1(c, prev, inblock) { + var cIsNsCharOrWhitespace = isNsCharOrWhitespace$1(c); + var cIsNsChar = cIsNsCharOrWhitespace && !isWhitespace$2(c); + return ( + // ns-plain-safe + inblock ? // c = flow-in + cIsNsCharOrWhitespace + : cIsNsCharOrWhitespace + // - c-flow-indicator + && c !== CHAR_COMMA$1 + && c !== CHAR_LEFT_SQUARE_BRACKET$1 + && c !== CHAR_RIGHT_SQUARE_BRACKET$1 + && c !== CHAR_LEFT_CURLY_BRACKET$1 + && c !== CHAR_RIGHT_CURLY_BRACKET$1 + ) + // ns-plain-char + && c !== CHAR_SHARP$1 // false on '#' + && !(prev === CHAR_COLON$1 && !cIsNsChar) // false on ': ' + || (isNsCharOrWhitespace$1(prev) && !isWhitespace$2(prev) && c === CHAR_SHARP$1) // change to true on '[^ ]#' + || (prev === CHAR_COLON$1 && cIsNsChar); // change to true on ':[^ ]' +} + +// Simplified test for values allowed as the first character in plain style. +function isPlainSafeFirst$1(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$1(c) && c !== CHAR_BOM$1 + && !isWhitespace$2(c) // - s-white + // - (c-indicator ::= + // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}” + && c !== CHAR_MINUS$1 + && c !== CHAR_QUESTION$1 + && c !== CHAR_COLON$1 + && c !== CHAR_COMMA$1 + && c !== CHAR_LEFT_SQUARE_BRACKET$1 + && c !== CHAR_RIGHT_SQUARE_BRACKET$1 + && c !== CHAR_LEFT_CURLY_BRACKET$1 + && c !== CHAR_RIGHT_CURLY_BRACKET$1 + // | “#” | “&” | “*” | “!” | “|” | “=” | “>” | “'” | “"” + && c !== CHAR_SHARP$1 + && c !== CHAR_AMPERSAND$1 + && c !== CHAR_ASTERISK$1 + && c !== CHAR_EXCLAMATION$1 + && c !== CHAR_VERTICAL_LINE$1 + && c !== CHAR_EQUALS$1 + && c !== CHAR_GREATER_THAN$1 + && c !== CHAR_SINGLE_QUOTE$1 + && c !== CHAR_DOUBLE_QUOTE$1 + // | “%” | “@” | “`”) + && c !== CHAR_PERCENT$1 + && c !== CHAR_COMMERCIAL_AT$1 + && c !== CHAR_GRAVE_ACCENT$1; +} + +// Simplified test for values allowed as the last character in plain style. +function isPlainSafeLast$1(c) { + // just not whitespace or colon, it will be checked to be plain character later + return !isWhitespace$2(c) && c !== CHAR_COLON$1; +} + +// Same as 'string'.codePointAt(pos), but works in older browsers. +function codePointAt$1(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$1(string) { + var leadingSpaceRe = /^\n* /; + return leadingSpaceRe.test(string); +} + +var STYLE_PLAIN$1 = 1, + STYLE_SINGLE$1 = 2, + STYLE_LITERAL$1 = 3, + STYLE_FOLDED$1 = 4, + STYLE_DOUBLE$1 = 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$1(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$1(codePointAt$1(string, 0)) + && isPlainSafeLast$1(codePointAt$1(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$1(string, i); + if (!isPrintable$1(char)) { + return STYLE_DOUBLE$1; + } + plain = plain && isPlainSafe$1(char, prevChar, inblock); + prevChar = char; + } + } else { + // Case: block styles permitted. + for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) { + char = codePointAt$1(string, i); + if (char === CHAR_LINE_FEED$1) { + 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$1(char)) { + return STYLE_DOUBLE$1; + } + plain = plain && isPlainSafe$1(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$1; + } + return quotingType === QUOTING_TYPE_DOUBLE$1 ? STYLE_DOUBLE$1 : STYLE_SINGLE$1; + } + // Edge case: block indentation indicator can only have one digit. + if (indentPerLevel > 9 && needIndentIndicator$1(string)) { + return STYLE_DOUBLE$1; + } + // At this point we know block styles are valid. + // Prefer literal style unless we want to fold. + if (!forceQuotes) { + return hasFoldableLine ? STYLE_FOLDED$1 : STYLE_LITERAL$1; + } + return quotingType === QUOTING_TYPE_DOUBLE$1 ? STYLE_DOUBLE$1 : STYLE_SINGLE$1; +} + +// 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$1(state, string, level, iskey, inblock) { + state.dump = (function () { + if (string.length === 0) { + return state.quotingType === QUOTING_TYPE_DOUBLE$1 ? '""' : "''"; + } + if (!state.noCompatMode) { + if (DEPRECATED_BOOLEANS_SYNTAX$1.indexOf(string) !== -1 || DEPRECATED_BASE60_SYNTAX$1.test(string)) { + return state.quotingType === QUOTING_TYPE_DOUBLE$1 ? ('"' + 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$1(state, string); + } + + switch (chooseScalarStyle$1(string, singleLineOnly, state.indent, lineWidth, + testAmbiguity, state.quotingType, state.forceQuotes && !iskey, inblock)) { + + case STYLE_PLAIN$1: + return string; + case STYLE_SINGLE$1: + return "'" + string.replace(/'/g, "''") + "'"; + case STYLE_LITERAL$1: + return '|' + blockHeader$1(string, state.indent) + + dropEndingNewline$1(indentString$1(string, indent)); + case STYLE_FOLDED$1: + return '>' + blockHeader$1(string, state.indent) + + dropEndingNewline$1(indentString$1(foldString$1(string, lineWidth), indent)); + case STYLE_DOUBLE$1: + return '"' + escapeString$2(string) + '"'; + default: + throw new exception$1('impossible error: invalid scalar style'); + } + }()); +} + +// Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9. +function blockHeader$1(string, indentPerLevel) { + var indentIndicator = needIndentIndicator$1(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$1(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$1(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$1(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$1(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$1(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$2(string) { + var result = ''; + var char = 0; + var escapeSeq; + + for (var i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) { + char = codePointAt$1(string, i); + escapeSeq = ESCAPE_SEQUENCES$1[char]; + + if (!escapeSeq && isPrintable$1(char)) { + result += string[i]; + if (char >= 0x10000) result += string[i + 1]; + } else { + result += escapeSeq || encodeHex$1(char); + } + } + + return result; +} + +function writeFlowSequence$1(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$1(state, level, value, false, false) || + (typeof value === 'undefined' && + writeNode$1(state, level, null, false, false))) { + + if (_result !== '') _result += ',' + (!state.condenseFlow ? ' ' : ''); + _result += state.dump; + } + } + + state.tag = _tag; + state.dump = '[' + _result + ']'; +} + +function writeBlockSequence$1(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$1(state, level + 1, value, true, true, false, true) || + (typeof value === 'undefined' && + writeNode$1(state, level + 1, null, true, true, false, true))) { + + if (!compact || _result !== '') { + _result += generateNextLine$1(state, level); + } + + if (state.dump && CHAR_LINE_FEED$1 === state.dump.charCodeAt(0)) { + _result += '-'; + } else { + _result += '- '; + } + + _result += state.dump; + } + } + + state.tag = _tag; + state.dump = _result || '[]'; // Empty sequence if no valid values. +} + +function writeFlowMapping$1(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$1(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$1(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$1(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 exception$1('sortKeys must be a boolean or a function'); + } + + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + pairBuffer = ''; + + if (!compact || _result !== '') { + pairBuffer += generateNextLine$1(state, level); + } + + objectKey = objectKeyList[index]; + objectValue = object[objectKey]; + + if (state.replacer) { + objectValue = state.replacer.call(object, objectKey, objectValue); + } + + if (!writeNode$1(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$1 === state.dump.charCodeAt(0)) { + pairBuffer += '?'; + } else { + pairBuffer += '? '; + } + } + + pairBuffer += state.dump; + + if (explicitPair) { + pairBuffer += generateNextLine$1(state, level); + } + + if (!writeNode$1(state, level + 1, objectValue, true, explicitPair)) { + continue; // Skip this pair because of invalid value. + } + + if (state.dump && CHAR_LINE_FEED$1 === 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$1(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$3.call(type.represent) === '[object Function]') { + _result = type.represent(object, style); + } else if (_hasOwnProperty$4.call(type.represent, style)) { + _result = type.represent[style](object, style); + } else { + throw new exception$1('!<' + 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$1(state, level, object, block, compact, iskey, isblockseq) { + state.tag = null; + state.dump = object; + + if (!detectType$1(state, object, false)) { + detectType$1(state, object, true); + } + + var type = _toString$3.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$1(state, level, state.dump, compact); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + state.dump; + } + } else { + writeFlowMapping$1(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$1(state, level - 1, state.dump, compact); + } else { + writeBlockSequence$1(state, level, state.dump, compact); + } + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + state.dump; + } + } else { + writeFlowSequence$1(state, level, state.dump); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; + } + } + } else if (type === '[object String]') { + if (state.tag !== '?') { + writeScalar$1(state, state.dump, level, iskey, inblock); + } + } else if (type === '[object Undefined]') { + return false; + } else { + if (state.skipInvalid) return false; + throw new exception$1('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$1(object, state) { + var objects = [], + duplicatesIndexes = [], + index, + length; + + inspectNode$1(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$1(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$1(object[index], objects, duplicatesIndexes); + } + } else { + objectKeyList = Object.keys(object); + + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + inspectNode$1(object[objectKeyList[index]], objects, duplicatesIndexes); + } + } + } + } +} + +function dump$1$1(input, options) { + options = options || {}; + + var state = new State$2(options); + + if (!state.noRefs) getDuplicateReferences$1(input, state); + + var value = input; + + if (state.replacer) { + value = state.replacer.call({ '': value }, '', value); + } + + if (writeNode$1(state, 0, value, true, true)) return state.dump + '\n'; + + return ''; +} + +var dump_1 = dump$1$1; + +var dumper$2 = { + dump: dump_1 +}; + +function renamed$1(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.'); + }; +} + + +var Type$g = type$f; +var Schema$5 = schema$2; +var FAILSAFE_SCHEMA = failsafe$2; +var JSON_SCHEMA$1 = json$4; +var CORE_SCHEMA = core$8; +var DEFAULT_SCHEMA$2 = _default$2; +var load$2 = loader$2.load; +var loadAll$2 = loader$2.loadAll; +var dump$2 = dumper$2.dump; +var YAMLException$5 = exception$1; + +// Re-export all types in case user wants to create custom schema +var types$3 = { + binary: binary$4, + float: float$1, + map: map$4, + null: _null$1, + pairs: pairs$2, + set: set$3, + timestamp: timestamp$2, + bool: bool$1, + int: int$1, + merge: merge$2, + omap: omap$2, + seq: seq$2, + str: str$1 +}; + +// Removed functions from JS-YAML 3.0.x +var safeLoad = renamed$1('safeLoad', 'load'); +var safeLoadAll = renamed$1('safeLoadAll', 'loadAll'); +var safeDump = renamed$1('safeDump', 'dump'); + +var jsYaml$1 = { + Type: Type$g, + Schema: Schema$5, + FAILSAFE_SCHEMA: FAILSAFE_SCHEMA, + JSON_SCHEMA: JSON_SCHEMA$1, + CORE_SCHEMA: CORE_SCHEMA, + DEFAULT_SCHEMA: DEFAULT_SCHEMA$2, + load: load$2, + loadAll: loadAll$2, + dump: dump$2, + YAMLException: YAMLException$5, + types: types$3, + safeLoad: safeLoad, + safeLoadAll: safeLoadAll, + safeDump: safeDump +}; + +// src/lib/utils.ts +function isBuffer$5(obj) { + return obj != null && obj.constructor != null && typeof obj.constructor.isBuffer === "function" && obj.constructor.isBuffer(obj); +} +function normalizeURL(url) { + if (url.startsWith("https://github.com/") && url.includes("/blob/")) { + return url.replace("github.com", "raw.githubusercontent.com").replace("/blob/", "/"); + } + return url; +} +function getType(obj) { + if (isBuffer$5(obj)) { + return "buffer"; + } else if (typeof obj === "object") { + return "json"; + } else if (typeof obj === "string") { + if (obj.match(/\s*{/)) { + return "string-json"; + } else if (obj.match(/\n/)) { + return "string-yaml"; + } else if (obj.substring(0, 4) === "http") { + return "url"; + } + return "path"; + } + return false; +} +function isOpenAPI$1(schema) { + return !!schema.openapi; +} +function isPostman$1(schema) { + return !!schema.info && !!schema.item; +} +function isSwagger$1(schema) { + return !!schema.swagger; +} +function stringToJSON(string) { + if (typeof string === "object") { + return string; + } else if (string.match(/^\s*{/)) { + return JSON.parse(string); + } + return jsYaml$1.load(string, { schema: JSON_SCHEMA$1 }); +} +function getAPIDefinitionType$1(schema) { + if (isOpenAPI$1(schema)) { + return "openapi"; + } else if (isPostman$1(schema)) { + return "postman"; + } else if (isSwagger$1(schema)) { + return "swagger"; + } + return "unknown"; +} + +const nonJsonTypes = ["function", "symbol", "undefined"]; +const protectedProps$1 = ["constructor", "prototype", "__proto__"]; +const objectPrototype = Object.getPrototypeOf({}); +/** + * Custom JSON serializer for Error objects. + * Returns all built-in error properties, as well as extended properties. + */ +function toJSON$1() { + // HACK: We have to cast the objects to `any` so we can use symbol indexers. + // see https://github.com/Microsoft/TypeScript/issues/1863 + let pojo = {}; + let error = this; + for (let key of getDeepKeys(error)) { + if (typeof key === "string") { + let value = error[key]; + let type = typeof value; + if (!nonJsonTypes.includes(type)) { + pojo[key] = value; + } + } + } + return pojo; +} +/** + * Returns own, inherited, enumerable, non-enumerable, string, and symbol keys of `obj`. + * Does NOT return members of the base Object prototype, or the specified omitted keys. + */ +function getDeepKeys(obj, omit = []) { + let keys = []; + // Crawl the prototype chain, finding all the string and symbol keys + while (obj && obj !== objectPrototype) { + keys = keys.concat(Object.getOwnPropertyNames(obj), Object.getOwnPropertySymbols(obj)); + obj = Object.getPrototypeOf(obj); + } + // De-duplicate the list of keys + let uniqueKeys = new Set(keys); + // Remove any omitted keys + for (let key of omit.concat(protectedProps$1)) { + uniqueKeys.delete(key); + } + return uniqueKeys; +} + +// The `inspect()` method is actually a Symbol, not a string key. +// https://nodejs.org/api/util.html#util_util_inspect_custom +const inspectMethod = require$$0__namespace.inspect.custom || Symbol.for("nodejs.util.inspect.custom"); +/** + * Ono supports Node's `util.format()` formatting for error messages. + * + * @see https://nodejs.org/api/util.html#util_util_format_format_args + */ +const format$6 = require$$0__namespace.format; +/** + * Adds an `inspect()` method to support Node's `util.inspect()` function. + * + * @see https://nodejs.org/api/util.html#util_util_inspect_custom + */ +function addInspectMethod(newError) { + // @ts-expect-error - TypeScript doesn't support symbol indexers + newError[inspectMethod] = inspect; +} +/** + * Returns a representation of the error for Node's `util.inspect()` method. + * + * @see https://nodejs.org/api/util.html#util_custom_inspection_functions_on_objects + */ +function inspect() { + // HACK: We have to cast the objects to `any` so we can use symbol indexers. + // see https://github.com/Microsoft/TypeScript/issues/1863 + let pojo = {}; + let error = this; + for (let key of getDeepKeys(error)) { + let value = error[key]; + pojo[key] = value; + } + // Don't include the `inspect()` method on the output object, + // otherwise it will cause `util.inspect()` to go into an infinite loop + // eslint-disable-next-line @typescript-eslint/no-dynamic-delete + delete pojo[inspectMethod]; + return pojo; +} + +const newline = /\r?\n/; +const onoCall = /\bono[ @]/; +/** + * Is the property lazily computed? + */ +function isLazyStack(stackProp) { + return Boolean(stackProp && + stackProp.configurable && + typeof stackProp.get === "function"); +} +/** + * Is the stack property writable? + */ +function isWritableStack(stackProp) { + return Boolean( + // If there is no stack property, then it's writable, since assigning it will create it + !stackProp || + stackProp.writable || + typeof stackProp.set === "function"); +} +/** + * Appends the original `Error.stack` property to the new Error's stack. + */ +function joinStacks(newError, originalError) { + let newStack = popStack(newError.stack); + let originalStack = originalError ? originalError.stack : undefined; + if (newStack && originalStack) { + return newStack + "\n\n" + originalStack; + } + else { + return newStack || originalStack; + } +} +/** + * Calls `joinStacks` lazily, when the `Error.stack` property is accessed. + */ +function lazyJoinStacks(lazyStack, newError, originalError) { + if (originalError) { + Object.defineProperty(newError, "stack", { + get: () => { + let newStack = lazyStack.get.apply(newError); + return joinStacks({ stack: newStack }, originalError); + }, + enumerable: false, + configurable: true + }); + } + else { + lazyPopStack(newError, lazyStack); + } +} +/** + * Removes Ono from the stack, so that the stack starts at the original error location + */ +function popStack(stack) { + if (stack) { + let lines = stack.split(newline); + // Find the Ono call(s) in the stack, and remove them + let onoStart; + for (let i = 0; i < lines.length; i++) { + let line = lines[i]; + if (onoCall.test(line)) { + if (onoStart === undefined) { + // We found the first Ono call in the stack trace. + // There may be other subsequent Ono calls as well. + onoStart = i; + } + } + else if (onoStart !== undefined) { + // We found the first non-Ono call after one or more Ono calls. + // So remove the Ono call lines from the stack trace + lines.splice(onoStart, i - onoStart); + break; + } + } + if (lines.length > 0) { + return lines.join("\n"); + } + } + // If we get here, then the stack doesn't contain a call to `ono`. + // This may be due to minification or some optimization of the JS engine. + // So just return the stack as-is. + return stack; +} +/** + * Calls `popStack` lazily, when the `Error.stack` property is accessed. + */ +function lazyPopStack(error, lazyStack) { + Object.defineProperty(error, "stack", { + get: () => popStack(lazyStack.get.apply(error)), + enumerable: false, + configurable: true + }); +} + +const protectedProps = ["name", "message", "stack"]; +/** + * Extends the new error with the properties of the original error and the `props` object. + * + * @param newError - The error object to extend + * @param originalError - The original error object, if any + * @param props - Additional properties to add, if any + */ +function extendError(error, originalError, props) { + let onoError = error; + extendStack(onoError, originalError); + // Copy properties from the original error + if (originalError && typeof originalError === "object") { + mergeErrors(onoError, originalError); + } + // The default `toJSON` method doesn't output props like `name`, `message`, `stack`, etc. + // So replace it with one that outputs every property of the error. + onoError.toJSON = toJSON$1; + // On Node.js, add support for the `util.inspect()` method + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + if (addInspectMethod) { + addInspectMethod(onoError); + } + // Finally, copy custom properties that were specified by the user. + // These props OVERWRITE any previous props + if (props && typeof props === "object") { + Object.assign(onoError, props); + } + return onoError; +} +/** + * Extend the error stack to include its cause + */ +function extendStack(newError, originalError) { + let stackProp = Object.getOwnPropertyDescriptor(newError, "stack"); + if (isLazyStack(stackProp)) { + lazyJoinStacks(stackProp, newError, originalError); + } + else if (isWritableStack(stackProp)) { + newError.stack = joinStacks(newError, originalError); + } +} +/** + * Merges properties of the original error with the new error. + * + * @param newError - The error object to extend + * @param originalError - The original error object, if any + */ +function mergeErrors(newError, originalError) { + // Get the original error's keys + // NOTE: We specifically exclude properties that we have already set on the new error. + // This is _especially_ important for the `stack` property, because this property has + // a lazy getter in some environments + let keys = getDeepKeys(originalError, protectedProps); + // HACK: We have to cast the errors to `any` so we can use symbol indexers. + // see https://github.com/Microsoft/TypeScript/issues/1863 + let _newError = newError; + let _originalError = originalError; + for (let key of keys) { + if (_newError[key] === undefined) { + try { + _newError[key] = _originalError[key]; + } + catch (e) { + // This property is read-only, so it can't be copied + } + } + } +} + +/** + * Normalizes Ono options, accounting for defaults and optional options. + */ +function normalizeOptions$1(options) { + options = options || {}; + return { + concatMessages: options.concatMessages === undefined ? true : Boolean(options.concatMessages), + format: options.format === undefined ? format$6 + : (typeof options.format === "function" ? options.format : false), + }; +} +/** + * Normalizes the Ono arguments, accounting for defaults, options, and optional arguments. + */ +function normalizeArgs$3(args, options) { + let originalError; + let props; + let formatArgs; + let message = ""; + // Determine which arguments were actually specified + if (typeof args[0] === "string") { + formatArgs = args; + } + else if (typeof args[1] === "string") { + if (args[0] instanceof Error) { + originalError = args[0]; + } + else { + props = args[0]; + } + formatArgs = args.slice(1); + } + else { + originalError = args[0]; + props = args[1]; + formatArgs = args.slice(2); + } + // If there are any format arguments, then format the error message + if (formatArgs.length > 0) { + if (options.format) { + message = options.format.apply(undefined, formatArgs); + } + else { + message = formatArgs.join(" "); + } + } + if (options.concatMessages && originalError && originalError.message) { + // The inner-error's message will be added to the new message + message += (message ? " \n" : "") + originalError.message; + } + return { originalError, props, message }; +} + +const constructor = Ono$1; +/** + * Creates an `Ono` instance for a specifc error type. + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +function Ono$1(ErrorConstructor, options) { + options = normalizeOptions$1(options); + function ono(...args) { + let { originalError, props, message } = normalizeArgs$3(args, options); + // Create a new error of the specified type + let newError = new ErrorConstructor(message); + // Extend the error with the properties of the original error and the `props` object + return extendError(newError, originalError, props); + } + ono[Symbol.species] = ErrorConstructor; + return ono; +} +/** + * Returns an object containing all properties of the given Error object, + * which can be used with `JSON.stringify()`. + */ +Ono$1.toJSON = function toJSON(error) { + return toJSON$1.call(error); +}; +/** + * Extends the given Error object with enhanced Ono functionality, such as nested stack traces, + * additional properties, and improved support for `JSON.stringify()`. + */ +Ono$1.extend = function extend(error, originalError, props) { + if (props || originalError instanceof Error) { + return extendError(error, originalError, props); + } + else if (originalError) { + return extendError(error, undefined, originalError); + } + else { + return extendError(error); + } +}; + +const singleton = ono$a; +ono$a.error = new constructor(Error); +ono$a.eval = new constructor(EvalError); +ono$a.range = new constructor(RangeError); +ono$a.reference = new constructor(ReferenceError); +ono$a.syntax = new constructor(SyntaxError); +ono$a.type = new constructor(TypeError); +ono$a.uri = new constructor(URIError); +const onoMap = ono$a; +/** + * Creates a new error with the specified message, properties, and/or inner error. + * If an inner error is provided, then the new error will match its type, if possible. + */ +function ono$a(...args) { + let originalError = args[0]; + // Is the first argument an Error-like object? + if (typeof originalError === "object" && typeof originalError.name === "string") { + // Try to find an Ono singleton method that matches this error type + for (let typedOno of Object.values(onoMap)) { + if (typeof typedOno === "function" && typedOno.name === "ono") { + let species = typedOno[Symbol.species]; + if (species && species !== Error && (originalError instanceof species || originalError.name === species.name)) { + // Create an error of the same type + return typedOno.apply(undefined, args); + } + } + } + } + // By default, create a base Error object + return ono$a.error.apply(undefined, args); +} + +/* eslint-env commonjs */ +// CommonJS default export hack +if (typeof module === "object" && typeof module.exports === "object" && typeof module.exports.default === "object") { + module.exports = Object.assign(module.exports.default, module.exports); +} + +var esm = /*#__PURE__*/Object.freeze({ + __proto__: null, + Ono: constructor, + default: singleton, + ono: singleton +}); + +var require$$0$3 = /*@__PURE__*/getAugmentedNamespace(esm); + +var lib$h = {exports: {}}; + +function makeNext () { + if (typeof process === 'object' && typeof process.nextTick === 'function') { + return process.nextTick + } else if (typeof setImmediate === 'function') { + return setImmediate + } else { + return function next (f) { + setTimeout(f, 0); + } + } +} + +var next$3 = makeNext(); + +var next$2 = next$3; + +var maybe$3 = function maybe (cb, promise) { + if (cb) { + promise + .then(function (result) { + next$2(function () { cb(null, result); }); + }, function (err) { + next$2(function () { cb(err); }); + }); + return undefined + } + else { + return promise + } +}; + +var errors$2 = {}; + +var url$c = {exports: {}}; + +(function (module, exports) { + const isWindows = /^win/.test(process.platform); + const forwardSlashPattern = /\//g; + const protocolPattern = /^(\w{2,}):\/\//i; + const url = module.exports; + const jsonPointerSlash = /~1/g; + const jsonPointerTilde = /~0/g; + + /* eslint-disable prettier/prettier */ + // RegExp patterns to URL-encode special characters in local filesystem paths + const urlEncodePatterns = [ + /\?/g, '%3F', + /#/g, '%23', + ]; + + // RegExp patterns to URL-decode special characters for local filesystem paths + const urlDecodePatterns = [ + /%23/g, '#', + /%24/g, '$', + /%26/g, '&', + /%2C/g, ',', + /%40/g, '@', + ]; + /* eslint-enable prettier/prettier */ + + exports.parse = require$$0$e.parse; + exports.resolve = require$$0$e.resolve; + + /** + * Returns the current working directory (in Node) or the current page URL (in browsers). + * + * @returns {string} + */ + exports.cwd = function cwd() { + if (process.browser) { + // eslint-disable-next-line no-restricted-globals + return location.href; + } + + const path = process.cwd(); + + const lastChar = path.slice(-1); + if (lastChar === '/' || lastChar === '\\') { + return path; + } + + return `${path}/`; + }; + + /** + * Returns the protocol of the given URL, or `undefined` if it has no protocol. + * + * @param {string} path + * @returns {?string} + */ + exports.getProtocol = function getProtocol(path) { + const match = protocolPattern.exec(path); + if (match) { + return match[1].toLowerCase(); + } + }; + + /** + * Returns the lowercased file extension of the given URL, + * or an empty string if it has no extension. + * + * @param {string} path + * @returns {string} + */ + exports.getExtension = function getExtension(path) { + const lastDot = path.lastIndexOf('.'); + if (lastDot >= 0) { + return url.stripQuery(path.substr(lastDot).toLowerCase()); + } + return ''; + }; + + /** + * Removes the query, if any, from the given path. + * + * @param {string} path + * @returns {string} + */ + exports.stripQuery = function stripQuery(path) { + const queryIndex = path.indexOf('?'); + if (queryIndex >= 0) { + // eslint-disable-next-line no-param-reassign + path = path.substr(0, queryIndex); + } + return path; + }; + + /** + * Returns the hash (URL fragment), of the given path. + * If there is no hash, then the root hash ("#") is returned. + * + * @param {string} path + * @returns {string} + */ + exports.getHash = function getHash(path) { + const hashIndex = path.indexOf('#'); + if (hashIndex >= 0) { + return path.substr(hashIndex); + } + return '#'; + }; + + /** + * Removes the hash (URL fragment), if any, from the given path. + * + * @param {string} path + * @returns {string} + */ + exports.stripHash = function stripHash(path) { + const hashIndex = path.indexOf('#'); + if (hashIndex >= 0) { + return path.substr(0, hashIndex); + } + return path; + }; + + /** + * Determines whether the given path is an HTTP(S) URL. + * + * @param {string} path + * @returns {boolean} + */ + exports.isHttp = function isHttp(path) { + const protocol = url.getProtocol(path); + if (protocol === 'http' || protocol === 'https') { + return true; + } else if (protocol === undefined) { + // There is no protocol. If we're running in a browser, then assume it's HTTP. + return process.browser; + } + + // It's some other protocol, such as "ftp://", "mongodb://", etc. + return false; + }; + + /** + * Determines whether the given path is a filesystem path. + * This includes "file://" URLs. + * + * @param {string} path + * @returns {boolean} + */ + exports.isFileSystemPath = function isFileSystemPath(path) { + if (process.browser) { + // We're running in a browser, so assume that all paths are URLs. + // This way, even relative paths will be treated as URLs rather than as filesystem paths + return false; + } + + const protocol = url.getProtocol(path); + return protocol === undefined || protocol === 'file'; + }; + + /** + * Converts a filesystem path to a properly-encoded URL. + * + * This is intended to handle situations where JSON Schema $Ref Parser is called + * with a filesystem path that contains characters which are not allowed in URLs. + * + * @example + * The following filesystem paths would be converted to the following URLs: + * + * <"!@#$%^&*+=?'>.json ==> %3C%22!@%23$%25%5E&*+=%3F\'%3E.json + * C:\\My Documents\\File (1).json ==> C:/My%20Documents/File%20(1).json + * file://Project #42/file.json ==> file://Project%20%2342/file.json + * + * @param {string} path + * @returns {string} + */ + /* eslint-disable no-param-reassign */ + exports.fromFileSystemPath = function fromFileSystemPath(path) { + // Step 1: On Windows, replace backslashes with forward slashes, + // rather than encoding them as "%5C" + if (isWindows) { + path = path.replace(/\\/g, '/'); + } + + // Step 2: `encodeURI` will take care of MOST characters + path = encodeURI(path); + + // Step 3: Manually encode characters that are not encoded by `encodeURI`. + // This includes characters such as "#" and "?", which have special meaning in URLs, + // but are just normal characters in a filesystem path. + for (let i = 0; i < urlEncodePatterns.length; i += 2) { + path = path.replace(urlEncodePatterns[i], urlEncodePatterns[i + 1]); + } + + return path; + }; + /* eslint-enable no-param-reassign */ + + /** + * Converts a URL to a local filesystem path. + * + * @param {string} path + * @param {boolean} [keepFileProtocol] - If true, then "file://" will NOT be stripped + * @returns {string} + */ + /* eslint-disable no-param-reassign */ + exports.toFileSystemPath = function toFileSystemPath(path, keepFileProtocol) { + // Step 1: `decodeURI` will decode characters such as Cyrillic characters, spaces, etc. + path = decodeURI(path); + + // Step 2: Manually decode characters that are not decoded by `decodeURI`. + // This includes characters such as "#" and "?", which have special meaning in URLs, + // but are just normal characters in a filesystem path. + for (let i = 0; i < urlDecodePatterns.length; i += 2) { + path = path.replace(urlDecodePatterns[i], urlDecodePatterns[i + 1]); + } + + // Step 3: If it's a "file://" URL, then format it consistently + // or convert it to a local filesystem path + let isFileUrl = path.substr(0, 7).toLowerCase() === 'file://'; + if (isFileUrl) { + // Strip-off the protocol, and the initial "/", if there is one + path = path[7] === '/' ? path.substr(8) : path.substr(7); + + // insert a colon (":") after the drive letter on Windows + if (isWindows && path[1] === '/') { + path = `${path[0]}:${path.substr(1)}`; + } + + if (keepFileProtocol) { + // Return the consistently-formatted "file://" URL + path = `file:///${path}`; + } else { + // Convert the "file://" URL to a local filesystem path. + // On Windows, it will start with something like "C:/". + // On Posix, it will start with "/" + isFileUrl = false; + path = isWindows ? path : `/${path}`; + } + } + + // Step 4: Normalize Windows paths (unless it's a "file://" URL) + if (isWindows && !isFileUrl) { + // Replace forward slashes with backslashes + path = path.replace(forwardSlashPattern, '\\'); + + // Capitalize the drive letter + if (path.substr(1, 2) === ':\\') { + path = path[0].toUpperCase() + path.substr(1); + } + } + + return path; + }; + /* eslint-enable no-param-reassign */ + + /** + * Converts a $ref pointer to a valid JSON Path. + * + * @param {string} pointer + * @returns {Array<number | string>} + */ + exports.safePointerToPath = function safePointerToPath(pointer) { + if (pointer.length <= 1 || pointer[0] !== '#' || pointer[1] !== '/') { + return []; + } + + return pointer + .slice(2) + .split('/') + .map(value => { + return decodeURIComponent(value).replace(jsonPointerSlash, '/').replace(jsonPointerTilde, '~'); + }); + }; +} (url$c, url$c.exports)); + +var urlExports = url$c.exports; + +/* eslint-disable max-classes-per-file */ + +const { Ono } = require$$0$3; + +const { stripHash, toFileSystemPath } = urlExports; + +function setErrorName(err) { + Object.defineProperty(err.prototype, 'name', { + value: err.name, + enumerable: true, + }); +} + +const JSONParserError$1 = class JSONParserError extends Error { + constructor(message, source) { + super(); + + this.code = 'EUNKNOWN'; + this.message = message; + this.source = source; + this.path = null; + + Ono.extend(this); + } + + get footprint() { + return `${this.path}+${this.source}+${this.code}+${this.message}`; + } +}; + +errors$2.JSONParserError = JSONParserError$1; +setErrorName(JSONParserError$1); + +const JSONParserErrorGroup$1 = class JSONParserErrorGroup extends Error { + constructor(parser) { + super(); + + this.files = parser; + this.message = `${this.errors.length} error${ + this.errors.length > 1 ? 's' : '' + } occurred while reading '${toFileSystemPath(parser.$refs._root$Ref.path)}'`; + + Ono.extend(this); + } + + static getParserErrors(parser) { + const errors = []; + + for (const $ref of Object.values(parser.$refs._$refs)) { + if ($ref.errors) { + errors.push(...$ref.errors); + } + } + + return errors; + } + + get errors() { + return JSONParserErrorGroup.getParserErrors(this.files); + } +}; + +errors$2.JSONParserErrorGroup = JSONParserErrorGroup$1; +setErrorName(JSONParserErrorGroup$1); + +const ParserError$5 = class ParserError extends JSONParserError$1 { + constructor(message, source) { + super(`Error parsing ${source}: ${message}`, source); + + this.code = 'EPARSER'; + } +}; + +errors$2.ParserError = ParserError$5; +setErrorName(ParserError$5); + +const UnmatchedParserError$2 = class UnmatchedParserError extends JSONParserError$1 { + constructor(source) { + super(`Could not find parser for "${source}"`, source); + + this.code = 'EUNMATCHEDPARSER'; + } +}; + +errors$2.UnmatchedParserError = UnmatchedParserError$2; +setErrorName(UnmatchedParserError$2); + +const ResolverError$4 = class ResolverError extends JSONParserError$1 { + constructor(ex, source) { + super(ex.message || `Error reading file "${source}"`, source); + + this.code = 'ERESOLVER'; + + if ('code' in ex) { + this.ioErrorCode = String(ex.code); + } + } +}; +errors$2.ResolverError = ResolverError$4; +setErrorName(ResolverError$4); + +const UnmatchedResolverError$2 = class UnmatchedResolverError extends JSONParserError$1 { + constructor(source) { + super(`Could not find resolver for "${source}"`, source); + + this.code = 'EUNMATCHEDRESOLVER'; + } +}; + +errors$2.UnmatchedResolverError = UnmatchedResolverError$2; +setErrorName(UnmatchedResolverError$2); + +const MissingPointerError$1 = class MissingPointerError extends JSONParserError$1 { + constructor(token, path) { + super(`Token "${token}" does not exist.`, stripHash(path)); + + this.code = 'EMISSINGPOINTER'; + } +}; + +errors$2.MissingPointerError = MissingPointerError$1; +setErrorName(MissingPointerError$1); + +const InvalidPointerError$1 = class InvalidPointerError extends JSONParserError$1 { + constructor(pointer, path) { + super(`Invalid $ref pointer "${pointer}". Pointers must begin with "#/"`, stripHash(path)); + + this.code = 'EINVALIDPOINTER'; + } +}; + +errors$2.InvalidPointerError = InvalidPointerError$1; +setErrorName(InvalidPointerError$1); + +errors$2.isHandledError = function (err) { + return err instanceof JSONParserError$1 || err instanceof JSONParserErrorGroup$1; +}; + +errors$2.normalizeError = function (err) { + if (err.path === null) { + // eslint-disable-next-line no-param-reassign + err.path = []; + } + + return err; +}; + +/* eslint-disable no-param-reassign */ + +var pointer; +var hasRequiredPointer; + +function requirePointer () { + if (hasRequiredPointer) return pointer; + hasRequiredPointer = 1; + const $Ref = requireRef(); + const { JSONParserError, InvalidPointerError, MissingPointerError, isHandledError } = errors$2; + const url = urlExports; + + const slashes = /\//g; + const tildes = /~/g; + const escapedSlash = /~1/g; + const escapedTilde = /~0/g; + + pointer = Pointer; + + /** + * This class represents a single JSON pointer and its resolved value. + * + * @param {$Ref} $ref + * @param {string} path + * @param {string} [friendlyPath] - The original user-specified path (used for error messages) + * @constructor + */ + function Pointer($ref, path, friendlyPath) { + /** + * The {@link $Ref} object that contains this {@link Pointer} object. + * @type {$Ref} + */ + this.$ref = $ref; + + /** + * The file path or URL, containing the JSON pointer in the hash. + * This path is relative to the path of the main JSON schema file. + * @type {string} + */ + this.path = path; + + /** + * The original path or URL, used for error messages. + * @type {string} + */ + this.originalPath = friendlyPath || path; + + /** + * The value of the JSON pointer. + * Can be any JSON type, not just objects. Unknown file types are represented as Buffers (byte arrays). + * @type {?*} + */ + this.value = undefined; + + /** + * Indicates whether the pointer references itself. + * @type {boolean} + */ + this.circular = false; + + /** + * The number of indirect references that were traversed to resolve the value. + * Resolving a single pointer may require resolving multiple $Refs. + * @type {number} + */ + this.indirections = 0; + } + + /** + * Resolves the value of a nested property within the given object. + * + * @param {*} obj - The object that will be crawled + * @param {$RefParserOptions} options + * @param {string} pathFromRoot - the path of place that initiated resolving + * + * @returns {Pointer} + * Returns a JSON pointer whose {@link Pointer#value} is the resolved value. + * If resolving this value required resolving other JSON references, then + * the {@link Pointer#$ref} and {@link Pointer#path} will reflect the resolution path + * of the resolved value. + */ + Pointer.prototype.resolve = function (obj, options, pathFromRoot) { + const tokens = Pointer.parse(this.path, this.originalPath); + + // Crawl the object, one token at a time + this.value = unwrapOrThrow(obj); + + for (let i = 0; i < tokens.length; i++) { + if (resolveIf$Ref(this, options)) { + // The $ref path has changed, so append the remaining tokens to the path + this.path = Pointer.join(this.path, tokens.slice(i)); + } + + if (typeof this.value === 'object' && this.value !== null && '$ref' in this.value) { + return this; + } + + const token = tokens[i]; + if (this.value[token] === undefined || this.value[token] === null) { + this.value = null; + throw new MissingPointerError(token, this.originalPath); + } else { + this.value = this.value[token]; + } + } + + // Resolve the final value + if (!this.value || (this.value.$ref && url.resolve(this.path, this.value.$ref) !== pathFromRoot)) { + resolveIf$Ref(this, options); + } + + return this; + }; + + /** + * Sets the value of a nested property within the given object. + * + * @param {*} obj - The object that will be crawled + * @param {*} value - the value to assign + * @param {$RefParserOptions} options + * + * @returns {*} + * Returns the modified object, or an entirely new object if the entire object is overwritten. + */ + Pointer.prototype.set = function (obj, value, options) { + const tokens = Pointer.parse(this.path); + let token; + + if (tokens.length === 0) { + // There are no tokens, replace the entire object with the new value + this.value = value; + return value; + } + + // Crawl the object, one token at a time + this.value = unwrapOrThrow(obj); + + for (let i = 0; i < tokens.length - 1; i++) { + resolveIf$Ref(this, options); + + token = tokens[i]; + if (this.value && this.value[token] !== undefined) { + // The token exists + this.value = this.value[token]; + } else { + // The token doesn't exist, so create it + this.value = setValue(this, token, {}); + } + } + + // Set the value of the final token + resolveIf$Ref(this, options); + token = tokens[tokens.length - 1]; + setValue(this, token, value); + + // Return the updated object + return obj; + }; + + /** + * Parses a JSON pointer (or a path containing a JSON pointer in the hash) + * and returns an array of the pointer's tokens. + * (e.g. "schema.json#/definitions/person/name" => ["definitions", "person", "name"]) + * + * The pointer is parsed according to RFC 6901 + * {@link https://tools.ietf.org/html/rfc6901#section-3} + * + * @param {string} path + * @param {string} [originalPath] + * @returns {string[]} + */ + Pointer.parse = function (path, originalPath) { + // Get the JSON pointer from the path's hash + let pointer = url.getHash(path).substr(1); + + // If there's no pointer, then there are no tokens, + // so return an empty array + if (!pointer) { + return []; + } + + // Split into an array + pointer = pointer.split('/'); + + // Decode each part, according to RFC 6901 + for (let i = 0; i < pointer.length; i++) { + pointer[i] = decodeURIComponent(pointer[i].replace(escapedSlash, '/').replace(escapedTilde, '~')); + } + + if (pointer[0] !== '') { + throw new InvalidPointerError(pointer, originalPath === undefined ? path : originalPath); + } + + return pointer.slice(1); + }; + + /** + * Creates a JSON pointer path, by joining one or more tokens to a base path. + * + * @param {string} base - The base path (e.g. "schema.json#/definitions/person") + * @param {string|string[]} tokens - The token(s) to append (e.g. ["name", "first"]) + * @returns {string} + */ + Pointer.join = function (base, tokens) { + // Ensure that the base path contains a hash + if (base.indexOf('#') === -1) { + base += '#'; + } + + // Append each token to the base path + tokens = Array.isArray(tokens) ? tokens : [tokens]; + for (let i = 0; i < tokens.length; i++) { + const token = tokens[i]; + // Encode the token, according to RFC 6901 + base += `/${encodeURIComponent(token.replace(tildes, '~0').replace(slashes, '~1'))}`; + } + + return base; + }; + + /** + * If the given pointer's {@link Pointer#value} is a JSON reference, + * then the reference is resolved and {@link Pointer#value} is replaced with the resolved value. + * In addition, {@link Pointer#path} and {@link Pointer#$ref} are updated to reflect the + * resolution path of the new value. + * + * @param {Pointer} pointer + * @param {$RefParserOptions} options + * @returns {boolean} - Returns `true` if the resolution path changed + */ + function resolveIf$Ref(pointer, options) { + // Is the value a JSON reference? (and allowed?) + + if ($Ref.isAllowed$Ref(pointer.value, options)) { + const $refPath = url.resolve(pointer.path, pointer.value.$ref); + + if ($refPath === pointer.path) { + // The value is a reference to itself, so there's nothing to do. + pointer.circular = true; + } else { + const resolved = pointer.$ref.$refs._resolve($refPath, pointer.path, options); + if (resolved === null) { + return false; + } + + pointer.indirections += resolved.indirections + 1; + + if ($Ref.isExtended$Ref(pointer.value)) { + // This JSON reference "extends" the resolved value, rather than simply pointing to it. + // So the resolved path does NOT change. Just the value does. + pointer.value = $Ref.dereference(pointer.value, resolved.value); + return false; + } + + // Resolve the reference + pointer.$ref = resolved.$ref; + pointer.path = resolved.path; + pointer.value = resolved.value; + return true; + } + } + } + + /** + * Sets the specified token value of the {@link Pointer#value}. + * + * The token is evaluated according to RFC 6901. + * {@link https://tools.ietf.org/html/rfc6901#section-4} + * + * @param {Pointer} pointer - The JSON Pointer whose value will be modified + * @param {string} token - A JSON Pointer token that indicates how to modify `obj` + * @param {*} value - The value to assign + * @returns {*} - Returns the assigned value + */ + function setValue(pointer, token, value) { + if (pointer.value && typeof pointer.value === 'object') { + if (token === '-' && Array.isArray(pointer.value)) { + pointer.value.push(value); + } else { + pointer.value[token] = value; + } + } else { + throw new JSONParserError( + `Error assigning $ref pointer "${pointer.path}". \nCannot set "${token}" of a non-object.` + ); + } + return value; + } + + function unwrapOrThrow(value) { + if (isHandledError(value)) { + throw value; + } + + return value; + } + return pointer; +} + +var ref$1; +var hasRequiredRef; + +function requireRef () { + if (hasRequiredRef) return ref$1; + hasRequiredRef = 1; + // This export needs to be loaded before everything else or else this export doesn't work. 🤷‍♂️ + ref$1 = $Ref; + + const Pointer = requirePointer(); + const { InvalidPointerError, isHandledError, normalizeError } = errors$2; + const { safePointerToPath, stripHash, getHash } = urlExports; + + /** + * This class represents a single JSON reference and its resolved value. + * + * @class + */ + function $Ref() { + /** + * The file path or URL of the referenced file. + * This path is relative to the path of the main JSON schema file. + * + * This path does NOT contain document fragments (JSON pointers). It always references an ENTIRE file. + * Use methods such as {@link $Ref#get}, {@link $Ref#resolve}, and {@link $Ref#exists} to get + * specific JSON pointers within the file. + * + * @type {string} + */ + this.path = undefined; + + /** + * The resolved value of the JSON reference. + * Can be any JSON type, not just objects. Unknown file types are represented as Buffers (byte arrays). + * + * @type {?*} + */ + this.value = undefined; + + /** + * The {@link $Refs} object that contains this {@link $Ref} object. + * + * @type {$Refs} + */ + this.$refs = undefined; + + /** + * Indicates the type of {@link $Ref#path} (e.g. "file", "http", etc.) + * + * @type {?string} + */ + this.pathType = undefined; + + /** + * List of all errors. Undefined if no errors. + * + * @type {Array<JSONParserError | ResolverError | ParserError | MissingPointerError>} + */ + this.errors = undefined; + } + + /** + * Pushes an error to errors array. + * + * @param {Array<JSONParserError | JSONParserErrorGroup>} err - The error to be pushed + * @returns {void} + */ + $Ref.prototype.addError = function (err) { + if (this.errors === undefined) { + this.errors = []; + } + + const existingErrors = this.errors.map(({ footprint }) => footprint); + + // the path has been almost certainly set at this point, + // but just in case something went wrong, normalizeError injects path if necessary + // moreover, certain errors might point at the same spot, so filter them out to reduce noise + if (Array.isArray(err.errors)) { + this.errors.push(...err.errors.map(normalizeError).filter(({ footprint }) => !existingErrors.includes(footprint))); + } else if (!existingErrors.includes(err.footprint)) { + this.errors.push(normalizeError(err)); + } + }; + + /** + * Determines whether the given JSON reference exists within this {@link $Ref#value}. + * + * @param {string} path - The full path being resolved, optionally with a JSON pointer in the hash + * @param {$RefParserOptions} options + * @returns {boolean} + */ + $Ref.prototype.exists = function (path, options) { + try { + this.resolve(path, options); + return true; + } catch (e) { + return false; + } + }; + + /** + * Resolves the given JSON reference within this {@link $Ref#value} and returns the resolved value. + * + * @param {string} path - The full path being resolved, optionally with a JSON pointer in the hash + * @param {$RefParserOptions} options + * @returns {*} - Returns the resolved value + */ + $Ref.prototype.get = function (path, options) { + return this.resolve(path, options).value; + }; + + /** + * Resolves the given JSON reference within this {@link $Ref#value}. + * + * @param {string} path - The full path being resolved, optionally with a JSON pointer in the hash + * @param {$RefParserOptions} options + * @param {string} friendlyPath - The original user-specified path (used for error messages) + * @param {string} pathFromRoot - The path of `obj` from the schema root + * @returns {Pointer | null} + */ + $Ref.prototype.resolve = function (path, options, friendlyPath, pathFromRoot) { + const pointer = new Pointer(this, path, friendlyPath); + try { + return pointer.resolve(this.value, options, pathFromRoot); + } catch (err) { + if (!options || !options.continueOnError || !isHandledError(err)) { + throw err; + } + + if (err.path === null) { + err.path = safePointerToPath(getHash(pathFromRoot)); + } + + if (err instanceof InvalidPointerError) { + // this is a special case - InvalidPointerError is thrown when dereferencing external file, + // but the issue is caused by the source file that referenced the file that undergoes dereferencing + err.source = stripHash(pathFromRoot); + } + + this.addError(err); + return null; + } + }; + + /** + * Sets the value of a nested property within this {@link $Ref#value}. + * If the property, or any of its parents don't exist, they will be created. + * + * @param {string} path - The full path of the property to set, optionally with a JSON pointer in the hash + * @param {*} value - The value to assign + */ + $Ref.prototype.set = function (path, value) { + const pointer = new Pointer(this, path); + this.value = pointer.set(this.value, value); + }; + + /** + * Determines whether the given value is a JSON reference. + * + * @param {*} value - The value to inspect + * @returns {boolean} + */ + $Ref.is$Ref = function (value) { + return value && typeof value === 'object' && typeof value.$ref === 'string' && value.$ref.length > 0; + }; + + /** + * Determines whether the given value is an external JSON reference. + * + * @param {*} value - The value to inspect + * @returns {boolean} + */ + $Ref.isExternal$Ref = function (value) { + return $Ref.is$Ref(value) && value.$ref[0] !== '#'; + }; + + /** + * Determines whether the given value is a JSON reference, and whether it is allowed by the options. + * For example, if it references an external file, then options.resolve.external must be true. + * + * @param {*} value - The value to inspect + * @param {$RefParserOptions} options + * @returns {boolean} + */ + $Ref.isAllowed$Ref = function (value, options) { + if ($Ref.is$Ref(value)) { + if (value.$ref.substr(0, 2) === '#/' || value.$ref === '#') { + // It's a JSON Pointer reference, which is always allowed + return true; + } else if (value.$ref[0] !== '#' && (!options || options.resolve.external)) { + // It's an external reference, which is allowed by the options + return true; + } + } + }; + + /** + * Determines whether the given value is a JSON reference that "extends" its resolved value. + * That is, it has extra properties (in addition to "$ref"), so rather than simply pointing to + * an existing value, this $ref actually creates a NEW value that is a shallow copy of the resolved + * value, plus the extra properties. + * + * @example: + * { + * person: { + * properties: { + * firstName: { type: string } + * lastName: { type: string } + * } + * } + * employee: { + * properties: { + * $ref: #/person/properties + * salary: { type: number } + * } + * } + * } + * + * In this example, "employee" is an extended $ref, since it extends "person" with an additional + * property (salary). The result is a NEW value that looks like this: + * + * { + * properties: { + * firstName: { type: string } + * lastName: { type: string } + * salary: { type: number } + * } + * } + * + * @param {*} value - The value to inspect + * @returns {boolean} + */ + $Ref.isExtended$Ref = function (value) { + return $Ref.is$Ref(value) && Object.keys(value).length > 1; + }; + + /** + * Returns the resolved value of a JSON Reference. + * If necessary, the resolved value is merged with the JSON Reference to create a new object + * + * @example: + * { + * person: { + * properties: { + * firstName: { type: string } + * lastName: { type: string } + * } + * } + * employee: { + * properties: { + * $ref: #/person/properties + * salary: { type: number } + * } + * } + * } + * + * When "person" and "employee" are merged, you end up with the following object: + * + * { + * properties: { + * firstName: { type: string } + * lastName: { type: string } + * salary: { type: number } + * } + * } + * + * @param {object} $ref - The JSON reference object (the one with the "$ref" property) + * @param {*} resolvedValue - The resolved value, which can be any type + * @returns {*} - Returns the dereferenced value + */ + $Ref.dereference = function ($ref, resolvedValue) { + if (resolvedValue && typeof resolvedValue === 'object' && $Ref.isExtended$Ref($ref)) { + const merged = {}; + for (const key of Object.keys($ref)) { + if (key !== '$ref') { + merged[key] = $ref[key]; + } + } + + for (const key of Object.keys(resolvedValue)) { + if (!(key in merged)) { + merged[key] = resolvedValue[key]; + } + } + + return merged; + } + + // Completely replace the original reference with the resolved value + return resolvedValue; + }; + return ref$1; +} + +/* eslint-disable import/order */ + +const $Ref$3 = requireRef(); +const Pointer$2 = requirePointer(); +const url$b = urlExports; + +/** + * Bundles all external JSON references into the main JSON schema, thus resulting in a schema that + * only has *internal* references, not any *external* references. + * This method mutates the JSON schema object, adding new references and re-mapping existing ones. + * + * @param {$RefParser} parser + * @param {$RefParserOptions} options + */ +var bundle = function bundle(parser, options) { + // console.log('Bundling $ref pointers in %s', parser.$refs._root$Ref.path); + + // Build an inventory of all $ref pointers in the JSON Schema + const inventory = []; + crawl$2(parser, 'schema', `${parser.$refs._root$Ref.path}#`, '#', 0, inventory, parser.$refs, options); + + // Remap all $ref pointers + remap(inventory); +}; + +/** + * Recursively crawls the given value, and inventories all JSON references. + * + * @param {object} parent - The object containing the value to crawl. If the value is not an object or array, it will be ignored. + * @param {string} key - The property key of `parent` to be crawled + * @param {string} path - The full path of the property being crawled, possibly with a JSON Pointer in the hash + * @param {string} pathFromRoot - The path of the property being crawled, from the schema root + * @param {object[]} inventory - An array of already-inventoried $ref pointers + * @param {$Refs} $refs + * @param {$RefParserOptions} options + */ +function crawl$2(parent, key, path, pathFromRoot, indirections, inventory, $refs, options) { + const obj = key === null ? parent : parent[key]; + + if (obj && typeof obj === 'object' && !ArrayBuffer.isView(obj)) { + if ($Ref$3.isAllowed$Ref(obj)) { + inventory$Ref(parent, key, path, pathFromRoot, indirections, inventory, $refs, options); + } else { + // Crawl the object in a specific order that's optimized for bundling. + // This is important because it determines how `pathFromRoot` gets built, + // which later determines which keys get dereferenced and which ones get remapped + const keys = Object.keys(obj).sort((a, b) => { + // Most people will expect references to be bundled into the the "definitions" property, + // so we always crawl that property first, if it exists. + if (a === 'definitions') { + return -1; + } else if (b === 'definitions') { + return 1; + } + + // Otherwise, crawl the keys based on their length. + // This produces the shortest possible bundled references + return a.length - b.length; + }); + + // eslint-disable-next-line no-shadow + for (const key of keys) { + const keyPath = Pointer$2.join(path, key); + const keyPathFromRoot = Pointer$2.join(pathFromRoot, key); + const value = obj[key]; + + if ($Ref$3.isAllowed$Ref(value)) { + inventory$Ref(obj, key, path, keyPathFromRoot, indirections, inventory, $refs, options); + } else { + crawl$2(obj, key, keyPath, keyPathFromRoot, indirections, inventory, $refs, options); + } + } + } + } +} + +/** + * Inventories the given JSON Reference (i.e. records detailed information about it so we can + * optimize all $refs in the schema), and then crawls the resolved value. + * + * @param {object} $refParent - The object that contains a JSON Reference as one of its keys + * @param {string} $refKey - The key in `$refParent` that is a JSON Reference + * @param {string} path - The full path of the JSON Reference at `$refKey`, possibly with a JSON Pointer in the hash + * @param {string} pathFromRoot - The path of the JSON Reference at `$refKey`, from the schema root + * @param {object[]} inventory - An array of already-inventoried $ref pointers + * @param {$Refs} $refs + * @param {$RefParserOptions} options + */ +function inventory$Ref($refParent, $refKey, path, pathFromRoot, indirections, inventory, $refs, options) { + const $ref = $refKey === null ? $refParent : $refParent[$refKey]; + const $refPath = url$b.resolve(path, $ref.$ref); + const pointer = $refs._resolve($refPath, pathFromRoot, options); + if (pointer === null) { + return; + } + + const depth = Pointer$2.parse(pathFromRoot).length; + const file = url$b.stripHash(pointer.path); + const hash = url$b.getHash(pointer.path); + const external = file !== $refs._root$Ref.path; + const extended = $Ref$3.isExtended$Ref($ref); + indirections += pointer.indirections; // eslint-disable-line no-param-reassign + + const existingEntry = findInInventory(inventory, $refParent, $refKey); + if (existingEntry) { + // This $Ref has already been inventoried, so we don't need to process it again + if (depth < existingEntry.depth || indirections < existingEntry.indirections) { + removeFromInventory(inventory, existingEntry); + } else { + return; + } + } + + inventory.push({ + $ref, // The JSON Reference (e.g. {$ref: string}) + parent: $refParent, // The object that contains this $ref pointer + key: $refKey, // The key in `parent` that is the $ref pointer + pathFromRoot, // The path to the $ref pointer, from the JSON Schema root + depth, // How far from the JSON Schema root is this $ref pointer? + file, // The file that the $ref pointer resolves to + hash, // The hash within `file` that the $ref pointer resolves to + value: pointer.value, // The resolved value of the $ref pointer + circular: pointer.circular, // Is this $ref pointer DIRECTLY circular? (i.e. it references itself) + extended, // Does this $ref extend its resolved value? (i.e. it has extra properties, in addition to "$ref") + external, // Does this $ref pointer point to a file other than the main JSON Schema file? + indirections, // The number of indirect references that were traversed to resolve the value + }); + + // Recursively crawl the resolved value + if (!existingEntry) { + crawl$2(pointer.value, null, pointer.path, pathFromRoot, indirections + 1, inventory, $refs, options); + } +} + +/** + * Re-maps every $ref pointer, so that they're all relative to the root of the JSON Schema. + * Each referenced value is dereferenced EXACTLY ONCE. All subsequent references to the same + * value are re-mapped to point to the first reference. + * + * @example: + * { + * first: { $ref: somefile.json#/some/part }, + * second: { $ref: somefile.json#/another/part }, + * third: { $ref: somefile.json }, + * fourth: { $ref: somefile.json#/some/part/sub/part } + * } + * + * In this example, there are four references to the same file, but since the third reference points + * to the ENTIRE file, that's the only one we need to dereference. The other three can just be + * remapped to point inside the third one. + * + * On the other hand, if the third reference DIDN'T exist, then the first and second would both need + * to be dereferenced, since they point to different parts of the file. The fourth reference does NOT + * need to be dereferenced, because it can be remapped to point inside the first one. + * + * @param {object[]} inventory + */ +function remap(inventory) { + // Group & sort all the $ref pointers, so they're in the order that we need to dereference/remap them + inventory.sort((a, b) => { + if (a.file !== b.file) { + // Group all the $refs that point to the same file + return a.file < b.file ? -1 : +1; + } else if (a.hash !== b.hash) { + // Group all the $refs that point to the same part of the file + return a.hash < b.hash ? -1 : +1; + } else if (a.circular !== b.circular) { + // If the $ref points to itself, then sort it higher than other $refs that point to this $ref + return a.circular ? -1 : +1; + } else if (a.extended !== b.extended) { + // If the $ref extends the resolved value, then sort it lower than other $refs that don't extend the value + return a.extended ? +1 : -1; + } else if (a.indirections !== b.indirections) { + // Sort direct references higher than indirect references + return a.indirections - b.indirections; + } else if (a.depth !== b.depth) { + // Sort $refs by how close they are to the JSON Schema root + return a.depth - b.depth; + } + + // Determine how far each $ref is from the "definitions" property. + // Most people will expect references to be bundled into the the "definitions" property if possible. + const aDefinitionsIndex = a.pathFromRoot.lastIndexOf('/definitions'); + const bDefinitionsIndex = b.pathFromRoot.lastIndexOf('/definitions'); + + if (aDefinitionsIndex !== bDefinitionsIndex) { + // Give higher priority to the $ref that's closer to the "definitions" property + return bDefinitionsIndex - aDefinitionsIndex; + } + + // All else is equal, so use the shorter path, which will produce the shortest possible reference + return a.pathFromRoot.length - b.pathFromRoot.length; + }); + + let file; + let hash; + let pathFromRoot; + for (const entry of inventory) { + // console.log('Re-mapping $ref pointer "%s" at %s', entry.$ref.$ref, entry.pathFromRoot); + + if (!entry.external) { + // This $ref already resolves to the main JSON Schema file + entry.$ref.$ref = entry.hash; + } else if (entry.file === file && entry.hash === hash) { + // This $ref points to the same value as the prevous $ref, so remap it to the same path + entry.$ref.$ref = pathFromRoot; + } else if (entry.file === file && entry.hash.indexOf(`${hash}/`) === 0) { + // This $ref points to a sub-value of the prevous $ref, so remap it beneath that path + entry.$ref.$ref = Pointer$2.join(pathFromRoot, Pointer$2.parse(entry.hash.replace(hash, '#'))); + } else { + // We've moved to a new file or new hash + file = entry.file; + hash = entry.hash; + pathFromRoot = entry.pathFromRoot; + + // This is the first $ref to point to this value, so dereference the value. + // Any other $refs that point to the same value will point to this $ref instead + entry.parent[entry.key] = $Ref$3.dereference(entry.$ref, entry.value); + entry.$ref = entry.parent[entry.key]; + + if (entry.circular) { + // This $ref points to itself + entry.$ref.$ref = entry.pathFromRoot; + } + } + + // console.log(' new value: %s', (entry.$ref && entry.$ref.$ref) ? entry.$ref.$ref : '[object Object]'); + } +} + +/** + * TODO + */ +function findInInventory(inventory, $refParent, $refKey) { + for (let i = 0; i < inventory.length; i++) { + const existingEntry = inventory[i]; + if (existingEntry.parent === $refParent && existingEntry.key === $refKey) { + return existingEntry; + } + } +} + +function removeFromInventory(inventory, entry) { + const index = inventory.indexOf(entry); + inventory.splice(index, 1); +} + +/* eslint-disable no-param-reassign */ + +const { ono: ono$9 } = require$$0$3; + +const Pointer$1 = requirePointer(); +const $Ref$2 = requireRef(); +const url$a = urlExports; + +/** + * Crawls the JSON schema, finds all JSON references, and dereferences them. + * This method mutates the JSON schema object, replacing JSON references with their resolved value. + * + * @param {$RefParser} parser + * @param {$RefParserOptions} options + */ +var dereference$2 = function dereference(parser, options) { + // console.log('Dereferencing $ref pointers in %s', parser.$refs._root$Ref.path); + const dereferenced = crawl$1( + parser.schema, + parser.$refs._root$Ref.path, + '#', + new Set(), + new Set(), + new Map(), + parser.$refs, + options + ); + + parser.$refs.circular = dereferenced.circular; + parser.schema = dereferenced.value; +}; + +/** + * Recursively crawls the given value, and dereferences any JSON references. + * + * @param {*} obj - The value to crawl. If it's not an object or array, it will be ignored. + * @param {string} path - The full path of `obj`, possibly with a JSON Pointer in the hash + * @param {string} pathFromRoot - The path of `obj` from the schema root + * @param {Set<object>} parents - An array of the parent objects that have already been dereferenced + * @param {Set<object>} processedObjects - An array of all the objects that have already been processed + * @param {Map<string,object>} dereferencedCache - An map of all the dereferenced objects + * @param {$Refs} $refs + * @param {$RefParserOptions} options + * @returns {{value: object, circular: boolean}} + */ +function crawl$1(obj, path, pathFromRoot, parents, processedObjects, dereferencedCache, $refs, options) { + let dereferenced; + const result = { + value: obj, + circular: false, + }; + + if (options.dereference.circular === 'ignore' || !processedObjects.has(obj)) { + if (obj && typeof obj === 'object' && !ArrayBuffer.isView(obj)) { + parents.add(obj); + processedObjects.add(obj); + + if ($Ref$2.isAllowed$Ref(obj, options)) { + dereferenced = dereference$Ref( + obj, + path, + pathFromRoot, + parents, + processedObjects, + dereferencedCache, + $refs, + options + ); + + result.circular = dereferenced.circular; + result.value = dereferenced.value; + + // OpenAPI 3.1 $ref overrides: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#fixed-fields-19 + if (obj.description) { + result.value.description = obj.description; + } + + if (obj.summary) { + result.value.summary = obj.summary; + } + } else { + for (const key of Object.keys(obj)) { + const keyPath = Pointer$1.join(path, key); + const keyPathFromRoot = Pointer$1.join(pathFromRoot, key); + const value = obj[key]; + let circular = false; + + if ($Ref$2.isAllowed$Ref(value, options)) { + dereferenced = dereference$Ref( + value, + keyPath, + keyPathFromRoot, + parents, + processedObjects, + dereferencedCache, + $refs, + options + ); + + circular = dereferenced.circular; + + // Avoid pointless mutations; breaks frozen objects to no profit + if (obj[key] !== dereferenced.value) { + obj[key] = dereferenced.value; + + // OpenAPI 3.1 $ref overrides: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#fixed-fields-19 + if (value.description) { + obj[key].description = value.description; + } + + if (value.summary) { + obj[key].summary = value.summary; + } + } + } else if (!parents.has(value)) { + dereferenced = crawl$1( + value, + keyPath, + keyPathFromRoot, + parents, + processedObjects, + dereferencedCache, + $refs, + options + ); + + circular = dereferenced.circular; + + // Avoid pointless mutations; breaks frozen objects to no profit + if (obj[key] !== dereferenced.value) { + obj[key] = dereferenced.value; + } + } else { + circular = foundCircularReference(keyPath, $refs, options); + } + + // Set the "isCircular" flag if this or any other property is circular + result.circular = result.circular || circular; + } + } + + parents.delete(obj); + } + } + + return result; +} + +/** + * Dereferences the given JSON Reference, and then crawls the resulting value. + * + * @param {{$ref: string}} $ref - The JSON Reference to resolve + * @param {string} path - The full path of `$ref`, possibly with a JSON Pointer in the hash + * @param {string} pathFromRoot - The path of `$ref` from the schema root + * @param {Set<object>} parents - An array of the parent objects that have already been dereferenced + * @param {Set<object>} processedObjects - An array of all the objects that have already been dereferenced + * @param {Map<string,object>} dereferencedCache - An map of all the dereferenced objects + * @param {$Refs} $refs + * @param {$RefParserOptions} options + * @returns {{value: object, circular: boolean}} + */ +function dereference$Ref($ref, path, pathFromRoot, parents, processedObjects, dereferencedCache, $refs, options) { + // console.log('Dereferencing $ref pointer "%s" at %s', $ref.$ref, path); + + const $refPath = url$a.resolve(path, $ref.$ref); + + const cache = dereferencedCache.get($refPath); + if (cache) { + const refKeys = Object.keys($ref); + if (refKeys.length > 1) { + const extraKeys = {}; + for (const key of refKeys) { + if (key !== '$ref' && !(key in cache.value)) { + extraKeys[key] = $ref[key]; + } + } + + return { + circular: cache.circular, + value: { ...cache.value, ...extraKeys }, + }; + } + + return cache; + } + + const pointer = $refs._resolve($refPath, path, options); + + if (pointer === null) { + return { + circular: false, + value: null, + }; + } + + // Check for circular references + const directCircular = pointer.circular; + let circular = directCircular || parents.has(pointer.value); + // eslint-disable-next-line chai-friendly/no-unused-expressions + circular && foundCircularReference(path, $refs, options); + + // Dereference the JSON reference + let dereferencedValue = $Ref$2.dereference($ref, pointer.value); + + // Crawl the dereferenced value (unless it's circular) + if (!circular) { + // Determine if the dereferenced value is circular + const dereferenced = crawl$1( + dereferencedValue, + pointer.path, + pathFromRoot, + parents, + processedObjects, + dereferencedCache, + $refs, + options + ); + + circular = dereferenced.circular; + dereferencedValue = dereferenced.value; + } + + if (circular && !directCircular && options.dereference.circular === 'ignore') { + // The user has chosen to "ignore" circular references, so don't change the value + dereferencedValue = $ref; + } + + if (directCircular) { + // The pointer is a DIRECT circular reference (i.e. it references itself). + // So replace the $ref path with the absolute path from the JSON Schema root + dereferencedValue.$ref = pathFromRoot; + } + + const dereferencedObject = { + circular, + value: dereferencedValue, + }; + + // only cache if no extra properties than $ref + if (Object.keys($ref).length === 1) { + dereferencedCache.set($refPath, dereferencedObject); + } + + return dereferencedObject; +} + +/** + * Called when a circular reference is found. + * It sets the {@link $Refs#circular} flag, and throws an error if options.dereference.circular is false. + * + * @param {string} keyPath - The JSON Reference path of the circular reference + * @param {$Refs} $refs + * @param {$RefParserOptions} options + * @returns {boolean} - always returns true, to indicate that a circular reference was found + */ +function foundCircularReference(keyPath, $refs, options) { + $refs.circular = true; + $refs.circularRefs.push(keyPath); + + if (!options.dereference.circular) { + throw ono$9.reference(`Circular $ref pointer found at ${keyPath}`); + } + + return true; +} + +const BINARY_REGEXP = /\.(jpeg|jpg|gif|png|bmp|ico)$/i; + +var binary$3 = { + /** + * The order that this parser will run, in relation to other parsers. + * + * @type {number} + */ + order: 400, + + /** + * Whether to allow "empty" files (zero bytes). + * + * @type {boolean} + */ + allowEmpty: true, + + /** + * Determines whether this parser can parse a given file reference. + * Parsers that return true will be tried, in order, until one successfully parses the file. + * Parsers that return false will be skipped, UNLESS all parsers returned false, in which case + * every parser will be tried. + * + * @param {object} file - An object containing information about the referenced file + * @param {string} file.url - The full URL of the referenced file + * @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.) + * @param {*} file.data - The file contents. This will be whatever data type was returned by the resolver + * @returns {boolean} + */ + canParse(file) { + // Use this parser if the file is a Buffer, and has a known binary extension + return Buffer.isBuffer(file.data) && BINARY_REGEXP.test(file.url); + }, + + /** + * Parses the given data as a Buffer (byte array). + * + * @param {object} file - An object containing information about the referenced file + * @param {string} file.url - The full URL of the referenced file + * @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.) + * @param {*} file.data - The file contents. This will be whatever data type was returned by the resolver + * @returns {Buffer} + */ + parse(file) { + if (Buffer.isBuffer(file.data)) { + return file.data; + } + + // This will reject if data is anything other than a string or typed array + return Buffer.from(file.data); + }, +}; + +const { ParserError: ParserError$4 } = errors$2; + +var json$3 = { + /** + * The order that this parser will run, in relation to other parsers. + * + * @type {number} + */ + order: 100, + + /** + * Whether to allow "empty" files. This includes zero-byte files, as well as empty JSON objects. + * + * @type {boolean} + */ + allowEmpty: true, + + /** + * Determines whether this parser can parse a given file reference. + * Parsers that match will be tried, in order, until one successfully parses the file. + * Parsers that don't match will be skipped, UNLESS none of the parsers match, in which case + * every parser will be tried. + * + * @type {RegExp|string|string[]|function} + */ + canParse: '.json', + + /** + * Parses the given file as JSON + * + * @param {object} file - An object containing information about the referenced file + * @param {string} file.url - The full URL of the referenced file + * @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.) + * @param {*} file.data - The file contents. This will be whatever data type was returned by the resolver + * @returns {Promise} + */ + // eslint-disable-next-line require-await + async parse(file) { + let data = file.data; + if (Buffer.isBuffer(data)) { + data = data.toString(); + } + + if (typeof data === 'string') { + if (data.trim().length === 0) { + return; // This mirrors the YAML behavior + } + + try { + return JSON.parse(data); + } catch (e) { + throw new ParserError$4(e.message, file.url); + } + } + + // data is already a JavaScript value (object, array, number, null, NaN, etc.) + return data; + }, +}; + +const { ParserError: ParserError$3 } = errors$2; + +const TEXT_REGEXP = /\.(txt|htm|html|md|xml|js|min|map|css|scss|less|svg)$/i; + +var text = { + /** + * The order that this parser will run, in relation to other parsers. + * + * @type {number} + */ + order: 300, + + /** + * Whether to allow "empty" files (zero bytes). + * + * @type {boolean} + */ + allowEmpty: true, + + /** + * The encoding that the text is expected to be in. + * + * @type {string} + */ + encoding: 'utf8', + + /** + * Determines whether this parser can parse a given file reference. + * Parsers that return true will be tried, in order, until one successfully parses the file. + * Parsers that return false will be skipped, UNLESS all parsers returned false, in which case + * every parser will be tried. + * + * @param {object} file - An object containing information about the referenced file + * @param {string} file.url - The full URL of the referenced file + * @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.) + * @param {*} file.data - The file contents. This will be whatever data type was returned by the resolver + * @returns {boolean} + */ + canParse(file) { + // Use this parser if the file is a string or Buffer, and has a known text-based extension + return (typeof file.data === 'string' || Buffer.isBuffer(file.data)) && TEXT_REGEXP.test(file.url); + }, + + /** + * Parses the given file as text + * + * @param {object} file - An object containing information about the referenced file + * @param {string} file.url - The full URL of the referenced file + * @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.) + * @param {*} file.data - The file contents. This will be whatever data type was returned by the resolver + * @returns {string} + */ + parse(file) { + if (typeof file.data === 'string') { + return file.data; + } else if (Buffer.isBuffer(file.data)) { + return file.data.toString(this.encoding); + } + + throw new ParserError$3('data is not text', file.url); + }, +}; + +var jsYaml = {}; + +var loader$1 = {}; + +var common$9 = {}; + +function isNothing(subject) { + return (typeof subject === 'undefined') || (subject === null); +} + + +function isObject$k(subject) { + return (typeof subject === 'object') && (subject !== null); +} + + +function toArray$2(sequence) { + if (Array.isArray(sequence)) return sequence; + else if (isNothing(sequence)) return []; + + return [ sequence ]; +} + + +function extend$1(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$1(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$9.isNothing = isNothing; +common$9.isObject = isObject$k; +common$9.toArray = toArray$2; +common$9.repeat = repeat$1; +common$9.isNegativeZero = isNegativeZero; +common$9.extend = extend$1; + +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$4(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$4.prototype = Object.create(Error.prototype); +YAMLException$4.prototype.constructor = YAMLException$4; + + +YAMLException$4.prototype.toString = function toString(compact) { + return this.name + ': ' + formatError(this, compact); +}; + + +var exception = YAMLException$4; + +var common$8 = common$9; + + +// get snippet for a single line, respecting maxLength +function getLine$1(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$8.repeat(' ', max - string.length) + string; +} + + +function makeSnippet$1(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$1( + mark.buffer, + lineStarts[foundLineNo - i], + lineEnds[foundLineNo - i], + mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i]), + maxLineLength + ); + result = common$8.repeat(' ', options.indent) + padStart((mark.line - i + 1).toString(), lineNoLength) + + ' | ' + line.str + '\n' + result; + } + + line = getLine$1(mark.buffer, lineStarts[foundLineNo], lineEnds[foundLineNo], mark.position, maxLineLength); + result += common$8.repeat(' ', options.indent) + padStart((mark.line + 1).toString(), lineNoLength) + + ' | ' + line.str + '\n'; + result += common$8.repeat('-', options.indent + lineNoLength + 3 + line.pos) + '^' + '\n'; + + for (i = 1; i <= options.linesAfter; i++) { + if (foundLineNo + i >= lineEnds.length) break; + line = getLine$1( + mark.buffer, + lineStarts[foundLineNo + i], + lineEnds[foundLineNo + i], + mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i]), + maxLineLength + ); + result += common$8.repeat(' ', options.indent) + padStart((mark.line + i + 1).toString(), lineNoLength) + + ' | ' + line.str + '\n'; + } + + return result.replace(/\n$/, ''); +} + + +var snippet = makeSnippet$1; + +var YAMLException$3 = exception; + +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$f(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.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$3('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.'); + } +} + +var type$e = Type$f; + +/*eslint-disable max-len*/ + +var YAMLException$2 = exception; +var Type$e = type$e; + + +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$4(definition) { + return this.extend(definition); +} + + +Schema$4.prototype.extend = function extend(definition) { + var implicit = []; + var explicit = []; + + if (definition instanceof Type$e) { + // 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$2('Schema.extend argument should be a Type, [ Type ], ' + + 'or a schema definition ({ implicit: [...], explicit: [...] })'); + } + + implicit.forEach(function (type) { + if (!(type instanceof Type$e)) { + throw new YAMLException$2('Specified list of YAML types (or a single Type object) contains a non-Type object.'); + } + + 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.'); + } + + if (type.multi) { + throw new YAMLException$2('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$e)) { + throw new YAMLException$2('Specified list of YAML types (or a single Type object) contains a non-Type object.'); + } + }); + + var result = Object.create(Schema$4.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; +}; + + +var schema$1 = Schema$4; + +var Type$d = type$e; + +var str = new Type$d('tag:yaml.org,2002:str', { + kind: 'scalar', + construct: function (data) { return data !== null ? data : ''; } +}); + +var Type$c = type$e; + +var seq$1 = new Type$c('tag:yaml.org,2002:seq', { + kind: 'sequence', + construct: function (data) { return data !== null ? data : []; } +}); + +var Type$b = type$e; + +var map$3 = new Type$b('tag:yaml.org,2002:map', { + kind: 'mapping', + construct: function (data) { return data !== null ? data : {}; } +}); + +var Schema$3 = schema$1; + + +var failsafe$1 = new Schema$3({ + explicit: [ + str, + seq$1, + map$3 + ] +}); + +var Type$a = type$e; + +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$2(object) { + return object === null; +} + +var _null = new Type$a('tag:yaml.org,2002:null', { + kind: 'scalar', + resolve: resolveYamlNull, + construct: constructYamlNull, + predicate: isNull$2, + represent: { + canonical: function () { return '~'; }, + lowercase: function () { return 'null'; }, + uppercase: function () { return 'NULL'; }, + camelcase: function () { return 'Null'; }, + empty: function () { return ''; } + }, + defaultStyle: 'lowercase' +}); + +var Type$9 = type$e; + +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$2(object) { + return Object.prototype.toString.call(object) === '[object Boolean]'; +} + +var bool = new Type$9('tag:yaml.org,2002:bool', { + kind: 'scalar', + resolve: resolveYamlBoolean, + construct: constructYamlBoolean, + predicate: isBoolean$2, + 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$7 = common$9; +var Type$8 = type$e; + +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$2(object) { + return (Object.prototype.toString.call(object)) === '[object Number]' && + (object % 1 === 0 && !common$7.isNegativeZero(object)); +} + +var int = new Type$8('tag:yaml.org,2002:int', { + kind: 'scalar', + resolve: resolveYamlInteger, + construct: constructYamlInteger, + predicate: isInteger$2, + 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' ] + } +}); + +var common$6 = common$9; +var Type$7 = type$e; + +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$6.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$6.isNegativeZero(object)); +} + +var float = new Type$7('tag:yaml.org,2002:float', { + kind: 'scalar', + resolve: resolveYamlFloat, + construct: constructYamlFloat, + predicate: isFloat, + represent: representYamlFloat, + defaultStyle: 'lowercase' +}); + +var json$2 = failsafe$1.extend({ + implicit: [ + _null, + bool, + int, + float + ] +}); + +var core$7 = json$2; + +var Type$6 = type$e; + +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$1 = new Type$6('tag:yaml.org,2002:timestamp', { + kind: 'scalar', + resolve: resolveYamlTimestamp, + construct: constructYamlTimestamp, + instanceOf: Date, + represent: representYamlTimestamp +}); + +var Type$5 = type$e; + +function resolveYamlMerge(data) { + return data === '<<' || data === null; +} + +var merge$1 = new Type$5('tag:yaml.org,2002:merge', { + kind: 'scalar', + resolve: resolveYamlMerge +}); + +/*eslint-disable no-bitwise*/ + + +var Type$4 = type$e; + + +// [ 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]'; +} + +var binary$2 = new Type$4('tag:yaml.org,2002:binary', { + kind: 'scalar', + resolve: resolveYamlBinary, + construct: constructYamlBinary, + predicate: isBinary, + represent: representYamlBinary +}); + +var Type$3 = type$e; + +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$1 = new Type$3('tag:yaml.org,2002:omap', { + kind: 'sequence', + resolve: resolveYamlOmap, + construct: constructYamlOmap +}); + +var Type$2 = type$e; + +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$1 = new Type$2('tag:yaml.org,2002:pairs', { + kind: 'sequence', + resolve: resolveYamlPairs, + construct: constructYamlPairs +}); + +var Type$1 = type$e; + +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$2 = new Type$1('tag:yaml.org,2002:set', { + kind: 'mapping', + resolve: resolveYamlSet, + construct: constructYamlSet +}); + +var _default$1 = core$7.extend({ + implicit: [ + timestamp$1, + merge$1 + ], + explicit: [ + binary$2, + omap$1, + pairs$1, + set$2 + ] +}); + +/*eslint-disable max-len,no-use-before-define*/ + +var common$5 = common$9; +var YAMLException$1 = exception; +var makeSnippet = snippet; +var DEFAULT_SCHEMA$1 = _default$1; + + +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$1 = 0; i$1 < 256; i$1++) { + simpleEscapeCheck[i$1] = simpleEscapeSequence(i$1) ? 1 : 0; + simpleEscapeMap[i$1] = simpleEscapeSequence(i$1); +} + + +function State$1(input, options) { + this.input = input; + + this.filename = options['filename'] || null; + this.schema = options['schema'] || DEFAULT_SCHEMA$1; + 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$1(message, mark); +} + +function throwError$1(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$1(state, 'duplication of %YAML directive'); + } + + if (args.length !== 1) { + throwError$1(state, 'YAML directive accepts exactly one argument'); + } + + match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]); + + if (match === null) { + throwError$1(state, 'ill-formed argument of the YAML directive'); + } + + major = parseInt(match[1], 10); + minor = parseInt(match[2], 10); + + if (major !== 1) { + throwError$1(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$1(state, 'TAG directive accepts exactly two arguments'); + } + + handle = args[0]; + prefix = args[1]; + + if (!PATTERN_TAG_HANDLE.test(handle)) { + throwError$1(state, 'ill-formed tag handle (first argument) of the TAG directive'); + } + + if (_hasOwnProperty$1.call(state.tagMap, handle)) { + throwError$1(state, 'there is a previously declared suffix for "' + handle + '" tag handle'); + } + + if (!PATTERN_TAG_URI.test(prefix)) { + throwError$1(state, 'ill-formed tag prefix (second argument) of the TAG directive'); + } + + try { + prefix = decodeURIComponent(prefix); + } catch (err) { + throwError$1(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$1(state, 'expected valid JSON character'); + } + } + } else if (PATTERN_NON_PRINTABLE.test(_result)) { + throwError$1(state, 'the stream contains non-printable characters'); + } + + state.result += _result; + } +} + +function mergeMappings(state, destination, source, overridableKeys) { + var sourceKeys, key, index, quantity; + + if (!common$5.isObject(source)) { + throwError$1(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, 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$1(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.lineStart = startLineStart || state.lineStart; + state.position = startPos || state.position; + throwError$1(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$1(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$5.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$1(state, 'unexpected end of the document within a single quoted scalar'); + + } else { + state.position++; + captureEnd = state.position; + } + } + + throwError$1(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$1(state, 'expected hexadecimal character'); + } + } + + state.result += charFromCodepoint(hexResult); + + state.position++; + + } else { + throwError$1(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$1(state, 'unexpected end of the document within a double quoted scalar'); + + } else { + state.position++; + captureEnd = state.position; + } + } + + throwError$1(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$1(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$1(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$1(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$1(state, 'repeat of a chomping mode identifier'); + } + + } else if ((tmp = fromDecimalCode(ch)) >= 0) { + if (tmp === 0) { + throwError$1(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$1(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$5.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$5.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + + // End of more-indented block. + } else if (atMoreIndented) { + atMoreIndented = false; + state.result += common$5.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$5.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$5.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$1(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$1(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$1(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$1(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$1(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$1(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$1(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$1(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$1(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$1(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$1(state, 'named tag handle cannot contain such characters'); + } + + isNamed = true; + _position = state.position + 1; + } else { + throwError$1(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$1(state, 'tag suffix cannot contain flow indicator characters'); + } + } + + if (tagName && !PATTERN_TAG_URI.test(tagName)) { + throwError$1(state, 'tag name cannot contain such characters: ' + tagName); + } + + try { + tagName = decodeURIComponent(tagName); + } catch (err) { + throwError$1(state, 'tag name is malformed: ' + 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$1(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$1(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$1(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$1(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$1(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<parent + atNewLine = false, + hasContent = false, + typeIndex, + typeQuantity, + typeList, + type, + flowIndent, + blockIndent; + + if (state.listener !== null) { + state.listener('open', state); + } + + state.tag = null; + state.anchor = null; + state.kind = null; + state.result = null; + + allowBlockStyles = allowBlockScalars = allowBlockCollections = + CONTEXT_BLOCK_OUT === nodeContext || + CONTEXT_BLOCK_IN === nodeContext; + + if (allowToSeek) { + if (skipSeparationSpace(state, true, -1)) { + atNewLine = true; + + if (state.lineIndent > 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$1(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$1(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$1.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$1(state, 'unknown tag !<' + state.tag + '>'); + } + + if (state.result !== null && type.kind !== state.kind) { + throwError$1(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$1(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$1(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$1(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$1(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$1(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$1(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'); +} + + +loader$1.loadAll = loadAll; +loader$1.load = load$1; + +var dumper$1 = {}; + +/*eslint-disable no-use-before-define*/ + +var common$4 = common$9; +var YAMLException = exception; +var DEFAULT_SCHEMA = _default$1; + +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$4.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$4.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$4.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$4.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$1(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$1(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$1(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$1(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$1(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$1(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$1(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$1(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 ''; +} + +dumper$1.dump = dump$1; + +var loader = loader$1; +var dumper = dumper$1; + + +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.'); + }; +} + + +jsYaml.Type = type$e; +jsYaml.Schema = schema$1; +jsYaml.FAILSAFE_SCHEMA = failsafe$1; +jsYaml.JSON_SCHEMA = json$2; +jsYaml.CORE_SCHEMA = core$7; +jsYaml.DEFAULT_SCHEMA = _default$1; +jsYaml.load = loader.load; +jsYaml.loadAll = loader.loadAll; +jsYaml.dump = dumper.dump; +jsYaml.YAMLException = exception; + +// Re-export all types in case user wants to create custom schema +jsYaml.types = { + binary: binary$2, + float: float, + map: map$3, + null: _null, + pairs: pairs$1, + set: set$2, + timestamp: timestamp$1, + bool: bool, + int: int, + merge: merge$1, + omap: omap$1, + seq: seq$1, + str: str +}; + +// Removed functions from JS-YAML 3.0.x +jsYaml.safeLoad = renamed('safeLoad', 'load'); +jsYaml.safeLoadAll = renamed('safeLoadAll', 'loadAll'); +jsYaml.safeDump = renamed('safeDump', 'dump'); + +const yaml$3 = jsYaml; +const { JSON_SCHEMA } = jsYaml; + +const { ParserError: ParserError$2 } = errors$2; + +var yaml_1 = { + /** + * The order that this parser will run, in relation to other parsers. + * + * @type {number} + */ + order: 200, + + /** + * Whether to allow "empty" files. This includes zero-byte files, as well as empty JSON objects. + * + * @type {boolean} + */ + allowEmpty: true, + + /** + * Determines whether this parser can parse a given file reference. + * Parsers that match will be tried, in order, until one successfully parses the file. + * Parsers that don't match will be skipped, UNLESS none of the parsers match, in which case + * every parser will be tried. + * + * @type {RegExp|string[]|function} + */ + canParse: ['.yaml', '.yml', '.json'], // JSON is valid YAML + + /** + * Parses the given file as YAML + * + * @param {object} file - An object containing information about the referenced file + * @param {string} file.url - The full URL of the referenced file + * @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.) + * @param {*} file.data - The file contents. This will be whatever data type was returned by the resolver + * @returns {Promise} + */ + // eslint-disable-next-line require-await + async parse(file) { + let data = file.data; + if (Buffer.isBuffer(data)) { + data = data.toString(); + } + + if (typeof data === 'string') { + try { + return yaml$3.load(data, { schema: JSON_SCHEMA }); + } catch (e) { + throw new ParserError$2(e.message, file.url); + } + } + + // data is already a JavaScript value (object, array, number, null, NaN, etc.) + return data; + }, +}; + +const fs$3 = require$$0$8; + +const { ono: ono$8 } = require$$0$3; + +const { ResolverError: ResolverError$3 } = errors$2; +const url$9 = urlExports; + +var file = { + /** + * The order that this resolver will run, in relation to other resolvers. + * + * @type {number} + */ + order: 100, + + /** + * Determines whether this resolver can read a given file reference. + * Resolvers that return true will be tried, in order, until one successfully resolves the file. + * Resolvers that return false will not be given a chance to resolve the file. + * + * @param {object} file - An object containing information about the referenced file + * @param {string} file.url - The full URL of the referenced file + * @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.) + * @returns {boolean} + */ + canRead(file) { + return url$9.isFileSystemPath(file.url); + }, + + /** + * Reads the given file and returns its raw contents as a Buffer. + * + * @param {object} file - An object containing information about the referenced file + * @param {string} file.url - The full URL of the referenced file + * @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.) + * @returns {Promise<Buffer>} + */ + read(file) { + return new Promise((resolve, reject) => { + let path; + try { + path = url$9.toFileSystemPath(file.url); + } catch (err) { + reject(new ResolverError$3(ono$8.uri(err, `Malformed URI: ${file.url}`), file.url)); + } + + // console.log('Opening file: %s', path); + + try { + fs$3.readFile(path, (err, data) => { + if (err) { + reject(new ResolverError$3(ono$8(err, `Error opening file "${path}"`), path)); + } else { + resolve(data); + } + }); + } catch (err) { + reject(new ResolverError$3(ono$8(err, `Error opening file "${path}"`), path)); + } + }); + }, +}; + +const http$4 = require$$0$a; +const https$3 = require$$1$4; + +const { ono: ono$7 } = require$$0$3; + +const { ResolverError: ResolverError$2 } = errors$2; +const url$8 = urlExports; + +/** + * Sends an HTTP GET request. + * + * @param {Url} u - A parsed {@link Url} object + * @param {object} httpOptions - The `options.resolve.http` object + * + * @returns {Promise<Response>} + * The promise resolves with the HTTP Response object. + */ +function get$8(u, httpOptions) { + return new Promise((resolve, reject) => { + // console.log('GET', u.href); + + const protocol = u.protocol === 'https:' ? https$3 : http$4; + const req = protocol.get({ + hostname: u.hostname, + port: u.port, + path: u.path, + auth: u.auth, + protocol: u.protocol, + headers: httpOptions.headers || {}, + withCredentials: httpOptions.withCredentials, + }); + + if (typeof req.setTimeout === 'function') { + req.setTimeout(httpOptions.timeout); + } + + req.on('timeout', () => { + req.abort(); + }); + + req.on('error', reject); + + req.once('response', res => { + res.body = Buffer.alloc(0); + + res.on('data', data => { + res.body = Buffer.concat([res.body, Buffer.from(data)]); + }); + + res.on('error', reject); + + res.on('end', () => { + resolve(res); + }); + }); + }); +} + +/** + * Downloads the given file. + * + * @param {Url|string} u - The url to download (can be a parsed {@link Url} object) + * @param {object} httpOptions - The `options.resolve.http` object + * @param {number} [redirects] - The redirect URLs that have already been followed + * + * @returns {Promise<Buffer>} + * The promise resolves with the raw downloaded data, or rejects if there is an HTTP error. + */ +function download(u, httpOptions, redirects) { + return new Promise((resolve, reject) => { + u = url$8.parse(u); // eslint-disable-line no-param-reassign + redirects = redirects || []; // eslint-disable-line no-param-reassign + redirects.push(u.href); + + get$8(u, httpOptions) + .then(res => { + if (res.statusCode >= 400) { + throw ono$7({ status: res.statusCode }, `HTTP ERROR ${res.statusCode}`); + } else if (res.statusCode >= 300) { + if (redirects.length > httpOptions.redirects) { + reject( + new ResolverError$2( + ono$7( + { status: res.statusCode }, + `Error downloading ${redirects[0]}. \nToo many redirects: \n ${redirects.join(' \n ')}` + ) + ) + ); + } else if (!res.headers.location) { + throw ono$7({ status: res.statusCode }, `HTTP ${res.statusCode} redirect with no location header`); + } else { + // console.log('HTTP %d redirect %s -> %s', res.statusCode, u.href, res.headers.location); + const redirectTo = url$8.resolve(u, res.headers.location); + download(redirectTo, httpOptions, redirects).then(resolve, reject); + } + } else { + resolve(res.body || Buffer.alloc(0)); + } + }) + .catch(err => { + reject(new ResolverError$2(ono$7(err, `Error downloading ${u.href}`), u.href)); + }); + }); +} + +var http_1$1 = { + /** + * The order that this resolver will run, in relation to other resolvers. + * + * @type {number} + */ + order: 200, + + /** + * HTTP headers to send when downloading files. + * + * @example: + * { + * "User-Agent": "JSON Schema $Ref Parser", + * Accept: "application/json" + * } + * + * @type {object} + */ + headers: null, + + /** + * HTTP request timeout (in milliseconds). + * + * @type {number} + */ + timeout: 5000, // 5 seconds + + /** + * The maximum number of HTTP redirects to follow. + * To disable automatic following of redirects, set this to zero. + * + * @type {number} + */ + redirects: 5, + + /** + * The `withCredentials` option of XMLHttpRequest. + * Set this to `true` if you're downloading files from a CORS-enabled server that requires authentication + * + * @type {boolean} + */ + withCredentials: false, + + /** + * Determines whether this resolver can read a given file reference. + * Resolvers that return true will be tried in order, until one successfully resolves the file. + * Resolvers that return false will not be given a chance to resolve the file. + * + * @param {object} file - An object containing information about the referenced file + * @param {string} file.url - The full URL of the referenced file + * @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.) + * @returns {boolean} + */ + canRead(file) { + return url$8.isHttp(file.url); + }, + + /** + * Reads the given URL and returns its raw contents as a Buffer. + * + * @param {object} file - An object containing information about the referenced file + * @param {string} file.url - The full URL of the referenced file + * @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.) + * @returns {Promise<Buffer>} + */ + read(file) { + const u = url$8.parse(file.url); + + if (process.browser && !u.protocol) { + // Use the protocol of the current page + // eslint-disable-next-line no-restricted-globals + u.protocol = url$8.parse(location.href).protocol; + } + + return download(u, this); + }, +}; + +/* eslint-disable no-param-reassign */ + +const binaryParser = binary$3; +const jsonParser = json$3; +const textParser = text; +const yamlParser = yaml_1; +const fileResolver = file; +const httpResolver = http_1$1; + +var options$1 = $RefParserOptions$1; + +/** + * Options that determine how JSON schemas are parsed, resolved, and dereferenced. + * + * @param {object|$RefParserOptions} [options] - Overridden options + * @constructor + */ +function $RefParserOptions$1(options) { + merge(this, $RefParserOptions$1.defaults); + merge(this, options); +} + +$RefParserOptions$1.defaults = { + /** + * Determines how different types of files will be parsed. + * + * You can add additional parsers of your own, replace an existing one with + * your own implementation, or disable any parser by setting it to false. + */ + parse: { + json: jsonParser, + yaml: yamlParser, + text: textParser, + binary: binaryParser, + }, + + /** + * Determines how JSON References will be resolved. + * + * You can add additional resolvers of your own, replace an existing one with + * your own implementation, or disable any resolver by setting it to false. + */ + resolve: { + file: fileResolver, + http: httpResolver, + + /** + * Determines whether external $ref pointers will be resolved. + * If this option is disabled, then none of above resolvers will be called. + * Instead, external $ref pointers will simply be ignored. + * + * @type {boolean} + */ + external: true, + }, + + /** + * By default, JSON Schema $Ref Parser throws the first error it encounters. Setting `continueOnError` to `true` + * causes it to keep processing as much as possible and then throw a single error that contains all errors + * that were encountered. + */ + continueOnError: false, + + /** + * Determines the types of JSON references that are allowed. + */ + dereference: { + /** + * Dereference circular (recursive) JSON references? + * If false, then a {@link ReferenceError} will be thrown if a circular reference is found. + * If "ignore", then circular references will not be dereferenced. + * + * @type {boolean|string} + */ + circular: true, + }, +}; + +/** + * Merges the properties of the source object into the target object. + * + * @param {object} target - The object that we're populating + * @param {?object} source - The options that are being merged + * @returns {object} + */ +function merge(target, source) { + if (isMergeable(source)) { + const keys = Object.keys(source); + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + const sourceSetting = source[key]; + const targetSetting = target[key]; + + if (isMergeable(sourceSetting)) { + // It's a nested object, so merge it recursively + target[key] = merge(targetSetting || {}, sourceSetting); + } else if (sourceSetting !== undefined) { + // It's a scalar value, function, or array. No merging necessary. Just overwrite the target value. + target[key] = sourceSetting; + } + } + } + + return target; +} + +/** + * Determines whether the given value can be merged, + * or if it is a scalar value that should just override the target value. + * + * @param {*} val + * @returns {Boolean} + */ +function isMergeable(val) { + return val && typeof val === 'object' && !Array.isArray(val) && !(val instanceof RegExp) && !(val instanceof Date); +} + +const Options$1 = options$1; + +/** + * Normalizes the given arguments, accounting for optional args. + * + * @param {Arguments} args + * @returns {object} + */ +var normalizeArgs$2 = function normalizeArgs(args) { + let path; + let schema; + let options; + let callback; + + // eslint-disable-next-line no-param-reassign + args = Array.prototype.slice.call(args); + + if (typeof args[args.length - 1] === 'function') { + // The last parameter is a callback function + callback = args.pop(); + } + + if (typeof args[0] === 'string') { + // The first parameter is the path + path = args[0]; + if (typeof args[2] === 'object') { + // The second parameter is the schema, and the third parameter is the options + schema = args[1]; + options = args[2]; + } else { + // The second parameter is the options + schema = undefined; + options = args[1]; + } + } else { + // The first parameter is the schema + path = ''; + schema = args[0]; + options = args[1]; + } + + if (!(options instanceof Options$1)) { + options = new Options$1(options); + } + + return { + path, + schema, + options, + callback, + }; +}; + +var plugins$1 = {}; + +/** + * Returns the given plugins as an array, rather than an object map. + * All other methods in this module expect an array of plugins rather than an object map. + * + * @param {object} plugins - A map of plugin objects + * @return {object[]} + */ + +plugins$1.all = function (plugins) { + return Object.keys(plugins) + .filter(key => { + return typeof plugins[key] === 'object'; + }) + .map(key => { + // eslint-disable-next-line no-param-reassign + plugins[key].name = key; + return plugins[key]; + }); +}; + +/** + * Filters the given plugins, returning only the ones return `true` for the given method. + * + * @param {object[]} plugins - An array of plugin objects + * @param {string} method - The name of the filter method to invoke for each plugin + * @param {object} file - A file info object, which will be passed to each method + * @return {object[]} + */ +plugins$1.filter = function (plugins, method, file) { + return plugins.filter(plugin => { + return !!getResult(plugin, method, file); + }); +}; + +/** + * Sorts the given plugins, in place, by their `order` property. + * + * @param {object[]} plugins - An array of plugin objects + * @returns {object[]} + */ +plugins$1.sort = function (plugins) { + for (const plugin of plugins) { + plugin.order = plugin.order || Number.MAX_SAFE_INTEGER; + } + + return plugins.sort((a, b) => { + return a.order - b.order; + }); +}; + +/** + * Runs the specified method of the given plugins, in order, until one of them returns a successful result. + * Each method can return a synchronous value, a Promise, or call an error-first callback. + * If the promise resolves successfully, or the callback is called without an error, then the result + * is immediately returned and no further plugins are called. + * If the promise rejects, or the callback is called with an error, then the next plugin is called. + * If ALL plugins fail, then the last error is thrown. + * + * @param {object[]} plugins - An array of plugin objects + * @param {string} method - The name of the method to invoke for each plugin + * @param {object} file - A file info object, which will be passed to each method + * @returns {Promise} + */ +plugins$1.run = function (plugins, method, file, $refs) { + let plugin; + let lastError; + let index = 0; + + return new Promise((resolve, reject) => { + runNextPlugin(); + + function runNextPlugin() { + plugin = plugins[index++]; + if (!plugin) { + // There are no more functions, so re-throw the last error + return reject(lastError); + } + + try { + // console.log(' %s', plugin.name); + const result = getResult(plugin, method, file, callback, $refs); + if (result && typeof result.then === 'function') { + // A promise was returned + result.then(onSuccess, onError); + } else if (result !== undefined) { + // A synchronous result was returned + onSuccess(result); + } else if (index === plugins.length) { + throw new Error('No promise has been returned or callback has been called.'); + } + } catch (e) { + onError(e); + } + } + + function callback(err, result) { + if (err) { + onError(err); + } else { + onSuccess(result); + } + } + + function onSuccess(result) { + // console.log(' success'); + resolve({ + plugin, + result, + }); + } + + function onError(error) { + // console.log(' %s', err.message || err); + lastError = { + plugin, + error, + }; + runNextPlugin(); + } + }); +}; + +/** + * Returns the value of the given property. + * If the property is a function, then the result of the function is returned. + * If the value is a RegExp, then it will be tested against the file URL. + * If the value is an aray, then it will be compared against the file extension. + * + * @param {object} obj - The object whose property/method is called + * @param {string} prop - The name of the property/method to invoke + * @param {object} file - A file info object, which will be passed to the method + * @param {function} [callback] - A callback function, which will be passed to the method + * @returns {*} + */ +function getResult(obj, prop, file, callback, $refs) { + const value = obj[prop]; + + if (typeof value === 'function') { + return value.apply(obj, [file, callback, $refs]); + } + + if (!callback) { + // The synchronous plugin functions (canParse and canRead) + // allow a "shorthand" syntax, where the user can match + // files by RegExp or by file extension. + if (value instanceof RegExp) { + return value.test(file.url); + } else if (typeof value === 'string') { + return value === file.extension; + } else if (Array.isArray(value)) { + return value.indexOf(file.extension) !== -1; + } + } + + return value; +} + +const { ono: ono$6 } = require$$0$3; + +const { + ResolverError: ResolverError$1, + ParserError: ParserError$1, + UnmatchedParserError: UnmatchedParserError$1, + UnmatchedResolverError: UnmatchedResolverError$1, + isHandledError: isHandledError$2, +} = errors$2; +const plugins = plugins$1; +const url$7 = urlExports; + +/** + * Reads and parses the specified file path or URL. + * + * @param {string} path - This path MUST already be resolved, since `read` doesn't know the resolution context + * @param {$Refs} $refs + * @param {$RefParserOptions} options + * + * @returns {Promise} + * The promise resolves with the parsed file contents, NOT the raw (Buffer) contents. + */ +var parse$8 = async function parse(path, $refs, options) { + // Remove the URL fragment, if any + // eslint-disable-next-line no-param-reassign + path = url$7.stripHash(path); + + // Add a new $Ref for this file, even though we don't have the value yet. + // This ensures that we don't simultaneously read & parse the same file multiple times + const $ref = $refs._add(path); + + // This "file object" will be passed to all resolvers and parsers. + const file = { + url: path, + extension: url$7.getExtension(path), + }; + + // Read the file and then parse the data + try { + const resolver = await readFile$1(file, options, $refs); + $ref.pathType = resolver.plugin.name; + file.data = resolver.result; + + const parser = await parseFile(file, options, $refs); + $ref.value = parser.result; + + return parser.result; + } catch (err) { + if (isHandledError$2(err)) { + $ref.value = err; + } + + throw err; + } +}; + +/** + * Reads the given file, using the configured resolver plugins + * + * @param {object} file - An object containing information about the referenced file + * @param {string} file.url - The full URL of the referenced file + * @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.) + * @param {$RefParserOptions} options + * + * @returns {Promise} + * The promise resolves with the raw file contents and the resolver that was used. + */ +function readFile$1(file, options, $refs) { + return new Promise((resolve, reject) => { + // console.log('Reading %s', file.url); + + // Find the resolvers that can read this file + let resolvers = plugins.all(options.resolve); + resolvers = plugins.filter(resolvers, 'canRead', file); + + // Run the resolvers, in order, until one of them succeeds + plugins.sort(resolvers); + plugins.run(resolvers, 'read', file, $refs).then(resolve, onError); + + function onError(err) { + if (!err && options.continueOnError) { + // No resolver could be matched + reject(new UnmatchedResolverError$1(file.url)); + } else if (!err || !('error' in err)) { + // Throw a generic, friendly error. + reject(ono$6.syntax(`Unable to resolve $ref pointer "${file.url}"`)); + } else if (err.error instanceof ResolverError$1) { + // Throw the original error, if it's one of our own (user-friendly) errors. + reject(err.error); + } else { + reject(new ResolverError$1(err, file.url)); + } + } + }); +} + +/** + * Parses the given file's contents, using the configured parser plugins. + * + * @param {object} file - An object containing information about the referenced file + * @param {string} file.url - The full URL of the referenced file + * @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.) + * @param {*} file.data - The file contents. This will be whatever data type was returned by the resolver + * @param {$RefParserOptions} options + * + * @returns {Promise} + * The promise resolves with the parsed file contents and the parser that was used. + */ +function parseFile(file, options, $refs) { + return new Promise((resolve, reject) => { + // console.log('Parsing %s', file.url); + + // Find the parsers that can read this file type. + // If none of the parsers are an exact match for this file, then we'll try ALL of them. + // This handles situations where the file IS a supported type, just with an unknown extension. + const allParsers = plugins.all(options.parse); + const filteredParsers = plugins.filter(allParsers, 'canParse', file); + const parsers = filteredParsers.length > 0 ? filteredParsers : allParsers; + + // Run the parsers, in order, until one of them succeeds + plugins.sort(parsers); + plugins.run(parsers, 'parse', file, $refs).then(onParsed, onError); + + function onParsed(parser) { + if (!parser.plugin.allowEmpty && isEmpty(parser.result)) { + reject(ono$6.syntax(`Error parsing "${file.url}" as ${parser.plugin.name}. \nParsed value is empty`)); + } else { + resolve(parser); + } + } + + function onError(err) { + if (!err && options.continueOnError) { + // No resolver could be matched + reject(new UnmatchedParserError$1(file.url)); + } else if (!err || !('error' in err)) { + reject(ono$6.syntax(`Unable to parse ${file.url}`)); + } else if (err.error instanceof ParserError$1) { + reject(err.error); + } else { + reject(new ParserError$1(err.error.message, file.url)); + } + } + }); +} + +/** + * Determines whether the parsed value is "empty". + * + * @param {*} value + * @returns {boolean} + */ +function isEmpty(value) { + return ( + value === undefined || + (typeof value === 'object' && Object.keys(value).length === 0) || + (typeof value === 'string' && value.trim().length === 0) || + (Buffer.isBuffer(value) && value.length === 0) + ); +} + +const { ono: ono$5 } = require$$0$3; + +const $Ref$1 = requireRef(); +const url$6 = urlExports; + +var refs = $Refs$1; + +/** + * This class is a map of JSON references and their resolved values. + */ +function $Refs$1() { + /** + * Indicates whether the schema contains any circular references. + * + * @type {boolean} + */ + this.circular = false; + + /** + * Contains any circular references that may be present within the schema. + * + * @type {array} + */ + this.circularRefs = []; + + /** + * A map of paths/urls to {@link $Ref} objects + * + * @type {object} + * @protected + */ + this._$refs = {}; + + /** + * The {@link $Ref} object that is the root of the JSON schema. + * + * @type {$Ref} + * @protected + */ + this._root$Ref = null; +} + +/** + * Returns the paths of all the files/URLs that are referenced by the JSON schema, + * including the schema itself. + * + * @param {...string|string[]} [types] - Only return paths of the given types ("file", "http", etc.) + * @returns {string[]} + */ +$Refs$1.prototype.paths = function (types) { + const paths = getPaths(this._$refs, arguments); + return paths.map(path => { + return path.decoded; + }); +}; + +/** + * Returns the map of JSON references and their resolved values. + * + * @param {...string|string[]} [types] - Only return references of the given types ("file", "http", etc.) + * @returns {object} + */ +$Refs$1.prototype.values = function (types) { + const $refs = this._$refs; + const paths = getPaths($refs, arguments); + return paths.reduce((obj, path) => { + // eslint-disable-next-line no-param-reassign + obj[path.decoded] = $refs[path.encoded].value; + return obj; + }, {}); +}; + +/** + * Returns a POJO (plain old JavaScript object) for serialization as JSON. + * + * @returns {object} + */ +$Refs$1.prototype.toJSON = $Refs$1.prototype.values; + +/** + * Determines whether the given JSON reference exists. + * + * @param {string} path - The path being resolved, optionally with a JSON pointer in the hash + * @param {$RefParserOptions} [options] + * @returns {boolean} + */ +$Refs$1.prototype.exists = function (path, options) { + try { + this._resolve(path, '', options); + return true; + } catch (e) { + return false; + } +}; + +/** + * Resolves the given JSON reference and returns the resolved value. + * + * @param {string} path - The path being resolved, with a JSON pointer in the hash + * @param {$RefParserOptions} [options] + * @returns {*} - Returns the resolved value + */ +$Refs$1.prototype.get = function (path, options) { + return this._resolve(path, '', options).value; +}; + +/** + * Sets the value of a nested property within this {@link $Ref#value}. + * If the property, or any of its parents don't exist, they will be created. + * + * @param {string} path - The path of the property to set, optionally with a JSON pointer in the hash + * @param {*} value - The value to assign + */ +$Refs$1.prototype.set = function (path, value) { + const absPath = url$6.resolve(this._root$Ref.path, path); + const withoutHash = url$6.stripHash(absPath); + const $ref = this._$refs[withoutHash]; + + if (!$ref) { + throw ono$5(`Error resolving $ref pointer "${path}". \n"${withoutHash}" not found.`); + } + + $ref.set(absPath, value); +}; + +/** + * Creates a new {@link $Ref} object and adds it to this {@link $Refs} object. + * + * @param {string} path - The file path or URL of the referenced file + */ +$Refs$1.prototype._add = function (path) { + const withoutHash = url$6.stripHash(path); + + const $ref = new $Ref$1(); + $ref.path = withoutHash; + $ref.$refs = this; + + this._$refs[withoutHash] = $ref; + this._root$Ref = this._root$Ref || $ref; + + return $ref; +}; + +/** + * Resolves the given JSON reference. + * + * @param {string} path - The path being resolved, optionally with a JSON pointer in the hash + * @param {string} pathFromRoot - The path of `obj` from the schema root + * @param {$RefParserOptions} [options] + * @returns {Pointer} + * @protected + */ +$Refs$1.prototype._resolve = function (path, pathFromRoot, options) { + const absPath = url$6.resolve(this._root$Ref.path, path); + const withoutHash = url$6.stripHash(absPath); + const $ref = this._$refs[withoutHash]; + + if (!$ref) { + throw ono$5(`Error resolving $ref pointer "${path}". \n"${withoutHash}" not found.`); + } + + return $ref.resolve(absPath, options, path, pathFromRoot); +}; + +/** + * Returns the specified {@link $Ref} object, or undefined. + * + * @param {string} path - The path being resolved, optionally with a JSON pointer in the hash + * @returns {$Ref|undefined} + * @protected + */ +$Refs$1.prototype._get$Ref = function (path) { + // eslint-disable-next-line no-param-reassign + path = url$6.resolve(this._root$Ref.path, path); + const withoutHash = url$6.stripHash(path); + return this._$refs[withoutHash]; +}; + +/** + * Returns the encoded and decoded paths keys of the given object. + * + * @param {object} $refs - The object whose keys are URL-encoded paths + * @param {...string|string[]} [types] - Only return paths of the given types ("file", "http", etc.) + * @returns {object[]} + */ +function getPaths($refs, types) { + let paths = Object.keys($refs); + + // Filter the paths by type + // eslint-disable-next-line no-param-reassign + types = Array.isArray(types[0]) ? types[0] : Array.prototype.slice.call(types); + if (types.length > 0 && types[0]) { + paths = paths.filter(key => { + return types.indexOf($refs[key].pathType) !== -1; + }); + } + + // Decode local filesystem paths + return paths.map(path => { + return { + encoded: path, + decoded: $refs[path].pathType === 'file' ? url$6.toFileSystemPath(path, true) : path, + }; + }); +} + +const parse$7 = parse$8; +const Pointer = requirePointer(); +const $Ref = requireRef(); +const { isHandledError: isHandledError$1 } = errors$2; +const url$5 = urlExports; + +var resolveExternal_1 = resolveExternal$2; + +/** + * Crawls the JSON schema, finds all external JSON references, and resolves their values. + * This method does not mutate the JSON schema. The resolved values are added to {@link $RefParser#$refs}. + * + * NOTE: We only care about EXTERNAL references here. INTERNAL references are only relevant when dereferencing. + * + * @param {$RefParser} parser + * @param {$RefParserOptions} options + * + * @returns {Promise} + * The promise resolves once all JSON references in the schema have been resolved, + * including nested references that are contained in externally-referenced files. + */ +function resolveExternal$2(parser, options) { + if (!options.resolve.external) { + // Nothing to resolve, so exit early + return Promise.resolve(); + } + + try { + // console.log('Resolving $ref pointers in %s', parser.$refs._root$Ref.path); + const promises = crawl(parser.schema, `${parser.$refs._root$Ref.path}#`, parser.$refs, options); + return Promise.all(promises); + } catch (e) { + return Promise.reject(e); + } +} + +/** + * Recursively crawls the given value, and resolves any external JSON references. + * + * @param {*} obj - The value to crawl. If it's not an object or array, it will be ignored. + * @param {string} path - The full path of `obj`, possibly with a JSON Pointer in the hash + * @param {$Refs} $refs + * @param {$RefParserOptions} options + * @param {Set} seen - Internal. + * + * @returns {Promise[]} + * Returns an array of promises. There will be one promise for each JSON reference in `obj`. + * If `obj` does not contain any JSON references, then the array will be empty. + * If any of the JSON references point to files that contain additional JSON references, + * then the corresponding promise will internally reference an array of promises. + */ +function crawl(obj, path, $refs, options, seen) { + // eslint-disable-next-line no-param-reassign + seen = seen || new Set(); + let promises = []; + + if (obj && typeof obj === 'object' && !ArrayBuffer.isView(obj) && !seen.has(obj)) { + seen.add(obj); // Track previously seen objects to avoid infinite recursion + if ($Ref.isExternal$Ref(obj)) { + promises.push(resolve$Ref(obj, path, $refs, options)); + } else { + for (const key of Object.keys(obj)) { + const keyPath = Pointer.join(path, key); + const value = obj[key]; + + if ($Ref.isExternal$Ref(value)) { + promises.push(resolve$Ref(value, keyPath, $refs, options)); + } else { + promises = promises.concat(crawl(value, keyPath, $refs, options, seen)); + } + } + } + } + + return promises; +} + +/** + * Resolves the given JSON Reference, and then crawls the resulting value. + * + * @param {{$ref: string}} $ref - The JSON Reference to resolve + * @param {string} path - The full path of `$ref`, possibly with a JSON Pointer in the hash + * @param {$Refs} $refs + * @param {$RefParserOptions} options + * + * @returns {Promise} + * The promise resolves once all JSON references in the object have been resolved, + * including nested references that are contained in externally-referenced files. + */ +async function resolve$Ref($ref, path, $refs, options) { + // console.log('Resolving $ref pointer "%s" at %s', $ref.$ref, path); + + const resolvedPath = url$5.resolve(path, $ref.$ref); + const withoutHash = url$5.stripHash(resolvedPath); + + // Do we already have this $ref? + // eslint-disable-next-line no-param-reassign + $ref = $refs._$refs[withoutHash]; + if ($ref) { + // We've already parsed this $ref, so use the existing value + return Promise.resolve($ref.value); + } + + // Parse the $referenced file/url + try { + const result = await parse$7(resolvedPath, $refs, options); + + // Crawl the parsed value + // console.log('Resolving $ref pointers in %s', withoutHash); + const promises = crawl(result, `${withoutHash}#`, $refs, options); + + return Promise.all(promises); + } catch (err) { + if (!options.continueOnError || !isHandledError$1(err)) { + throw err; + } + + if ($refs._$refs[withoutHash]) { + err.source = url$5.stripHash(path); + err.path = url$5.safePointerToPath(url$5.getHash(path)); + } + + return []; + } +} + +/* eslint-disable prefer-spread */ + +const { ono: ono$4 } = require$$0$3; +const maybe$2 = maybe$3; + +const _bundle = bundle; +const _dereference = dereference$2; +const normalizeArgs$1 = normalizeArgs$2; +const _parse = parse$8; +const $Refs = refs; +const resolveExternal$1 = resolveExternal_1; +const { + JSONParserError, + InvalidPointerError, + MissingPointerError, + ResolverError, + ParserError, + UnmatchedParserError, + UnmatchedResolverError, + isHandledError, + JSONParserErrorGroup, +} = errors$2; +const url$4 = urlExports; + +lib$h.exports = $RefParser$1; +lib$h.exports.default = $RefParser$1; +lib$h.exports.JSONParserError = JSONParserError; +lib$h.exports.InvalidPointerError = InvalidPointerError; +lib$h.exports.MissingPointerError = MissingPointerError; +lib$h.exports.ResolverError = ResolverError; +lib$h.exports.ParserError = ParserError; +lib$h.exports.UnmatchedParserError = UnmatchedParserError; +lib$h.exports.UnmatchedResolverError = UnmatchedResolverError; + +/** + * This class parses a JSON schema, builds a map of its JSON references and their resolved values, + * and provides methods for traversing, manipulating, and dereferencing those references. + * + * @constructor + */ +function $RefParser$1() { + /** + * The parsed (and possibly dereferenced) JSON schema object + * + * @type {object} + * @readonly + */ + this.schema = null; + + /** + * The resolved JSON references + * + * @type {$Refs} + * @readonly + */ + this.$refs = new $Refs(); +} + +/** + * Parses the given JSON schema. + * This method does not resolve any JSON references. + * It just reads a single file in JSON or YAML format, and parse it as a JavaScript object. + * + * @param {string} [path] - The file path or URL of the JSON schema + * @param {object} [schema] - A JSON schema object. This object will be used instead of reading from `path`. + * @param {$RefParserOptions} [options] - Options that determine how the schema is parsed + * @param {function} [callback] - An error-first callback. The second parameter is the parsed JSON schema object. + * @returns {Promise} - The returned promise resolves with the parsed JSON schema object. + */ +$RefParser$1.parse = function parse(path, schema, options, callback) { + const Class = this; + const instance = new Class(); + return instance.parse.apply(instance, arguments); +}; + +/** + * Parses the given JSON schema. + * This method does not resolve any JSON references. + * It just reads a single file in JSON or YAML format, and parse it as a JavaScript object. + * + * @param {string} [path] - The file path or URL of the JSON schema + * @param {object} [schema] - A JSON schema object. This object will be used instead of reading from `path`. + * @param {$RefParserOptions} [options] - Options that determine how the schema is parsed + * @param {function} [callback] - An error-first callback. The second parameter is the parsed JSON schema object. + * @returns {Promise} - The returned promise resolves with the parsed JSON schema object. + */ +$RefParser$1.prototype.parse = async function parse(path, schema, options, callback) { + const args = normalizeArgs$1(arguments); + let promise; + + if (!args.path && !args.schema) { + const err = ono$4(`Expected a file path, URL, or object. Got ${args.path || args.schema}`); + return maybe$2(args.callback, Promise.reject(err)); + } + + // Reset everything + this.schema = null; + this.$refs = new $Refs(); + + // If the path is a filesystem path, then convert it to a URL. + // NOTE: According to the JSON Reference spec, these should already be URLs, + // but, in practice, many people use local filesystem paths instead. + // So we're being generous here and doing the conversion automatically. + // This is not intended to be a 100% bulletproof solution. + // If it doesn't work for your use-case, then use a URL instead. + let pathType = 'http'; + if (url$4.isFileSystemPath(args.path)) { + args.path = url$4.fromFileSystemPath(args.path); + pathType = 'file'; + } + + // Resolve the absolute path of the schema + args.path = url$4.resolve(url$4.cwd(), args.path); + + if (args.schema && typeof args.schema === 'object') { + // A schema object was passed-in. + // So immediately add a new $Ref with the schema object as its value + const $ref = this.$refs._add(args.path); + $ref.value = args.schema; + $ref.pathType = pathType; + promise = Promise.resolve(args.schema); + } else { + // Parse the schema file/url + promise = _parse(args.path, this.$refs, args.options); + } + + const me = this; + try { + const result = await promise; + + if (result !== null && typeof result === 'object' && !Buffer.isBuffer(result)) { + me.schema = result; + return maybe$2(args.callback, Promise.resolve(me.schema)); + } else if (args.options.continueOnError) { + me.schema = null; // it's already set to null at line 79, but let's set it again for the sake of readability + return maybe$2(args.callback, Promise.resolve(me.schema)); + } + + throw ono$4.syntax(`"${me.$refs._root$Ref.path || result}" is not a valid JSON Schema`); + } catch (err) { + if (!args.options.continueOnError || !isHandledError(err)) { + return maybe$2(args.callback, Promise.reject(err)); + } + + if (this.$refs._$refs[url$4.stripHash(args.path)]) { + this.$refs._$refs[url$4.stripHash(args.path)].addError(err); + } + + return maybe$2(args.callback, Promise.resolve(null)); + } +}; + +/** + * Parses the given JSON schema and resolves any JSON references, including references in + * externally-referenced files. + * + * @param {string} [path] - The file path or URL of the JSON schema + * @param {object} [schema] - A JSON schema object. This object will be used instead of reading from `path`. + * @param {$RefParserOptions} [options] - Options that determine how the schema is parsed and resolved + * @param {function} [callback] + * - An error-first callback. The second parameter is a {@link $Refs} object containing the resolved JSON references + * + * @returns {Promise} + * The returned promise resolves with a {@link $Refs} object containing the resolved JSON references + */ +$RefParser$1.resolve = function resolve(path, schema, options, callback) { + const Class = this; + const instance = new Class(); + return instance.resolve.apply(instance, arguments); +}; + +/** + * Parses the given JSON schema and resolves any JSON references, including references in + * externally-referenced files. + * + * @param {string} [path] - The file path or URL of the JSON schema + * @param {object} [schema] - A JSON schema object. This object will be used instead of reading from `path`. + * @param {$RefParserOptions} [options] - Options that determine how the schema is parsed and resolved + * @param {function} [callback] + * - An error-first callback. The second parameter is a {@link $Refs} object containing the resolved JSON references + * + * @returns {Promise} + * The returned promise resolves with a {@link $Refs} object containing the resolved JSON references + */ +$RefParser$1.prototype.resolve = async function resolve(path, schema, options, callback) { + const me = this; + const args = normalizeArgs$1(arguments); + + try { + await this.parse(args.path, args.schema, args.options); + await resolveExternal$1(me, args.options); + finalize(me); + return maybe$2(args.callback, Promise.resolve(me.$refs)); + } catch (err) { + return maybe$2(args.callback, Promise.reject(err)); + } +}; + +/** + * Parses the given JSON schema, resolves any JSON references, and bundles all external references + * into the main JSON schema. This produces a JSON schema that only has *internal* references, + * not any *external* references. + * + * @param {string} [path] - The file path or URL of the JSON schema + * @param {object} [schema] - A JSON schema object. This object will be used instead of reading from `path`. + * @param {$RefParserOptions} [options] - Options that determine how the schema is parsed, resolved, and dereferenced + * @param {function} [callback] - An error-first callback. The second parameter is the bundled JSON schema object + * @returns {Promise} - The returned promise resolves with the bundled JSON schema object. + */ +$RefParser$1.bundle = function bundle(path, schema, options, callback) { + const Class = this; + const instance = new Class(); + return instance.bundle.apply(instance, arguments); +}; + +/** + * Parses the given JSON schema, resolves any JSON references, and bundles all external references + * into the main JSON schema. This produces a JSON schema that only has *internal* references, + * not any *external* references. + * + * @param {string} [path] - The file path or URL of the JSON schema + * @param {object} [schema] - A JSON schema object. This object will be used instead of reading from `path`. + * @param {$RefParserOptions} [options] - Options that determine how the schema is parsed, resolved, and dereferenced + * @param {function} [callback] - An error-first callback. The second parameter is the bundled JSON schema object + * @returns {Promise} - The returned promise resolves with the bundled JSON schema object. + */ +$RefParser$1.prototype.bundle = async function bundle(path, schema, options, callback) { + const me = this; + const args = normalizeArgs$1(arguments); + + try { + await this.resolve(args.path, args.schema, args.options); + _bundle(me, args.options); + finalize(me); + return maybe$2(args.callback, Promise.resolve(me.schema)); + } catch (err) { + return maybe$2(args.callback, Promise.reject(err)); + } +}; + +/** + * Parses the given JSON schema, resolves any JSON references, and dereferences the JSON schema. + * That is, all JSON references are replaced with their resolved values. + * + * @param {string} [path] - The file path or URL of the JSON schema + * @param {object} [schema] - A JSON schema object. This object will be used instead of reading from `path`. + * @param {$RefParserOptions} [options] - Options that determine how the schema is parsed, resolved, and dereferenced + * @param {function} [callback] - An error-first callback. The second parameter is the dereferenced JSON schema object + * @returns {Promise} - The returned promise resolves with the dereferenced JSON schema object. + */ +$RefParser$1.dereference = function dereference(path, schema, options, callback) { + const Class = this; + const instance = new Class(); + return instance.dereference.apply(instance, arguments); +}; + +/** + * Parses the given JSON schema, resolves any JSON references, and dereferences the JSON schema. + * That is, all JSON references are replaced with their resolved values. + * + * @param {string} [path] - The file path or URL of the JSON schema + * @param {object} [schema] - A JSON schema object. This object will be used instead of reading from `path`. + * @param {$RefParserOptions} [options] - Options that determine how the schema is parsed, resolved, and dereferenced + * @param {function} [callback] - An error-first callback. The second parameter is the dereferenced JSON schema object + * @returns {Promise} - The returned promise resolves with the dereferenced JSON schema object. + */ +$RefParser$1.prototype.dereference = async function dereference(path, schema, options, callback) { + const me = this; + const args = normalizeArgs$1(arguments); + + try { + await this.resolve(args.path, args.schema, args.options); + _dereference(me, args.options); + finalize(me); + return maybe$2(args.callback, Promise.resolve(me.schema)); + } catch (err) { + return maybe$2(args.callback, Promise.reject(err)); + } +}; + +function finalize(parser) { + const errors = JSONParserErrorGroup.getParserErrors(parser); + if (errors.length > 0) { + throw new JSONParserErrorGroup(parser); + } +} + +var libExports$2 = lib$h.exports; +var $RefParser$2 = /*@__PURE__*/getDefaultExportFromCjs(libExports$2); + +var util$9 = {}; + +// eslint-disable-next-line unicorn/import-style +const util$8 = require$$0$9; + +const url$3 = urlExports; + +util$9.format = util$8.format; +util$9.inherits = util$8.inherits; + +/** + * Regular Expression that matches Swagger path params. + */ +util$9.swaggerParamRegExp = /\{([^/}]+)}/g; + +/** + * List of HTTP verbs used for OperationItem as per the Swagger specification + */ +const operationsList = ['get', 'post', 'put', 'delete', 'patch', 'options', 'head', 'trace']; + +/** + * This function takes in a Server object, checks if it has relative path + * and then fixes it as per the path url + * + * @param {object} server - The server object to be fixed + * @param {string} path - The path (an http/https url) from where the file was downloaded + * @returns {object} - The fixed server object + */ +function fixServers(server, path) { + // Server url starting with "/" tells that it is not an http(s) url + if (server.url && server.url.startsWith('/')) { + const inUrl = url$3.parse(path); + const finalUrl = `${inUrl.protocol}//${inUrl.hostname}${server.url}`; + server.url = finalUrl; // eslint-disable-line no-param-reassign + } + + return server; +} + +/** + * This function helps fix the relative servers in the API definition file + * be at root, path or operation's level + */ +function fixOasRelativeServers(schema, filePath) { + if (schema.openapi && filePath && (filePath.startsWith('http:') || filePath.startsWith('https:'))) { + /** + * From OpenAPI v3 spec for Server object's url property: "REQUIRED. A URL to the target host. + * This URL supports Server Variables and MAY be relative, to indicate that the host location is relative to the location where + * the OpenAPI document is being served." + * Further, the spec says that "servers" property can show up at root level, in 'Path Item' object or in 'Operation' object. + * However, interpretation of the spec says that relative paths for servers should take into account the hostname that + * serves the OpenAPI file. + */ + if (schema.servers) { + schema.servers.map(server => fixServers(server, filePath)); // Root level servers array's fixup + } + + // Path, Operation, or Webhook level servers array's fixup + ['paths', 'webhooks'].forEach(component => { + Object.keys(schema[component] || []).forEach(path => { + const pathItem = schema[component][path]; + Object.keys(pathItem).forEach(opItem => { + if (opItem === 'servers') { + // servers at pathitem level + pathItem[opItem].map(server => fixServers(server, filePath)); + } else if (operationsList.includes(opItem)) { + // servers at operation level + if (pathItem[opItem].servers) { + pathItem[opItem].servers.map(server => fixServers(server, filePath)); + } + } + }); + }); + }); + } +} + +/** + * Determine the proper name for the API specification schema used by a given schema. + * + * @param {object} schema + * @returns {string} - The name of the specification that this schema utilizes. + */ +function getSpecificationName$1(schema) { + return schema.swagger ? 'Swagger' : 'OpenAPI'; +} + +util$9.fixOasRelativeServers = fixOasRelativeServers; +util$9.getSpecificationName = getSpecificationName$1; + +var lib$g = {exports: {}}; + +var id$4 = "https://raw.githubusercontent.com/OAI/OpenAPI-Specification/master/schemas/v1.2/apiDeclaration.json#"; +var $schema$c = "http://json-schema.org/draft-04/schema#"; +var type$d = "object"; +var required$7 = [ + "swaggerVersion", + "basePath", + "apis" +]; +var properties$f = { + swaggerVersion: { + "enum": [ + "1.2" + ] + }, + apiVersion: { + type: "string" + }, + basePath: { + type: "string", + format: "uri", + pattern: "^https?://" + }, + resourcePath: { + type: "string", + format: "uri", + pattern: "^/" + }, + apis: { + type: "array", + items: { + $ref: "#/definitions/apiObject" + } + }, + models: { + type: "object", + additionalProperties: { + $ref: "modelsObject.json#" + } + }, + produces: { + $ref: "#/definitions/mimeTypeArray" + }, + consumes: { + $ref: "#/definitions/mimeTypeArray" + }, + authorizations: { + $ref: "authorizationObject.json#" + } +}; +var additionalProperties$5 = false; +var definitions$3 = { + apiObject: { + type: "object", + required: [ + "path", + "operations" + ], + properties: { + path: { + type: "string", + format: "uri-template", + pattern: "^/" + }, + description: { + type: "string" + }, + operations: { + type: "array", + items: { + $ref: "operationObject.json#" + } + } + }, + additionalProperties: false + }, + mimeTypeArray: { + type: "array", + items: { + type: "string", + format: "mime-type" + }, + uniqueItems: true + } +}; +var require$$0$2 = { + id: id$4, + $schema: $schema$c, + type: type$d, + required: required$7, + properties: properties$f, + additionalProperties: additionalProperties$5, + definitions: definitions$3 +}; + +var title$8 = "A JSON Schema for Swagger 2.0 API."; +var id$3 = "http://swagger.io/v2/schema.json#"; +var $schema$b = "http://json-schema.org/draft-04/schema#"; +var type$c = "object"; +var required$6 = [ + "swagger", + "info", + "paths" +]; +var additionalProperties$4 = false; +var patternProperties$2 = { + "^x-": { + $ref: "#/definitions/vendorExtension" + } +}; +var properties$e = { + swagger: { + type: "string", + "enum": [ + "2.0" + ], + description: "The Swagger version of this document." + }, + info: { + $ref: "#/definitions/info" + }, + host: { + type: "string", + pattern: "^[^{}/ :\\\\]+(?::\\d+)?$", + description: "The host (name or ip) of the API. Example: 'swagger.io'" + }, + basePath: { + type: "string", + pattern: "^/", + description: "The base path to the API. Example: '/api'." + }, + schemes: { + $ref: "#/definitions/schemesList" + }, + consumes: { + description: "A list of MIME types accepted by the API.", + allOf: [ + { + $ref: "#/definitions/mediaTypeList" + } + ] + }, + produces: { + description: "A list of MIME types the API can produce.", + allOf: [ + { + $ref: "#/definitions/mediaTypeList" + } + ] + }, + paths: { + $ref: "#/definitions/paths" + }, + definitions: { + $ref: "#/definitions/definitions" + }, + parameters: { + $ref: "#/definitions/parameterDefinitions" + }, + responses: { + $ref: "#/definitions/responseDefinitions" + }, + security: { + $ref: "#/definitions/security" + }, + securityDefinitions: { + $ref: "#/definitions/securityDefinitions" + }, + tags: { + type: "array", + items: { + $ref: "#/definitions/tag" + }, + uniqueItems: true + }, + externalDocs: { + $ref: "#/definitions/externalDocs" + } +}; +var definitions$2 = { + info: { + type: "object", + description: "General information about the API.", + required: [ + "version", + "title" + ], + additionalProperties: false, + patternProperties: { + "^x-": { + $ref: "#/definitions/vendorExtension" + } + }, + properties: { + title: { + type: "string", + description: "A unique and precise title of the API." + }, + version: { + type: "string", + description: "A semantic version number of the API." + }, + description: { + type: "string", + description: "A longer description of the API. Should be different from the title. GitHub Flavored Markdown is allowed." + }, + termsOfService: { + type: "string", + description: "The terms of service for the API." + }, + contact: { + $ref: "#/definitions/contact" + }, + license: { + $ref: "#/definitions/license" + } + } + }, + contact: { + type: "object", + description: "Contact information for the owners of the API.", + additionalProperties: false, + properties: { + name: { + type: "string", + description: "The identifying name of the contact person/organization." + }, + url: { + type: "string", + description: "The URL pointing to the contact information.", + format: "uri" + }, + email: { + type: "string", + description: "The email address of the contact person/organization.", + format: "email" + } + }, + patternProperties: { + "^x-": { + $ref: "#/definitions/vendorExtension" + } + } + }, + license: { + type: "object", + required: [ + "name" + ], + additionalProperties: false, + properties: { + name: { + type: "string", + description: "The name of the license type. It's encouraged to use an OSI compatible license." + }, + url: { + type: "string", + description: "The URL pointing to the license.", + format: "uri" + } + }, + patternProperties: { + "^x-": { + $ref: "#/definitions/vendorExtension" + } + } + }, + paths: { + type: "object", + description: "Relative paths to the individual endpoints. They must be relative to the 'basePath'.", + patternProperties: { + "^x-": { + $ref: "#/definitions/vendorExtension" + }, + "^/": { + $ref: "#/definitions/pathItem" + } + }, + additionalProperties: false + }, + definitions: { + type: "object", + additionalProperties: { + $ref: "#/definitions/schema" + }, + description: "One or more JSON objects describing the schemas being consumed and produced by the API." + }, + parameterDefinitions: { + type: "object", + additionalProperties: { + $ref: "#/definitions/parameter" + }, + description: "One or more JSON representations for parameters" + }, + responseDefinitions: { + type: "object", + additionalProperties: { + $ref: "#/definitions/response" + }, + description: "One or more JSON representations for responses" + }, + externalDocs: { + type: "object", + additionalProperties: false, + description: "information about external documentation", + required: [ + "url" + ], + properties: { + description: { + type: "string" + }, + url: { + type: "string", + format: "uri" + } + }, + patternProperties: { + "^x-": { + $ref: "#/definitions/vendorExtension" + } + } + }, + examples: { + type: "object", + additionalProperties: true + }, + mimeType: { + type: "string", + description: "The MIME type of the HTTP message." + }, + operation: { + type: "object", + required: [ + "responses" + ], + additionalProperties: false, + patternProperties: { + "^x-": { + $ref: "#/definitions/vendorExtension" + } + }, + properties: { + tags: { + type: "array", + items: { + type: "string" + }, + uniqueItems: true + }, + summary: { + type: "string", + description: "A brief summary of the operation." + }, + description: { + type: "string", + description: "A longer description of the operation, GitHub Flavored Markdown is allowed." + }, + externalDocs: { + $ref: "#/definitions/externalDocs" + }, + operationId: { + type: "string", + description: "A unique identifier of the operation." + }, + produces: { + description: "A list of MIME types the API can produce.", + allOf: [ + { + $ref: "#/definitions/mediaTypeList" + } + ] + }, + consumes: { + description: "A list of MIME types the API can consume.", + allOf: [ + { + $ref: "#/definitions/mediaTypeList" + } + ] + }, + parameters: { + $ref: "#/definitions/parametersList" + }, + responses: { + $ref: "#/definitions/responses" + }, + schemes: { + $ref: "#/definitions/schemesList" + }, + deprecated: { + type: "boolean", + "default": false + }, + security: { + $ref: "#/definitions/security" + } + } + }, + pathItem: { + type: "object", + additionalProperties: false, + patternProperties: { + "^x-": { + $ref: "#/definitions/vendorExtension" + } + }, + properties: { + $ref: { + type: "string" + }, + get: { + $ref: "#/definitions/operation" + }, + put: { + $ref: "#/definitions/operation" + }, + post: { + $ref: "#/definitions/operation" + }, + "delete": { + $ref: "#/definitions/operation" + }, + options: { + $ref: "#/definitions/operation" + }, + head: { + $ref: "#/definitions/operation" + }, + patch: { + $ref: "#/definitions/operation" + }, + parameters: { + $ref: "#/definitions/parametersList" + } + } + }, + responses: { + type: "object", + description: "Response objects names can either be any valid HTTP status code or 'default'.", + minProperties: 1, + additionalProperties: false, + patternProperties: { + "^([0-9]{3})$|^(default)$": { + $ref: "#/definitions/responseValue" + }, + "^x-": { + $ref: "#/definitions/vendorExtension" + } + }, + not: { + type: "object", + additionalProperties: false, + patternProperties: { + "^x-": { + $ref: "#/definitions/vendorExtension" + } + } + } + }, + responseValue: { + oneOf: [ + { + $ref: "#/definitions/response" + }, + { + $ref: "#/definitions/jsonReference" + } + ] + }, + response: { + type: "object", + required: [ + "description" + ], + properties: { + description: { + type: "string" + }, + schema: { + oneOf: [ + { + $ref: "#/definitions/schema" + }, + { + $ref: "#/definitions/fileSchema" + } + ] + }, + headers: { + $ref: "#/definitions/headers" + }, + examples: { + $ref: "#/definitions/examples" + } + }, + additionalProperties: false, + patternProperties: { + "^x-": { + $ref: "#/definitions/vendorExtension" + } + } + }, + headers: { + type: "object", + additionalProperties: { + $ref: "#/definitions/header" + } + }, + header: { + type: "object", + additionalProperties: false, + required: [ + "type" + ], + properties: { + type: { + type: "string", + "enum": [ + "string", + "number", + "integer", + "boolean", + "array" + ] + }, + format: { + type: "string" + }, + items: { + $ref: "#/definitions/primitivesItems" + }, + collectionFormat: { + $ref: "#/definitions/collectionFormat" + }, + "default": { + $ref: "#/definitions/default" + }, + maximum: { + $ref: "#/definitions/maximum" + }, + exclusiveMaximum: { + $ref: "#/definitions/exclusiveMaximum" + }, + minimum: { + $ref: "#/definitions/minimum" + }, + exclusiveMinimum: { + $ref: "#/definitions/exclusiveMinimum" + }, + maxLength: { + $ref: "#/definitions/maxLength" + }, + minLength: { + $ref: "#/definitions/minLength" + }, + pattern: { + $ref: "#/definitions/pattern" + }, + maxItems: { + $ref: "#/definitions/maxItems" + }, + minItems: { + $ref: "#/definitions/minItems" + }, + uniqueItems: { + $ref: "#/definitions/uniqueItems" + }, + "enum": { + $ref: "#/definitions/enum" + }, + multipleOf: { + $ref: "#/definitions/multipleOf" + }, + description: { + type: "string" + } + }, + patternProperties: { + "^x-": { + $ref: "#/definitions/vendorExtension" + } + } + }, + vendorExtension: { + description: "Any property starting with x- is valid.", + additionalProperties: true, + additionalItems: true + }, + bodyParameter: { + type: "object", + required: [ + "name", + "in", + "schema" + ], + patternProperties: { + "^x-": { + $ref: "#/definitions/vendorExtension" + } + }, + properties: { + description: { + type: "string", + description: "A brief description of the parameter. This could contain examples of use. GitHub Flavored Markdown is allowed." + }, + name: { + type: "string", + description: "The name of the parameter." + }, + "in": { + type: "string", + description: "Determines the location of the parameter.", + "enum": [ + "body" + ] + }, + required: { + type: "boolean", + description: "Determines whether or not this parameter is required or optional.", + "default": false + }, + schema: { + $ref: "#/definitions/schema" + } + }, + additionalProperties: false + }, + headerParameterSubSchema: { + additionalProperties: false, + patternProperties: { + "^x-": { + $ref: "#/definitions/vendorExtension" + } + }, + properties: { + required: { + type: "boolean", + description: "Determines whether or not this parameter is required or optional.", + "default": false + }, + "in": { + type: "string", + description: "Determines the location of the parameter.", + "enum": [ + "header" + ] + }, + description: { + type: "string", + description: "A brief description of the parameter. This could contain examples of use. GitHub Flavored Markdown is allowed." + }, + name: { + type: "string", + description: "The name of the parameter." + }, + type: { + type: "string", + "enum": [ + "string", + "number", + "boolean", + "integer", + "array" + ] + }, + format: { + type: "string" + }, + items: { + $ref: "#/definitions/primitivesItems" + }, + collectionFormat: { + $ref: "#/definitions/collectionFormat" + }, + "default": { + $ref: "#/definitions/default" + }, + maximum: { + $ref: "#/definitions/maximum" + }, + exclusiveMaximum: { + $ref: "#/definitions/exclusiveMaximum" + }, + minimum: { + $ref: "#/definitions/minimum" + }, + exclusiveMinimum: { + $ref: "#/definitions/exclusiveMinimum" + }, + maxLength: { + $ref: "#/definitions/maxLength" + }, + minLength: { + $ref: "#/definitions/minLength" + }, + pattern: { + $ref: "#/definitions/pattern" + }, + maxItems: { + $ref: "#/definitions/maxItems" + }, + minItems: { + $ref: "#/definitions/minItems" + }, + uniqueItems: { + $ref: "#/definitions/uniqueItems" + }, + "enum": { + $ref: "#/definitions/enum" + }, + multipleOf: { + $ref: "#/definitions/multipleOf" + } + } + }, + queryParameterSubSchema: { + additionalProperties: false, + patternProperties: { + "^x-": { + $ref: "#/definitions/vendorExtension" + } + }, + properties: { + required: { + type: "boolean", + description: "Determines whether or not this parameter is required or optional.", + "default": false + }, + "in": { + type: "string", + description: "Determines the location of the parameter.", + "enum": [ + "query" + ] + }, + description: { + type: "string", + description: "A brief description of the parameter. This could contain examples of use. GitHub Flavored Markdown is allowed." + }, + name: { + type: "string", + description: "The name of the parameter." + }, + allowEmptyValue: { + type: "boolean", + "default": false, + description: "allows sending a parameter by name only or with an empty value." + }, + type: { + type: "string", + "enum": [ + "string", + "number", + "boolean", + "integer", + "array" + ] + }, + format: { + type: "string" + }, + items: { + $ref: "#/definitions/primitivesItems" + }, + collectionFormat: { + $ref: "#/definitions/collectionFormatWithMulti" + }, + "default": { + $ref: "#/definitions/default" + }, + maximum: { + $ref: "#/definitions/maximum" + }, + exclusiveMaximum: { + $ref: "#/definitions/exclusiveMaximum" + }, + minimum: { + $ref: "#/definitions/minimum" + }, + exclusiveMinimum: { + $ref: "#/definitions/exclusiveMinimum" + }, + maxLength: { + $ref: "#/definitions/maxLength" + }, + minLength: { + $ref: "#/definitions/minLength" + }, + pattern: { + $ref: "#/definitions/pattern" + }, + maxItems: { + $ref: "#/definitions/maxItems" + }, + minItems: { + $ref: "#/definitions/minItems" + }, + uniqueItems: { + $ref: "#/definitions/uniqueItems" + }, + "enum": { + $ref: "#/definitions/enum" + }, + multipleOf: { + $ref: "#/definitions/multipleOf" + } + } + }, + formDataParameterSubSchema: { + additionalProperties: false, + patternProperties: { + "^x-": { + $ref: "#/definitions/vendorExtension" + } + }, + properties: { + required: { + type: "boolean", + description: "Determines whether or not this parameter is required or optional.", + "default": false + }, + "in": { + type: "string", + description: "Determines the location of the parameter.", + "enum": [ + "formData" + ] + }, + description: { + type: "string", + description: "A brief description of the parameter. This could contain examples of use. GitHub Flavored Markdown is allowed." + }, + name: { + type: "string", + description: "The name of the parameter." + }, + allowEmptyValue: { + type: "boolean", + "default": false, + description: "allows sending a parameter by name only or with an empty value." + }, + type: { + type: "string", + "enum": [ + "string", + "number", + "boolean", + "integer", + "array", + "file" + ] + }, + format: { + type: "string" + }, + items: { + $ref: "#/definitions/primitivesItems" + }, + collectionFormat: { + $ref: "#/definitions/collectionFormatWithMulti" + }, + "default": { + $ref: "#/definitions/default" + }, + maximum: { + $ref: "#/definitions/maximum" + }, + exclusiveMaximum: { + $ref: "#/definitions/exclusiveMaximum" + }, + minimum: { + $ref: "#/definitions/minimum" + }, + exclusiveMinimum: { + $ref: "#/definitions/exclusiveMinimum" + }, + maxLength: { + $ref: "#/definitions/maxLength" + }, + minLength: { + $ref: "#/definitions/minLength" + }, + pattern: { + $ref: "#/definitions/pattern" + }, + maxItems: { + $ref: "#/definitions/maxItems" + }, + minItems: { + $ref: "#/definitions/minItems" + }, + uniqueItems: { + $ref: "#/definitions/uniqueItems" + }, + "enum": { + $ref: "#/definitions/enum" + }, + multipleOf: { + $ref: "#/definitions/multipleOf" + } + } + }, + pathParameterSubSchema: { + additionalProperties: false, + patternProperties: { + "^x-": { + $ref: "#/definitions/vendorExtension" + } + }, + required: [ + "required" + ], + properties: { + required: { + type: "boolean", + "enum": [ + true + ], + description: "Determines whether or not this parameter is required or optional." + }, + "in": { + type: "string", + description: "Determines the location of the parameter.", + "enum": [ + "path" + ] + }, + description: { + type: "string", + description: "A brief description of the parameter. This could contain examples of use. GitHub Flavored Markdown is allowed." + }, + name: { + type: "string", + description: "The name of the parameter." + }, + type: { + type: "string", + "enum": [ + "string", + "number", + "boolean", + "integer", + "array" + ] + }, + format: { + type: "string" + }, + items: { + $ref: "#/definitions/primitivesItems" + }, + collectionFormat: { + $ref: "#/definitions/collectionFormat" + }, + "default": { + $ref: "#/definitions/default" + }, + maximum: { + $ref: "#/definitions/maximum" + }, + exclusiveMaximum: { + $ref: "#/definitions/exclusiveMaximum" + }, + minimum: { + $ref: "#/definitions/minimum" + }, + exclusiveMinimum: { + $ref: "#/definitions/exclusiveMinimum" + }, + maxLength: { + $ref: "#/definitions/maxLength" + }, + minLength: { + $ref: "#/definitions/minLength" + }, + pattern: { + $ref: "#/definitions/pattern" + }, + maxItems: { + $ref: "#/definitions/maxItems" + }, + minItems: { + $ref: "#/definitions/minItems" + }, + uniqueItems: { + $ref: "#/definitions/uniqueItems" + }, + "enum": { + $ref: "#/definitions/enum" + }, + multipleOf: { + $ref: "#/definitions/multipleOf" + } + } + }, + nonBodyParameter: { + type: "object", + required: [ + "name", + "in", + "type" + ], + oneOf: [ + { + $ref: "#/definitions/headerParameterSubSchema" + }, + { + $ref: "#/definitions/formDataParameterSubSchema" + }, + { + $ref: "#/definitions/queryParameterSubSchema" + }, + { + $ref: "#/definitions/pathParameterSubSchema" + } + ] + }, + parameter: { + oneOf: [ + { + $ref: "#/definitions/bodyParameter" + }, + { + $ref: "#/definitions/nonBodyParameter" + } + ] + }, + schema: { + type: "object", + description: "A deterministic version of a JSON Schema object.", + patternProperties: { + "^x-": { + $ref: "#/definitions/vendorExtension" + } + }, + properties: { + $ref: { + type: "string" + }, + format: { + type: "string" + }, + title: { + $ref: "http://json-schema.org/draft-04/schema#/properties/title" + }, + description: { + $ref: "http://json-schema.org/draft-04/schema#/properties/description" + }, + "default": { + $ref: "http://json-schema.org/draft-04/schema#/properties/default" + }, + multipleOf: { + $ref: "http://json-schema.org/draft-04/schema#/properties/multipleOf" + }, + maximum: { + $ref: "http://json-schema.org/draft-04/schema#/properties/maximum" + }, + exclusiveMaximum: { + $ref: "http://json-schema.org/draft-04/schema#/properties/exclusiveMaximum" + }, + minimum: { + $ref: "http://json-schema.org/draft-04/schema#/properties/minimum" + }, + exclusiveMinimum: { + $ref: "http://json-schema.org/draft-04/schema#/properties/exclusiveMinimum" + }, + maxLength: { + $ref: "http://json-schema.org/draft-04/schema#/definitions/positiveInteger" + }, + minLength: { + $ref: "http://json-schema.org/draft-04/schema#/definitions/positiveIntegerDefault0" + }, + pattern: { + $ref: "http://json-schema.org/draft-04/schema#/properties/pattern" + }, + maxItems: { + $ref: "http://json-schema.org/draft-04/schema#/definitions/positiveInteger" + }, + minItems: { + $ref: "http://json-schema.org/draft-04/schema#/definitions/positiveIntegerDefault0" + }, + uniqueItems: { + $ref: "http://json-schema.org/draft-04/schema#/properties/uniqueItems" + }, + maxProperties: { + $ref: "http://json-schema.org/draft-04/schema#/definitions/positiveInteger" + }, + minProperties: { + $ref: "http://json-schema.org/draft-04/schema#/definitions/positiveIntegerDefault0" + }, + required: { + $ref: "http://json-schema.org/draft-04/schema#/definitions/stringArray" + }, + "enum": { + $ref: "http://json-schema.org/draft-04/schema#/properties/enum" + }, + additionalProperties: { + anyOf: [ + { + $ref: "#/definitions/schema" + }, + { + type: "boolean" + } + ], + "default": { + } + }, + type: { + $ref: "http://json-schema.org/draft-04/schema#/properties/type" + }, + items: { + anyOf: [ + { + $ref: "#/definitions/schema" + }, + { + type: "array", + minItems: 1, + items: { + $ref: "#/definitions/schema" + } + } + ], + "default": { + } + }, + allOf: { + type: "array", + minItems: 1, + items: { + $ref: "#/definitions/schema" + } + }, + properties: { + type: "object", + additionalProperties: { + $ref: "#/definitions/schema" + }, + "default": { + } + }, + discriminator: { + type: "string" + }, + readOnly: { + type: "boolean", + "default": false + }, + xml: { + $ref: "#/definitions/xml" + }, + externalDocs: { + $ref: "#/definitions/externalDocs" + }, + example: { + } + }, + additionalProperties: false + }, + fileSchema: { + type: "object", + description: "A deterministic version of a JSON Schema object.", + patternProperties: { + "^x-": { + $ref: "#/definitions/vendorExtension" + } + }, + required: [ + "type" + ], + properties: { + format: { + type: "string" + }, + title: { + $ref: "http://json-schema.org/draft-04/schema#/properties/title" + }, + description: { + $ref: "http://json-schema.org/draft-04/schema#/properties/description" + }, + "default": { + $ref: "http://json-schema.org/draft-04/schema#/properties/default" + }, + required: { + $ref: "http://json-schema.org/draft-04/schema#/definitions/stringArray" + }, + type: { + type: "string", + "enum": [ + "file" + ] + }, + readOnly: { + type: "boolean", + "default": false + }, + externalDocs: { + $ref: "#/definitions/externalDocs" + }, + example: { + } + }, + additionalProperties: false + }, + primitivesItems: { + type: "object", + additionalProperties: false, + properties: { + type: { + type: "string", + "enum": [ + "string", + "number", + "integer", + "boolean", + "array" + ] + }, + format: { + type: "string" + }, + items: { + $ref: "#/definitions/primitivesItems" + }, + collectionFormat: { + $ref: "#/definitions/collectionFormat" + }, + "default": { + $ref: "#/definitions/default" + }, + maximum: { + $ref: "#/definitions/maximum" + }, + exclusiveMaximum: { + $ref: "#/definitions/exclusiveMaximum" + }, + minimum: { + $ref: "#/definitions/minimum" + }, + exclusiveMinimum: { + $ref: "#/definitions/exclusiveMinimum" + }, + maxLength: { + $ref: "#/definitions/maxLength" + }, + minLength: { + $ref: "#/definitions/minLength" + }, + pattern: { + $ref: "#/definitions/pattern" + }, + maxItems: { + $ref: "#/definitions/maxItems" + }, + minItems: { + $ref: "#/definitions/minItems" + }, + uniqueItems: { + $ref: "#/definitions/uniqueItems" + }, + "enum": { + $ref: "#/definitions/enum" + }, + multipleOf: { + $ref: "#/definitions/multipleOf" + } + }, + patternProperties: { + "^x-": { + $ref: "#/definitions/vendorExtension" + } + } + }, + security: { + type: "array", + items: { + $ref: "#/definitions/securityRequirement" + }, + uniqueItems: true + }, + securityRequirement: { + type: "object", + additionalProperties: { + type: "array", + items: { + type: "string" + }, + uniqueItems: true + } + }, + xml: { + type: "object", + additionalProperties: false, + properties: { + name: { + type: "string" + }, + namespace: { + type: "string" + }, + prefix: { + type: "string" + }, + attribute: { + type: "boolean", + "default": false + }, + wrapped: { + type: "boolean", + "default": false + } + }, + patternProperties: { + "^x-": { + $ref: "#/definitions/vendorExtension" + } + } + }, + tag: { + type: "object", + additionalProperties: false, + required: [ + "name" + ], + properties: { + name: { + type: "string" + }, + description: { + type: "string" + }, + externalDocs: { + $ref: "#/definitions/externalDocs" + } + }, + patternProperties: { + "^x-": { + $ref: "#/definitions/vendorExtension" + } + } + }, + securityDefinitions: { + type: "object", + additionalProperties: { + oneOf: [ + { + $ref: "#/definitions/basicAuthenticationSecurity" + }, + { + $ref: "#/definitions/apiKeySecurity" + }, + { + $ref: "#/definitions/oauth2ImplicitSecurity" + }, + { + $ref: "#/definitions/oauth2PasswordSecurity" + }, + { + $ref: "#/definitions/oauth2ApplicationSecurity" + }, + { + $ref: "#/definitions/oauth2AccessCodeSecurity" + } + ] + } + }, + basicAuthenticationSecurity: { + type: "object", + additionalProperties: false, + required: [ + "type" + ], + properties: { + type: { + type: "string", + "enum": [ + "basic" + ] + }, + description: { + type: "string" + } + }, + patternProperties: { + "^x-": { + $ref: "#/definitions/vendorExtension" + } + } + }, + apiKeySecurity: { + type: "object", + additionalProperties: false, + required: [ + "type", + "name", + "in" + ], + properties: { + type: { + type: "string", + "enum": [ + "apiKey" + ] + }, + name: { + type: "string" + }, + "in": { + type: "string", + "enum": [ + "header", + "query" + ] + }, + description: { + type: "string" + } + }, + patternProperties: { + "^x-": { + $ref: "#/definitions/vendorExtension" + } + } + }, + oauth2ImplicitSecurity: { + type: "object", + additionalProperties: false, + required: [ + "type", + "flow", + "authorizationUrl" + ], + properties: { + type: { + type: "string", + "enum": [ + "oauth2" + ] + }, + flow: { + type: "string", + "enum": [ + "implicit" + ] + }, + scopes: { + $ref: "#/definitions/oauth2Scopes" + }, + authorizationUrl: { + type: "string", + format: "uri" + }, + description: { + type: "string" + } + }, + patternProperties: { + "^x-": { + $ref: "#/definitions/vendorExtension" + } + } + }, + oauth2PasswordSecurity: { + type: "object", + additionalProperties: false, + required: [ + "type", + "flow", + "tokenUrl" + ], + properties: { + type: { + type: "string", + "enum": [ + "oauth2" + ] + }, + flow: { + type: "string", + "enum": [ + "password" + ] + }, + scopes: { + $ref: "#/definitions/oauth2Scopes" + }, + tokenUrl: { + type: "string", + format: "uri" + }, + description: { + type: "string" + } + }, + patternProperties: { + "^x-": { + $ref: "#/definitions/vendorExtension" + } + } + }, + oauth2ApplicationSecurity: { + type: "object", + additionalProperties: false, + required: [ + "type", + "flow", + "tokenUrl" + ], + properties: { + type: { + type: "string", + "enum": [ + "oauth2" + ] + }, + flow: { + type: "string", + "enum": [ + "application" + ] + }, + scopes: { + $ref: "#/definitions/oauth2Scopes" + }, + tokenUrl: { + type: "string", + format: "uri" + }, + description: { + type: "string" + } + }, + patternProperties: { + "^x-": { + $ref: "#/definitions/vendorExtension" + } + } + }, + oauth2AccessCodeSecurity: { + type: "object", + additionalProperties: false, + required: [ + "type", + "flow", + "authorizationUrl", + "tokenUrl" + ], + properties: { + type: { + type: "string", + "enum": [ + "oauth2" + ] + }, + flow: { + type: "string", + "enum": [ + "accessCode" + ] + }, + scopes: { + $ref: "#/definitions/oauth2Scopes" + }, + authorizationUrl: { + type: "string", + format: "uri" + }, + tokenUrl: { + type: "string", + format: "uri" + }, + description: { + type: "string" + } + }, + patternProperties: { + "^x-": { + $ref: "#/definitions/vendorExtension" + } + } + }, + oauth2Scopes: { + type: "object", + additionalProperties: { + type: "string" + } + }, + mediaTypeList: { + type: "array", + items: { + $ref: "#/definitions/mimeType" + }, + uniqueItems: true + }, + parametersList: { + type: "array", + description: "The parameters needed to send a valid API call.", + additionalItems: false, + items: { + oneOf: [ + { + $ref: "#/definitions/parameter" + }, + { + $ref: "#/definitions/jsonReference" + } + ] + }, + uniqueItems: true + }, + schemesList: { + type: "array", + description: "The transfer protocol of the API.", + items: { + type: "string", + "enum": [ + "http", + "https", + "ws", + "wss" + ] + }, + uniqueItems: true + }, + collectionFormat: { + type: "string", + "enum": [ + "csv", + "ssv", + "tsv", + "pipes" + ], + "default": "csv" + }, + collectionFormatWithMulti: { + type: "string", + "enum": [ + "csv", + "ssv", + "tsv", + "pipes", + "multi" + ], + "default": "csv" + }, + title: { + $ref: "http://json-schema.org/draft-04/schema#/properties/title" + }, + description: { + $ref: "http://json-schema.org/draft-04/schema#/properties/description" + }, + "default": { + $ref: "http://json-schema.org/draft-04/schema#/properties/default" + }, + multipleOf: { + $ref: "http://json-schema.org/draft-04/schema#/properties/multipleOf" + }, + maximum: { + $ref: "http://json-schema.org/draft-04/schema#/properties/maximum" + }, + exclusiveMaximum: { + $ref: "http://json-schema.org/draft-04/schema#/properties/exclusiveMaximum" + }, + minimum: { + $ref: "http://json-schema.org/draft-04/schema#/properties/minimum" + }, + exclusiveMinimum: { + $ref: "http://json-schema.org/draft-04/schema#/properties/exclusiveMinimum" + }, + maxLength: { + $ref: "http://json-schema.org/draft-04/schema#/definitions/positiveInteger" + }, + minLength: { + $ref: "http://json-schema.org/draft-04/schema#/definitions/positiveIntegerDefault0" + }, + pattern: { + $ref: "http://json-schema.org/draft-04/schema#/properties/pattern" + }, + maxItems: { + $ref: "http://json-schema.org/draft-04/schema#/definitions/positiveInteger" + }, + minItems: { + $ref: "http://json-schema.org/draft-04/schema#/definitions/positiveIntegerDefault0" + }, + uniqueItems: { + $ref: "http://json-schema.org/draft-04/schema#/properties/uniqueItems" + }, + "enum": { + $ref: "http://json-schema.org/draft-04/schema#/properties/enum" + }, + jsonReference: { + type: "object", + required: [ + "$ref" + ], + additionalProperties: false, + properties: { + $ref: { + type: "string" + } + } + } +}; +var require$$1$2 = { + title: title$8, + id: id$3, + $schema: $schema$b, + type: type$c, + required: required$6, + additionalProperties: additionalProperties$4, + patternProperties: patternProperties$2, + properties: properties$e, + definitions: definitions$2 +}; + +var id$2 = "https://spec.openapis.org/oas/3.0/schema/2019-04-02"; +var $schema$a = "http://json-schema.org/draft-04/schema#"; +var description$3 = "Validation schema for OpenAPI Specification 3.0.X."; +var type$b = "object"; +var required$5 = [ + "openapi", + "info", + "paths" +]; +var properties$d = { + openapi: { + type: "string", + pattern: "^3\\.0\\.\\d(-.+)?$" + }, + info: { + $ref: "#/definitions/Info" + }, + externalDocs: { + $ref: "#/definitions/ExternalDocumentation" + }, + servers: { + type: "array", + items: { + $ref: "#/definitions/Server" + } + }, + security: { + type: "array", + items: { + $ref: "#/definitions/SecurityRequirement" + } + }, + tags: { + type: "array", + items: { + $ref: "#/definitions/Tag" + }, + uniqueItems: true + }, + paths: { + $ref: "#/definitions/Paths" + }, + components: { + $ref: "#/definitions/Components" + } +}; +var patternProperties$1 = { + "^x-": { + } +}; +var additionalProperties$3 = false; +var definitions$1 = { + Reference: { + type: "object", + required: [ + "$ref" + ], + patternProperties: { + "^\\$ref$": { + type: "string", + format: "uri-reference" + } + } + }, + Info: { + type: "object", + required: [ + "title", + "version" + ], + properties: { + title: { + type: "string" + }, + description: { + type: "string" + }, + termsOfService: { + type: "string", + format: "uri-reference" + }, + contact: { + $ref: "#/definitions/Contact" + }, + license: { + $ref: "#/definitions/License" + }, + version: { + type: "string" + } + }, + patternProperties: { + "^x-": { + } + }, + additionalProperties: false + }, + Contact: { + type: "object", + properties: { + name: { + type: "string" + }, + url: { + type: "string", + format: "uri-reference" + }, + email: { + type: "string", + format: "email" + } + }, + patternProperties: { + "^x-": { + } + }, + additionalProperties: false + }, + License: { + type: "object", + required: [ + "name" + ], + properties: { + name: { + type: "string" + }, + url: { + type: "string", + format: "uri-reference" + } + }, + patternProperties: { + "^x-": { + } + }, + additionalProperties: false + }, + Server: { + type: "object", + required: [ + "url" + ], + properties: { + url: { + type: "string" + }, + description: { + type: "string" + }, + variables: { + type: "object", + additionalProperties: { + $ref: "#/definitions/ServerVariable" + } + } + }, + patternProperties: { + "^x-": { + } + }, + additionalProperties: false + }, + ServerVariable: { + type: "object", + required: [ + "default" + ], + properties: { + "enum": { + type: "array", + items: { + type: "string" + } + }, + "default": { + type: "string" + }, + description: { + type: "string" + } + }, + patternProperties: { + "^x-": { + } + }, + additionalProperties: false + }, + Components: { + type: "object", + properties: { + schemas: { + type: "object", + patternProperties: { + "^[a-zA-Z0-9\\.\\-_]+$": { + oneOf: [ + { + $ref: "#/definitions/Schema" + }, + { + $ref: "#/definitions/Reference" + } + ] + } + } + }, + responses: { + type: "object", + patternProperties: { + "^[a-zA-Z0-9\\.\\-_]+$": { + oneOf: [ + { + $ref: "#/definitions/Reference" + }, + { + $ref: "#/definitions/Response" + } + ] + } + } + }, + parameters: { + type: "object", + patternProperties: { + "^[a-zA-Z0-9\\.\\-_]+$": { + oneOf: [ + { + $ref: "#/definitions/Reference" + }, + { + $ref: "#/definitions/Parameter" + } + ] + } + } + }, + examples: { + type: "object", + patternProperties: { + "^[a-zA-Z0-9\\.\\-_]+$": { + oneOf: [ + { + $ref: "#/definitions/Reference" + }, + { + $ref: "#/definitions/Example" + } + ] + } + } + }, + requestBodies: { + type: "object", + patternProperties: { + "^[a-zA-Z0-9\\.\\-_]+$": { + oneOf: [ + { + $ref: "#/definitions/Reference" + }, + { + $ref: "#/definitions/RequestBody" + } + ] + } + } + }, + headers: { + type: "object", + patternProperties: { + "^[a-zA-Z0-9\\.\\-_]+$": { + oneOf: [ + { + $ref: "#/definitions/Reference" + }, + { + $ref: "#/definitions/Header" + } + ] + } + } + }, + securitySchemes: { + type: "object", + patternProperties: { + "^[a-zA-Z0-9\\.\\-_]+$": { + oneOf: [ + { + $ref: "#/definitions/Reference" + }, + { + $ref: "#/definitions/SecurityScheme" + } + ] + } + } + }, + links: { + type: "object", + patternProperties: { + "^[a-zA-Z0-9\\.\\-_]+$": { + oneOf: [ + { + $ref: "#/definitions/Reference" + }, + { + $ref: "#/definitions/Link" + } + ] + } + } + }, + callbacks: { + type: "object", + patternProperties: { + "^[a-zA-Z0-9\\.\\-_]+$": { + oneOf: [ + { + $ref: "#/definitions/Reference" + }, + { + $ref: "#/definitions/Callback" + } + ] + } + } + } + }, + patternProperties: { + "^x-": { + } + }, + additionalProperties: false + }, + Schema: { + type: "object", + properties: { + title: { + type: "string" + }, + multipleOf: { + type: "number", + minimum: 0, + exclusiveMinimum: true + }, + maximum: { + type: "number" + }, + exclusiveMaximum: { + type: "boolean", + "default": false + }, + minimum: { + type: "number" + }, + exclusiveMinimum: { + type: "boolean", + "default": false + }, + maxLength: { + type: "integer", + minimum: 0 + }, + minLength: { + type: "integer", + minimum: 0, + "default": 0 + }, + pattern: { + type: "string", + format: "regex" + }, + maxItems: { + type: "integer", + minimum: 0 + }, + minItems: { + type: "integer", + minimum: 0, + "default": 0 + }, + uniqueItems: { + type: "boolean", + "default": false + }, + maxProperties: { + type: "integer", + minimum: 0 + }, + minProperties: { + type: "integer", + minimum: 0, + "default": 0 + }, + required: { + type: "array", + items: { + type: "string" + }, + minItems: 1, + uniqueItems: true + }, + "enum": { + type: "array", + items: { + }, + minItems: 1, + uniqueItems: false + }, + type: { + type: "string", + "enum": [ + "array", + "boolean", + "integer", + "number", + "object", + "string" + ] + }, + not: { + oneOf: [ + { + $ref: "#/definitions/Schema" + }, + { + $ref: "#/definitions/Reference" + } + ] + }, + allOf: { + type: "array", + items: { + oneOf: [ + { + $ref: "#/definitions/Schema" + }, + { + $ref: "#/definitions/Reference" + } + ] + } + }, + oneOf: { + type: "array", + items: { + oneOf: [ + { + $ref: "#/definitions/Schema" + }, + { + $ref: "#/definitions/Reference" + } + ] + } + }, + anyOf: { + type: "array", + items: { + oneOf: [ + { + $ref: "#/definitions/Schema" + }, + { + $ref: "#/definitions/Reference" + } + ] + } + }, + items: { + oneOf: [ + { + $ref: "#/definitions/Schema" + }, + { + $ref: "#/definitions/Reference" + } + ] + }, + properties: { + type: "object", + additionalProperties: { + oneOf: [ + { + $ref: "#/definitions/Schema" + }, + { + $ref: "#/definitions/Reference" + } + ] + } + }, + additionalProperties: { + oneOf: [ + { + $ref: "#/definitions/Schema" + }, + { + $ref: "#/definitions/Reference" + }, + { + type: "boolean" + } + ], + "default": true + }, + description: { + type: "string" + }, + format: { + type: "string" + }, + "default": { + }, + nullable: { + type: "boolean", + "default": false + }, + discriminator: { + $ref: "#/definitions/Discriminator" + }, + readOnly: { + type: "boolean", + "default": false + }, + writeOnly: { + type: "boolean", + "default": false + }, + example: { + }, + externalDocs: { + $ref: "#/definitions/ExternalDocumentation" + }, + deprecated: { + type: "boolean", + "default": false + }, + xml: { + $ref: "#/definitions/XML" + } + }, + patternProperties: { + "^x-": { + } + }, + additionalProperties: false + }, + Discriminator: { + type: "object", + required: [ + "propertyName" + ], + properties: { + propertyName: { + type: "string" + }, + mapping: { + type: "object", + additionalProperties: { + type: "string" + } + } + } + }, + XML: { + type: "object", + properties: { + name: { + type: "string" + }, + namespace: { + type: "string", + format: "uri" + }, + prefix: { + type: "string" + }, + attribute: { + type: "boolean", + "default": false + }, + wrapped: { + type: "boolean", + "default": false + } + }, + patternProperties: { + "^x-": { + } + }, + additionalProperties: false + }, + Response: { + type: "object", + required: [ + "description" + ], + properties: { + description: { + type: "string" + }, + headers: { + type: "object", + additionalProperties: { + oneOf: [ + { + $ref: "#/definitions/Header" + }, + { + $ref: "#/definitions/Reference" + } + ] + } + }, + content: { + type: "object", + additionalProperties: { + $ref: "#/definitions/MediaType" + } + }, + links: { + type: "object", + additionalProperties: { + oneOf: [ + { + $ref: "#/definitions/Link" + }, + { + $ref: "#/definitions/Reference" + } + ] + } + } + }, + patternProperties: { + "^x-": { + } + }, + additionalProperties: false + }, + MediaType: { + type: "object", + properties: { + schema: { + oneOf: [ + { + $ref: "#/definitions/Schema" + }, + { + $ref: "#/definitions/Reference" + } + ] + }, + example: { + }, + examples: { + type: "object", + additionalProperties: { + oneOf: [ + { + $ref: "#/definitions/Example" + }, + { + $ref: "#/definitions/Reference" + } + ] + } + }, + encoding: { + type: "object", + additionalProperties: { + $ref: "#/definitions/Encoding" + } + } + }, + patternProperties: { + "^x-": { + } + }, + additionalProperties: false, + allOf: [ + { + $ref: "#/definitions/ExampleXORExamples" + } + ] + }, + Example: { + type: "object", + properties: { + summary: { + type: "string" + }, + description: { + type: "string" + }, + value: { + }, + externalValue: { + type: "string", + format: "uri-reference" + } + }, + patternProperties: { + "^x-": { + } + }, + additionalProperties: false + }, + Header: { + type: "object", + properties: { + description: { + type: "string" + }, + required: { + type: "boolean", + "default": false + }, + deprecated: { + type: "boolean", + "default": false + }, + allowEmptyValue: { + type: "boolean", + "default": false + }, + style: { + type: "string", + "enum": [ + "simple" + ], + "default": "simple" + }, + explode: { + type: "boolean" + }, + allowReserved: { + type: "boolean", + "default": false + }, + schema: { + oneOf: [ + { + $ref: "#/definitions/Schema" + }, + { + $ref: "#/definitions/Reference" + } + ] + }, + content: { + type: "object", + additionalProperties: { + $ref: "#/definitions/MediaType" + }, + minProperties: 1, + maxProperties: 1 + }, + example: { + }, + examples: { + type: "object", + additionalProperties: { + oneOf: [ + { + $ref: "#/definitions/Example" + }, + { + $ref: "#/definitions/Reference" + } + ] + } + } + }, + patternProperties: { + "^x-": { + } + }, + additionalProperties: false, + allOf: [ + { + $ref: "#/definitions/ExampleXORExamples" + }, + { + $ref: "#/definitions/SchemaXORContent" + } + ] + }, + Paths: { + type: "object", + patternProperties: { + "^\\/": { + $ref: "#/definitions/PathItem" + }, + "^x-": { + } + }, + additionalProperties: false + }, + PathItem: { + type: "object", + properties: { + $ref: { + type: "string" + }, + summary: { + type: "string" + }, + description: { + type: "string" + }, + servers: { + type: "array", + items: { + $ref: "#/definitions/Server" + } + }, + parameters: { + type: "array", + items: { + oneOf: [ + { + $ref: "#/definitions/Parameter" + }, + { + $ref: "#/definitions/Reference" + } + ] + }, + uniqueItems: true + } + }, + patternProperties: { + "^(get|put|post|delete|options|head|patch|trace)$": { + $ref: "#/definitions/Operation" + }, + "^x-": { + } + }, + additionalProperties: false + }, + Operation: { + type: "object", + required: [ + "responses" + ], + properties: { + tags: { + type: "array", + items: { + type: "string" + } + }, + summary: { + type: "string" + }, + description: { + type: "string" + }, + externalDocs: { + $ref: "#/definitions/ExternalDocumentation" + }, + operationId: { + type: "string" + }, + parameters: { + type: "array", + items: { + oneOf: [ + { + $ref: "#/definitions/Parameter" + }, + { + $ref: "#/definitions/Reference" + } + ] + }, + uniqueItems: true + }, + requestBody: { + oneOf: [ + { + $ref: "#/definitions/RequestBody" + }, + { + $ref: "#/definitions/Reference" + } + ] + }, + responses: { + $ref: "#/definitions/Responses" + }, + callbacks: { + type: "object", + additionalProperties: { + oneOf: [ + { + $ref: "#/definitions/Callback" + }, + { + $ref: "#/definitions/Reference" + } + ] + } + }, + deprecated: { + type: "boolean", + "default": false + }, + security: { + type: "array", + items: { + $ref: "#/definitions/SecurityRequirement" + } + }, + servers: { + type: "array", + items: { + $ref: "#/definitions/Server" + } + } + }, + patternProperties: { + "^x-": { + } + }, + additionalProperties: false + }, + Responses: { + type: "object", + properties: { + "default": { + oneOf: [ + { + $ref: "#/definitions/Response" + }, + { + $ref: "#/definitions/Reference" + } + ] + } + }, + patternProperties: { + "^[1-5](?:\\d{2}|XX)$": { + oneOf: [ + { + $ref: "#/definitions/Response" + }, + { + $ref: "#/definitions/Reference" + } + ] + }, + "^x-": { + } + }, + minProperties: 1, + additionalProperties: false + }, + SecurityRequirement: { + type: "object", + additionalProperties: { + type: "array", + items: { + type: "string" + } + } + }, + Tag: { + type: "object", + required: [ + "name" + ], + properties: { + name: { + type: "string" + }, + description: { + type: "string" + }, + externalDocs: { + $ref: "#/definitions/ExternalDocumentation" + } + }, + patternProperties: { + "^x-": { + } + }, + additionalProperties: false + }, + ExternalDocumentation: { + type: "object", + required: [ + "url" + ], + properties: { + description: { + type: "string" + }, + url: { + type: "string", + format: "uri-reference" + } + }, + patternProperties: { + "^x-": { + } + }, + additionalProperties: false + }, + ExampleXORExamples: { + description: "Example and examples are mutually exclusive", + not: { + required: [ + "example", + "examples" + ] + } + }, + SchemaXORContent: { + description: "Schema and content are mutually exclusive, at least one is required", + not: { + required: [ + "schema", + "content" + ] + }, + oneOf: [ + { + required: [ + "schema" + ] + }, + { + required: [ + "content" + ], + description: "Some properties are not allowed if content is present", + allOf: [ + { + not: { + required: [ + "style" + ] + } + }, + { + not: { + required: [ + "explode" + ] + } + }, + { + not: { + required: [ + "allowReserved" + ] + } + }, + { + not: { + required: [ + "example" + ] + } + }, + { + not: { + required: [ + "examples" + ] + } + } + ] + } + ] + }, + Parameter: { + type: "object", + properties: { + name: { + type: "string" + }, + "in": { + type: "string" + }, + description: { + type: "string" + }, + required: { + type: "boolean", + "default": false + }, + deprecated: { + type: "boolean", + "default": false + }, + allowEmptyValue: { + type: "boolean", + "default": false + }, + style: { + type: "string" + }, + explode: { + type: "boolean" + }, + allowReserved: { + type: "boolean", + "default": false + }, + schema: { + oneOf: [ + { + $ref: "#/definitions/Schema" + }, + { + $ref: "#/definitions/Reference" + } + ] + }, + content: { + type: "object", + additionalProperties: { + $ref: "#/definitions/MediaType" + }, + minProperties: 1, + maxProperties: 1 + }, + example: { + }, + examples: { + type: "object", + additionalProperties: { + oneOf: [ + { + $ref: "#/definitions/Example" + }, + { + $ref: "#/definitions/Reference" + } + ] + } + } + }, + patternProperties: { + "^x-": { + } + }, + additionalProperties: false, + required: [ + "name", + "in" + ], + allOf: [ + { + $ref: "#/definitions/ExampleXORExamples" + }, + { + $ref: "#/definitions/SchemaXORContent" + }, + { + $ref: "#/definitions/ParameterLocation" + } + ] + }, + ParameterLocation: { + description: "Parameter location", + oneOf: [ + { + description: "Parameter in path", + required: [ + "required" + ], + properties: { + "in": { + "enum": [ + "path" + ] + }, + style: { + "enum": [ + "matrix", + "label", + "simple" + ], + "default": "simple" + }, + required: { + "enum": [ + true + ] + } + } + }, + { + description: "Parameter in query", + properties: { + "in": { + "enum": [ + "query" + ] + }, + style: { + "enum": [ + "form", + "spaceDelimited", + "pipeDelimited", + "deepObject" + ], + "default": "form" + } + } + }, + { + description: "Parameter in header", + properties: { + "in": { + "enum": [ + "header" + ] + }, + style: { + "enum": [ + "simple" + ], + "default": "simple" + } + } + }, + { + description: "Parameter in cookie", + properties: { + "in": { + "enum": [ + "cookie" + ] + }, + style: { + "enum": [ + "form" + ], + "default": "form" + } + } + } + ] + }, + RequestBody: { + type: "object", + required: [ + "content" + ], + properties: { + description: { + type: "string" + }, + content: { + type: "object", + additionalProperties: { + $ref: "#/definitions/MediaType" + } + }, + required: { + type: "boolean", + "default": false + } + }, + patternProperties: { + "^x-": { + } + }, + additionalProperties: false + }, + SecurityScheme: { + oneOf: [ + { + $ref: "#/definitions/APIKeySecurityScheme" + }, + { + $ref: "#/definitions/HTTPSecurityScheme" + }, + { + $ref: "#/definitions/OAuth2SecurityScheme" + }, + { + $ref: "#/definitions/OpenIdConnectSecurityScheme" + } + ] + }, + APIKeySecurityScheme: { + type: "object", + required: [ + "type", + "name", + "in" + ], + properties: { + type: { + type: "string", + "enum": [ + "apiKey" + ] + }, + name: { + type: "string" + }, + "in": { + type: "string", + "enum": [ + "header", + "query", + "cookie" + ] + }, + description: { + type: "string" + } + }, + patternProperties: { + "^x-": { + } + }, + additionalProperties: false + }, + HTTPSecurityScheme: { + type: "object", + required: [ + "scheme", + "type" + ], + properties: { + scheme: { + type: "string" + }, + bearerFormat: { + type: "string" + }, + description: { + type: "string" + }, + type: { + type: "string", + "enum": [ + "http" + ] + } + }, + patternProperties: { + "^x-": { + } + }, + additionalProperties: false, + oneOf: [ + { + description: "Bearer", + properties: { + scheme: { + "enum": [ + "bearer" + ] + } + } + }, + { + description: "Non Bearer", + not: { + required: [ + "bearerFormat" + ] + }, + properties: { + scheme: { + not: { + "enum": [ + "bearer" + ] + } + } + } + } + ] + }, + OAuth2SecurityScheme: { + type: "object", + required: [ + "type", + "flows" + ], + properties: { + type: { + type: "string", + "enum": [ + "oauth2" + ] + }, + flows: { + $ref: "#/definitions/OAuthFlows" + }, + description: { + type: "string" + } + }, + patternProperties: { + "^x-": { + } + }, + additionalProperties: false + }, + OpenIdConnectSecurityScheme: { + type: "object", + required: [ + "type", + "openIdConnectUrl" + ], + properties: { + type: { + type: "string", + "enum": [ + "openIdConnect" + ] + }, + openIdConnectUrl: { + type: "string", + format: "uri-reference" + }, + description: { + type: "string" + } + }, + patternProperties: { + "^x-": { + } + }, + additionalProperties: false + }, + OAuthFlows: { + type: "object", + properties: { + implicit: { + $ref: "#/definitions/ImplicitOAuthFlow" + }, + password: { + $ref: "#/definitions/PasswordOAuthFlow" + }, + clientCredentials: { + $ref: "#/definitions/ClientCredentialsFlow" + }, + authorizationCode: { + $ref: "#/definitions/AuthorizationCodeOAuthFlow" + } + }, + patternProperties: { + "^x-": { + } + }, + additionalProperties: false + }, + ImplicitOAuthFlow: { + type: "object", + required: [ + "authorizationUrl", + "scopes" + ], + properties: { + authorizationUrl: { + type: "string", + format: "uri-reference" + }, + refreshUrl: { + type: "string", + format: "uri-reference" + }, + scopes: { + type: "object", + additionalProperties: { + type: "string" + } + } + }, + patternProperties: { + "^x-": { + } + }, + additionalProperties: false + }, + PasswordOAuthFlow: { + type: "object", + required: [ + "tokenUrl" + ], + properties: { + tokenUrl: { + type: "string", + format: "uri-reference" + }, + refreshUrl: { + type: "string", + format: "uri-reference" + }, + scopes: { + type: "object", + additionalProperties: { + type: "string" + } + } + }, + patternProperties: { + "^x-": { + } + }, + additionalProperties: false + }, + ClientCredentialsFlow: { + type: "object", + required: [ + "tokenUrl" + ], + properties: { + tokenUrl: { + type: "string", + format: "uri-reference" + }, + refreshUrl: { + type: "string", + format: "uri-reference" + }, + scopes: { + type: "object", + additionalProperties: { + type: "string" + } + } + }, + patternProperties: { + "^x-": { + } + }, + additionalProperties: false + }, + AuthorizationCodeOAuthFlow: { + type: "object", + required: [ + "authorizationUrl", + "tokenUrl" + ], + properties: { + authorizationUrl: { + type: "string", + format: "uri-reference" + }, + tokenUrl: { + type: "string", + format: "uri-reference" + }, + refreshUrl: { + type: "string", + format: "uri-reference" + }, + scopes: { + type: "object", + additionalProperties: { + type: "string" + } + } + }, + patternProperties: { + "^x-": { + } + }, + additionalProperties: false + }, + Link: { + type: "object", + properties: { + operationId: { + type: "string" + }, + operationRef: { + type: "string", + format: "uri-reference" + }, + parameters: { + type: "object", + additionalProperties: { + } + }, + requestBody: { + }, + description: { + type: "string" + }, + server: { + $ref: "#/definitions/Server" + } + }, + patternProperties: { + "^x-": { + } + }, + additionalProperties: false, + not: { + description: "Operation Id and Operation Ref are mutually exclusive", + required: [ + "operationId", + "operationRef" + ] + } + }, + Callback: { + type: "object", + additionalProperties: { + $ref: "#/definitions/PathItem" + }, + patternProperties: { + "^x-": { + } + } + }, + Encoding: { + type: "object", + properties: { + contentType: { + type: "string" + }, + headers: { + type: "object", + additionalProperties: { + $ref: "#/definitions/Header" + } + }, + style: { + type: "string", + "enum": [ + "form", + "spaceDelimited", + "pipeDelimited", + "deepObject" + ] + }, + explode: { + type: "boolean" + }, + allowReserved: { + type: "boolean", + "default": false + } + }, + additionalProperties: false + } +}; +var require$$2$1 = { + id: id$2, + $schema: $schema$a, + description: description$3, + type: type$b, + required: required$5, + properties: properties$d, + patternProperties: patternProperties$1, + additionalProperties: additionalProperties$3, + definitions: definitions$1 +}; + +var $id$9 = "https://spec.openapis.org/oas/3.1/schema/2021-04-15"; +var $schema$9 = "https://json-schema.org/draft/2020-12/schema"; +var type$a = "object"; +var properties$c = { + openapi: { + type: "string", + pattern: "^3\\.1\\.\\d+(-.+)?$" + }, + info: { + $ref: "#/$defs/info" + }, + jsonSchemaDialect: { + $ref: "#/$defs/uri", + "default": "https://spec.openapis.org/oas/3.1/dialect/base" + }, + servers: { + type: "array", + items: { + $ref: "#/$defs/server" + } + }, + paths: { + $ref: "#/$defs/paths" + }, + webhooks: { + type: "object", + additionalProperties: { + $ref: "#/$defs/path-item-or-reference" + } + }, + components: { + $ref: "#/$defs/components" + }, + security: { + type: "array", + items: { + $ref: "#/$defs/security-requirement" + } + }, + tags: { + type: "array", + items: { + $ref: "#/$defs/tag" + } + }, + externalDocs: { + $ref: "#/$defs/external-documentation" + } +}; +var required$4 = [ + "openapi", + "info" +]; +var anyOf$1 = [ + { + required: [ + "paths" + ] + }, + { + required: [ + "components" + ] + }, + { + required: [ + "webhooks" + ] + } +]; +var $ref = "#/$defs/specification-extensions"; +var unevaluatedProperties$1 = false; +var $defs$3 = { + info: { + type: "object", + properties: { + title: { + type: "string" + }, + summary: { + type: "string" + }, + description: { + type: "string" + }, + termsOfService: { + type: "string" + }, + contact: { + $ref: "#/$defs/contact" + }, + license: { + $ref: "#/$defs/license" + }, + version: { + type: "string" + } + }, + required: [ + "title", + "version" + ], + $ref: "#/$defs/specification-extensions", + unevaluatedProperties: false + }, + contact: { + type: "object", + properties: { + name: { + type: "string" + }, + url: { + type: "string" + }, + email: { + type: "string" + } + }, + $ref: "#/$defs/specification-extensions", + unevaluatedProperties: false + }, + license: { + type: "object", + properties: { + name: { + type: "string" + }, + identifier: { + type: "string" + }, + url: { + $ref: "#/$defs/uri" + } + }, + required: [ + "name" + ], + oneOf: [ + { + required: [ + "identifier" + ] + }, + { + required: [ + "url" + ] + } + ], + $ref: "#/$defs/specification-extensions", + unevaluatedProperties: false + }, + server: { + type: "object", + properties: { + url: { + $ref: "#/$defs/uri" + }, + description: { + type: "string" + }, + variables: { + type: "object", + additionalProperties: { + $ref: "#/$defs/server-variable" + } + } + }, + required: [ + "url" + ], + $ref: "#/$defs/specification-extensions", + unevaluatedProperties: false + }, + "server-variable": { + type: "object", + properties: { + "enum": { + type: "array", + items: { + type: "string" + }, + minItems: 1 + }, + "default": { + type: "string" + }, + descriptions: { + type: "string" + } + }, + required: [ + "default" + ], + $ref: "#/$defs/specification-extensions", + unevaluatedProperties: false + }, + components: { + type: "object", + properties: { + schemas: { + type: "object", + additionalProperties: { + $dynamicRef: "#meta" + } + }, + responses: { + type: "object", + additionalProperties: { + $ref: "#/$defs/response-or-reference" + } + }, + parameters: { + type: "object", + additionalProperties: { + $ref: "#/$defs/parameter-or-reference" + } + }, + examples: { + type: "object", + additionalProperties: { + $ref: "#/$defs/example-or-reference" + } + }, + requestBodies: { + type: "object", + additionalProperties: { + $ref: "#/$defs/request-body-or-reference" + } + }, + headers: { + type: "object", + additionalProperties: { + $ref: "#/$defs/header-or-reference" + } + }, + securitySchemes: { + type: "object", + additionalProperties: { + $ref: "#/$defs/security-scheme-or-reference" + } + }, + links: { + type: "object", + additionalProperties: { + $ref: "#/$defs/link-or-reference" + } + }, + callbacks: { + type: "object", + additionalProperties: { + $ref: "#/$defs/callbacks-or-reference" + } + }, + pathItems: { + type: "object", + additionalProperties: { + $ref: "#/$defs/path-item-or-reference" + } + } + }, + patternProperties: { + "^(schemas|responses|parameters|examples|requestBodies|headers|securitySchemes|links|callbacks|pathItems)$": { + $comment: "Enumerating all of the property names in the regex above is necessary for unevaluatedProperties to work as expected", + propertyNames: { + pattern: "^[a-zA-Z0-9._-]+$" + } + } + }, + $ref: "#/$defs/specification-extensions", + unevaluatedProperties: false + }, + paths: { + type: "object", + patternProperties: { + "^/": { + $ref: "#/$defs/path-item" + } + }, + $ref: "#/$defs/specification-extensions", + unevaluatedProperties: false + }, + "path-item": { + type: "object", + properties: { + summary: { + type: "string" + }, + description: { + type: "string" + }, + servers: { + type: "array", + items: { + $ref: "#/$defs/server" + } + }, + parameters: { + type: "array", + items: { + $ref: "#/$defs/parameter-or-reference" + } + } + }, + patternProperties: { + "^(get|put|post|delete|options|head|patch|trace)$": { + $ref: "#/$defs/operation" + } + }, + $ref: "#/$defs/specification-extensions", + unevaluatedProperties: false + }, + "path-item-or-reference": { + "if": { + required: [ + "$ref" + ] + }, + then: { + $ref: "#/$defs/reference" + }, + "else": { + $ref: "#/$defs/path-item" + } + }, + operation: { + type: "object", + properties: { + tags: { + type: "array", + items: { + type: "string" + } + }, + summary: { + type: "string" + }, + description: { + type: "string" + }, + externalDocs: { + $ref: "#/$defs/external-documentation" + }, + operationId: { + type: "string" + }, + parameters: { + type: "array", + items: { + $ref: "#/$defs/parameter-or-reference" + } + }, + requestBody: { + $ref: "#/$defs/request-body-or-reference" + }, + responses: { + $ref: "#/$defs/responses" + }, + callbacks: { + type: "object", + additionalProperties: { + $ref: "#/$defs/callbacks-or-reference" + } + }, + deprecated: { + "default": false, + type: "boolean" + }, + security: { + type: "array", + items: { + $ref: "#/$defs/security-requirement" + } + }, + servers: { + type: "array", + items: { + $ref: "#/$defs/server" + } + } + }, + $ref: "#/$defs/specification-extensions", + unevaluatedProperties: false + }, + "external-documentation": { + type: "object", + properties: { + description: { + type: "string" + }, + url: { + $ref: "#/$defs/uri" + } + }, + required: [ + "url" + ], + $ref: "#/$defs/specification-extensions", + unevaluatedProperties: false + }, + parameter: { + type: "object", + properties: { + name: { + type: "string" + }, + "in": { + "enum": [ + "query", + "header", + "path", + "cookie" + ] + }, + description: { + type: "string" + }, + required: { + "default": false, + type: "boolean" + }, + deprecated: { + "default": false, + type: "boolean" + }, + allowEmptyValue: { + "default": false, + type: "boolean" + }, + schema: { + $dynamicRef: "#meta" + }, + content: { + $ref: "#/$defs/content" + } + }, + required: [ + "in" + ], + oneOf: [ + { + required: [ + "schema" + ] + }, + { + required: [ + "content" + ] + } + ], + dependentSchemas: { + schema: { + properties: { + style: { + type: "string" + }, + explode: { + type: "boolean" + }, + allowReserved: { + "default": false, + type: "boolean" + } + }, + allOf: [ + { + $ref: "#/$defs/examples" + }, + { + $ref: "#/$defs/parameter/dependentSchemas/schema/$defs/styles-for-path" + }, + { + $ref: "#/$defs/parameter/dependentSchemas/schema/$defs/styles-for-header" + }, + { + $ref: "#/$defs/parameter/dependentSchemas/schema/$defs/styles-for-query" + }, + { + $ref: "#/$defs/parameter/dependentSchemas/schema/$defs/styles-for-cookie" + }, + { + $ref: "#/$defs/parameter/dependentSchemas/schema/$defs/styles-for-form" + } + ], + $defs: { + "styles-for-path": { + "if": { + properties: { + "in": { + "const": "path" + } + }, + required: [ + "in" + ] + }, + then: { + properties: { + style: { + "default": "simple", + "enum": [ + "matrix", + "label", + "simple" + ] + }, + required: { + "const": true + } + }, + required: [ + "required" + ] + } + }, + "styles-for-header": { + "if": { + properties: { + "in": { + "const": "header" + } + }, + required: [ + "in" + ] + }, + then: { + properties: { + style: { + "default": "simple", + "enum": [ + "simple" + ] + } + } + } + }, + "styles-for-query": { + "if": { + properties: { + "in": { + "const": "query" + } + }, + required: [ + "in" + ] + }, + then: { + properties: { + style: { + "default": "form", + "enum": [ + "form", + "spaceDelimited", + "pipeDelimited", + "deepObject" + ] + } + } + } + }, + "styles-for-cookie": { + "if": { + properties: { + "in": { + "const": "cookie" + } + }, + required: [ + "in" + ] + }, + then: { + properties: { + style: { + "default": "form", + "enum": [ + "form" + ] + } + } + } + }, + "styles-for-form": { + "if": { + properties: { + style: { + "const": "form" + } + }, + required: [ + "style" + ] + }, + then: { + properties: { + explode: { + "default": true + } + } + }, + "else": { + properties: { + explode: { + "default": false + } + } + } + } + } + } + }, + $ref: "#/$defs/specification-extensions", + unevaluatedProperties: false + }, + "parameter-or-reference": { + "if": { + required: [ + "$ref" + ] + }, + then: { + $ref: "#/$defs/reference" + }, + "else": { + $ref: "#/$defs/parameter" + } + }, + "request-body": { + type: "object", + properties: { + description: { + type: "string" + }, + content: { + $ref: "#/$defs/content" + }, + required: { + "default": false, + type: "boolean" + } + }, + required: [ + "content" + ], + $ref: "#/$defs/specification-extensions", + unevaluatedProperties: false + }, + "request-body-or-reference": { + "if": { + required: [ + "$ref" + ] + }, + then: { + $ref: "#/$defs/reference" + }, + "else": { + $ref: "#/$defs/request-body" + } + }, + content: { + type: "object", + additionalProperties: { + $ref: "#/$defs/media-type" + }, + propertyNames: { + format: "media-range" + } + }, + "media-type": { + type: "object", + properties: { + schema: { + $dynamicRef: "#meta" + }, + encoding: { + type: "object", + additionalProperties: { + $ref: "#/$defs/encoding" + } + } + }, + allOf: [ + { + $ref: "#/$defs/specification-extensions" + }, + { + $ref: "#/$defs/examples" + } + ], + unevaluatedProperties: false + }, + encoding: { + type: "object", + properties: { + contentType: { + type: "string", + format: "media-range" + }, + headers: { + type: "object", + additionalProperties: { + $ref: "#/$defs/header-or-reference" + } + }, + style: { + "default": "form", + "enum": [ + "form", + "spaceDelimited", + "pipeDelimited", + "deepObject" + ] + }, + explode: { + type: "boolean" + }, + allowReserved: { + "default": false, + type: "boolean" + } + }, + allOf: [ + { + $ref: "#/$defs/specification-extensions" + }, + { + $ref: "#/$defs/encoding/$defs/explode-default" + } + ], + unevaluatedProperties: false, + $defs: { + "explode-default": { + "if": { + properties: { + style: { + "const": "form" + } + }, + required: [ + "style" + ] + }, + then: { + properties: { + explode: { + "default": true + } + } + }, + "else": { + properties: { + explode: { + "default": false + } + } + } + } + } + }, + responses: { + type: "object", + properties: { + "default": { + $ref: "#/$defs/response-or-reference" + } + }, + patternProperties: { + "^[1-5][0-9X]{2}$": { + $ref: "#/$defs/response-or-reference" + } + }, + $ref: "#/$defs/specification-extensions", + unevaluatedProperties: false + }, + response: { + type: "object", + properties: { + description: { + type: "string" + }, + headers: { + type: "object", + additionalProperties: { + $ref: "#/$defs/header-or-reference" + } + }, + content: { + $ref: "#/$defs/content" + }, + links: { + type: "object", + additionalProperties: { + $ref: "#/$defs/link-or-reference" + } + } + }, + required: [ + "description" + ], + $ref: "#/$defs/specification-extensions", + unevaluatedProperties: false + }, + "response-or-reference": { + "if": { + required: [ + "$ref" + ] + }, + then: { + $ref: "#/$defs/reference" + }, + "else": { + $ref: "#/$defs/response" + } + }, + callbacks: { + type: "object", + $ref: "#/$defs/specification-extensions", + additionalProperties: { + $ref: "#/$defs/path-item-or-reference" + } + }, + "callbacks-or-reference": { + "if": { + required: [ + "$ref" + ] + }, + then: { + $ref: "#/$defs/reference" + }, + "else": { + $ref: "#/$defs/callbacks" + } + }, + example: { + type: "object", + properties: { + summary: { + type: "string" + }, + description: { + type: "string" + }, + value: true, + externalValue: { + $ref: "#/$defs/uri" + } + }, + $ref: "#/$defs/specification-extensions", + unevaluatedProperties: false + }, + "example-or-reference": { + "if": { + required: [ + "$ref" + ] + }, + then: { + $ref: "#/$defs/reference" + }, + "else": { + $ref: "#/$defs/example" + } + }, + link: { + type: "object", + properties: { + operationRef: { + $ref: "#/$defs/uri" + }, + operationId: true, + parameters: { + $ref: "#/$defs/map-of-strings" + }, + requestBody: true, + description: { + type: "string" + }, + body: { + $ref: "#/$defs/server" + } + }, + oneOf: [ + { + required: [ + "operationRef" + ] + }, + { + required: [ + "operationId" + ] + } + ], + $ref: "#/$defs/specification-extensions", + unevaluatedProperties: false + }, + "link-or-reference": { + "if": { + required: [ + "$ref" + ] + }, + then: { + $ref: "#/$defs/reference" + }, + "else": { + $ref: "#/$defs/link" + } + }, + header: { + type: "object", + properties: { + description: { + type: "string" + }, + required: { + "default": false, + type: "boolean" + }, + deprecated: { + "default": false, + type: "boolean" + }, + allowEmptyValue: { + "default": false, + type: "boolean" + } + }, + dependentSchemas: { + schema: { + properties: { + style: { + "default": "simple", + "enum": [ + "simple" + ] + }, + explode: { + "default": false, + type: "boolean" + }, + allowReserved: { + "default": false, + type: "boolean" + }, + schema: { + $dynamicRef: "#meta" + } + }, + $ref: "#/$defs/examples" + }, + content: { + properties: { + content: { + $ref: "#/$defs/content" + } + } + } + }, + $ref: "#/$defs/specification-extensions", + unevaluatedProperties: false + }, + "header-or-reference": { + "if": { + required: [ + "$ref" + ] + }, + then: { + $ref: "#/$defs/reference" + }, + "else": { + $ref: "#/$defs/header" + } + }, + tag: { + type: "object", + properties: { + name: { + type: "string" + }, + description: { + type: "string" + }, + externalDocs: { + $ref: "#/$defs/external-documentation" + } + }, + required: [ + "name" + ], + $ref: "#/$defs/specification-extensions", + unevaluatedProperties: false + }, + reference: { + type: "object", + properties: { + $ref: { + $ref: "#/$defs/uri" + }, + summary: { + type: "string" + }, + description: { + type: "string" + } + }, + unevaluatedProperties: false + }, + schema: { + $dynamicAnchor: "meta", + type: [ + "object", + "boolean" + ] + }, + "security-scheme": { + type: "object", + properties: { + type: { + "enum": [ + "apiKey", + "http", + "mutualTLS", + "oauth2", + "openIdConnect" + ] + }, + description: { + type: "string" + } + }, + required: [ + "type" + ], + allOf: [ + { + $ref: "#/$defs/specification-extensions" + }, + { + $ref: "#/$defs/security-scheme/$defs/type-apikey" + }, + { + $ref: "#/$defs/security-scheme/$defs/type-http" + }, + { + $ref: "#/$defs/security-scheme/$defs/type-http-bearer" + }, + { + $ref: "#/$defs/security-scheme/$defs/type-oauth2" + }, + { + $ref: "#/$defs/security-scheme/$defs/type-oidc" + } + ], + unevaluatedProperties: false, + $defs: { + "type-apikey": { + "if": { + properties: { + type: { + "const": "apiKey" + } + }, + required: [ + "type" + ] + }, + then: { + properties: { + name: { + type: "string" + }, + "in": { + "enum": [ + "query", + "header", + "cookie" + ] + } + }, + required: [ + "name", + "in" + ] + } + }, + "type-http": { + "if": { + properties: { + type: { + "const": "http" + } + }, + required: [ + "type" + ] + }, + then: { + properties: { + scheme: { + type: "string" + } + }, + required: [ + "scheme" + ] + } + }, + "type-http-bearer": { + "if": { + properties: { + type: { + "const": "http" + }, + scheme: { + "const": "bearer" + } + }, + required: [ + "type", + "scheme" + ] + }, + then: { + properties: { + bearerFormat: { + type: "string" + } + }, + required: [ + "scheme" + ] + } + }, + "type-oauth2": { + "if": { + properties: { + type: { + "const": "oauth2" + } + }, + required: [ + "type" + ] + }, + then: { + properties: { + flows: { + $ref: "#/$defs/oauth-flows" + } + }, + required: [ + "flows" + ] + } + }, + "type-oidc": { + "if": { + properties: { + type: { + "const": "openIdConnect" + } + }, + required: [ + "type" + ] + }, + then: { + properties: { + openIdConnectUrl: { + $ref: "#/$defs/uri" + } + }, + required: [ + "openIdConnectUrl" + ] + } + } + } + }, + "security-scheme-or-reference": { + "if": { + required: [ + "$ref" + ] + }, + then: { + $ref: "#/$defs/reference" + }, + "else": { + $ref: "#/$defs/security-scheme" + } + }, + "oauth-flows": { + type: "object", + properties: { + implicit: { + $ref: "#/$defs/oauth-flows/$defs/implicit" + }, + password: { + $ref: "#/$defs/oauth-flows/$defs/password" + }, + clientCredentials: { + $ref: "#/$defs/oauth-flows/$defs/client-credentials" + }, + authorizationCode: { + $ref: "#/$defs/oauth-flows/$defs/authorization-code" + } + }, + $ref: "#/$defs/specification-extensions", + unevaluatedProperties: false, + $defs: { + implicit: { + type: "object", + properties: { + authorizationUrl: { + type: "string" + }, + refreshUrl: { + type: "string" + }, + scopes: { + $ref: "#/$defs/map-of-strings" + } + }, + required: [ + "authorizationUrl", + "scopes" + ], + $ref: "#/$defs/specification-extensions", + unevaluatedProperties: false + }, + password: { + type: "object", + properties: { + tokenUrl: { + type: "string" + }, + refreshUrl: { + type: "string" + }, + scopes: { + $ref: "#/$defs/map-of-strings" + } + }, + required: [ + "tokenUrl", + "scopes" + ], + $ref: "#/$defs/specification-extensions", + unevaluatedProperties: false + }, + "client-credentials": { + type: "object", + properties: { + tokenUrl: { + type: "string" + }, + refreshUrl: { + type: "string" + }, + scopes: { + $ref: "#/$defs/map-of-strings" + } + }, + required: [ + "tokenUrl", + "scopes" + ], + $ref: "#/$defs/specification-extensions", + unevaluatedProperties: false + }, + "authorization-code": { + type: "object", + properties: { + authorizationUrl: { + type: "string" + }, + tokenUrl: { + type: "string" + }, + refreshUrl: { + type: "string" + }, + scopes: { + $ref: "#/$defs/map-of-strings" + } + }, + required: [ + "authorizationUrl", + "tokenUrl", + "scopes" + ], + $ref: "#/$defs/specification-extensions", + unevaluatedProperties: false + } + } + }, + "security-requirement": { + type: "object", + additionalProperties: { + type: "array", + items: { + type: "string" + } + } + }, + "specification-extensions": { + patternProperties: { + "^x-": true + } + }, + examples: { + properties: { + example: true, + examples: { + type: "object", + additionalProperties: { + $ref: "#/$defs/example-or-reference" + } + } + } + }, + uri: { + type: "string", + format: "uri" + }, + "map-of-strings": { + type: "object", + additionalProperties: { + type: "string" + } + } +}; +var require$$3$3 = { + $id: $id$9, + $schema: $schema$9, + type: type$a, + properties: properties$c, + required: required$4, + anyOf: anyOf$1, + $ref: $ref, + unevaluatedProperties: unevaluatedProperties$1, + $defs: $defs$3 +}; + +(function (module, exports) { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.openapi = exports.openapiV31 = exports.openapiV3 = exports.openapiV2 = exports.openapiV1 = void 0; + /** + * JSON Schema for OpenAPI Specification v1.2 + */ + exports.openapiV1 = require$$0$2; + /** + * JSON Schema for OpenAPI Specification v2.0 + */ + exports.openapiV2 = require$$1$2; + /** + * JSON Schema for OpenAPI Specification v3.0 + */ + exports.openapiV3 = require$$2$1; + /** + * JSON Schema for OpenAPI Specification v3.1 + */ + exports.openapiV31 = require$$3$3; + /** + * JSON Schemas for every version of the OpenAPI Specification + */ + exports.openapi = { + v1: exports.openapiV1, + v2: exports.openapiV2, + v3: exports.openapiV3, + v31: exports.openapiV31, + }; + // Export `openapi` as the default export + exports.default = exports.openapi; + // CommonJS default export hack + /* eslint-env commonjs */ + { + module.exports = Object.assign(module.exports.default, module.exports); + } + +} (lib$g, lib$g.exports)); + +var libExports$1 = lib$g.exports; + +var lib$f = {exports: {}}; + +var interopRequireDefault = {exports: {}}; + +(function (module) { + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + "default": obj + }; + } + module.exports = _interopRequireDefault, module.exports.__esModule = true, module.exports["default"] = module.exports; +} (interopRequireDefault)); + +var interopRequireDefaultExports = interopRequireDefault.exports; + +var api$1 = {}; + +Object.defineProperty(api$1, '__esModule', { value: true }); + +/** + * @fileoverview JSON syntax helpers + * @author Nicholas C. Zakas + */ + +//----------------------------------------------------------------------------- +// Predefined Tokens +//----------------------------------------------------------------------------- + +const LBRACKET = "["; +const RBRACKET = "]"; +const LBRACE = "{"; +const RBRACE = "}"; +const COLON$1 = ":"; +const COMMA = ","; + +const TRUE = "true"; +const FALSE = "false"; +const NULL = "null"; + +const QUOTE = "\""; + +const expectedKeywords = new Map([ + ["t", TRUE], + ["f", FALSE], + ["n", NULL] +]); + +const escapeToChar = new Map([ + [QUOTE, QUOTE], + ["\\", "\\"], + ["/", "/"], + ["b", "\b"], + ["n", "\n"], + ["f", "\f"], + ["r", "\r"], + ["t", "\t"] +]); + +const knownTokenTypes = new Map([ + [LBRACKET, "Punctuator"], + [RBRACKET, "Punctuator"], + [LBRACE, "Punctuator"], + [RBRACE, "Punctuator"], + [COLON$1, "Punctuator"], + [COMMA, "Punctuator"], + [TRUE, "Boolean"], + [FALSE, "Boolean"], + [NULL, "Null"] +]); + +/** + * @fileoverview JSON tokenization/parsing errors + * @author Nicholas C. Zakas + */ + + +/** + * Base class that attaches location to an error. + */ +class ErrorWithLocation extends Error { + + /** + * + * @param {string} message The error message to report. + * @param {int} loc.line The line on which the error occurred. + * @param {int} loc.column The column in the line where the error occurrred. + * @param {int} loc.index The index in the string where the error occurred. + */ + constructor(message, { line, column, index }) { + super(`${ message } (${ line }:${ column})`); + + /** + * The line on which the error occurred. + * @type int + * @property line + */ + this.line = line; + + /** + * The column on which the error occurred. + * @type int + * @property column + */ + this.column = column; + + /** + * The index into the string where the error occurred. + * @type int + * @property index + */ + this.index = index; + } + +} + +/** + * Error thrown when an unexpected character is found during tokenizing. + */ +class UnexpectedChar extends ErrorWithLocation { + + /** + * Creates a new instance. + * @param {string} unexpected The character that was found. + * @param {Object} loc The location information for the found character. + */ + constructor(unexpected, loc) { + super(`Unexpected character ${ unexpected } found.`, loc); + } +} + +/** + * Error thrown when an unexpected token is found during parsing. + */ +class UnexpectedToken extends ErrorWithLocation { + + /** + * Creates a new instance. + * @param {string} expected The character that was expected. + * @param {string} unexpected The character that was found. + * @param {Object} loc The location information for the found character. + */ + constructor(token) { + super(`Unexpected token ${ token.type }(${ token.value }) found.`, token.loc.start); + } +} + +/** + * Error thrown when the end of input is found where it isn't expected. + */ +class UnexpectedEOF extends ErrorWithLocation { + + /** + * Creates a new instance. + * @param {Object} loc The location information for the found character. + */ + constructor(loc) { + super("Unexpected end of input found.", loc); + } +} + +/** + * @fileoverview JSON tokenizer + * @author Nicholas C. Zakas + */ + +//----------------------------------------------------------------------------- +// Helpers +//----------------------------------------------------------------------------- + +const QUOTE$1 = "\""; +const SLASH = "/"; +const STAR = "*"; + +const DEFAULT_OPTIONS = { + comments: false, + ranges: false +}; + +function isWhitespace(c) { + return /[\s\n]/.test(c); +} + +function isDigit$1(c) { + return c >= "0" && c <= "9"; +} + +function isHexDigit(c) { + return isDigit$1(c) || /[a-f]/i.test(c); +} + +function isPositiveDigit(c) { + return c >= "1" && c <= "9"; +} + +function isKeywordStart(c) { + return /[tfn]/.test(c); +} + +function isNumberStart(c) { + return isDigit$1(c) || c === "." || c === "-"; +} + +//----------------------------------------------------------------------------- +// Main +//----------------------------------------------------------------------------- + +/** + * Creates an iterator over the tokens representing the source text. + * @param {string} text The source text to tokenize. + * @returns {Iterator} An iterator over the tokens. + */ +function tokenize(text, options) { + + options = Object.freeze({ + ...DEFAULT_OPTIONS, + ...options + }); + + let offset = -1; + let line = 1; + let column = 0; + let newLine = false; + + const tokens = []; + + + function createToken(tokenType, value, startLoc, endLoc) { + + const endOffset = startLoc.offset + value.length; + let range = options.ranges ? { + range: [startLoc.offset, endOffset] + } : undefined; + + return { + type: tokenType, + value, + loc: { + start: startLoc, + end: endLoc || { + line: startLoc.line, + column: startLoc.column + value.length, + offset: endOffset + } + }, + ...range + }; + } + + function next() { + let c = text.charAt(++offset); + + if (newLine) { + line++; + column = 1; + newLine = false; + } else { + column++; + } + + if (c === "\r") { + newLine = true; + + // if we already see a \r, just ignore upcoming \n + if (text.charAt(offset + 1) === "\n") { + offset++; + } + } else if (c === "\n") { + newLine = true; + } + + return c; + } + + function locate() { + return { + line, + column, + offset + }; + } + + function readKeyword(c) { + + // get the expected keyword + let value = expectedKeywords.get(c); + + // check to see if it actually exists + if (text.slice(offset, offset + value.length) === value) { + offset += value.length - 1; + column += value.length - 1; + return { value, c: next() }; + } + + // find the first unexpected character + for (let j = 1; j < value.length; j++) { + if (value[j] !== text.charAt(offset + j)) { + unexpected(next()); + } + } + + } + + function readString(c) { + let value = c; + c = next(); + + while (c && c !== QUOTE$1) { + + // escapes + if (c === "\\") { + value += c; + c = next(); + + if (escapeToChar.has(c)) { + value += c; + } else if (c === "u") { + value += c; + for (let i = 0; i < 4; i++) { + c = next(); + if (isHexDigit(c)) { + value += c; + } else { + unexpected(c); + } + } + } else { + unexpected(c); + } + } else { + value += c; + } + + c = next(); + } + + if (!c) { + unexpectedEOF(); + } + + value += c; + + return { value, c: next() }; + } + + + function readNumber(c) { + + let value = ""; + + // Number may start with a minus but not a plus + if (c === "-") { + + value += c; + + c = next(); + + // Next digit cannot be zero + if (!isDigit$1(c)) { + unexpected(c); + } + + } + + // Zero must be followed by a decimal point or nothing + if (c === "0") { + + value += c; + + c = next(); + if (isDigit$1(c)) { + unexpected(c); + } + + } else { + if (!isPositiveDigit(c)) { + unexpected(c); + } + + do { + value += c; + c = next(); + } while (isDigit$1(c)); + } + + // Decimal point may be followed by any number of digits + if (c === ".") { + + do { + value += c; + c = next(); + } while (isDigit$1(c)); + } + + // Exponent is always last + if (c === "e" || c === "E") { + + value += c; + c = next(); + + if (c === "+" || c === "-") { + value += c; + c = next(); + } + + /* + * Must always have a digit in this position to avoid: + * 5e + * 12E+ + * 42e- + */ + if (!isDigit$1(c)) { + unexpected(c); + } + + while (isDigit$1(c)) { + value += c; + c = next(); + } + } + + + return { value, c }; + } + + /** + * Reads in either a single-line or multi-line comment. + * @param {string} c The first character of the comment. + * @returns {string} The comment string. + * @throws {UnexpectedChar} when the comment cannot be read. + * @throws {UnexpectedEOF} when EOF is reached before the comment is + * finalized. + */ + function readComment(c) { + + let value = c; + + // next character determines single- or multi-line + c = next(); + + // single-line comments + if (c === "/") { + + do { + value += c; + c = next(); + } while (c && c !== "\r" && c !== "\n"); + + return { value, c }; + } + + // multi-line comments + if (c === STAR) { + + while (c) { + value += c; + c = next(); + + // check for end of comment + if (c === STAR) { + value += c; + c = next(); + + //end of comment + if (c === SLASH) { + value += c; + + /* + * The single-line comment functionality cues up the + * next character, so we do the same here to avoid + * splitting logic later. + */ + c = next(); + return { value, c }; + } + } + } + + unexpectedEOF(); + + } + + // if we've made it here, there's an invalid character + unexpected(c); + } + + + /** + * Convenience function for throwing unexpected character errors. + * @param {string} c The unexpected character. + * @returns {void} + * @throws {UnexpectedChar} always. + */ + function unexpected(c) { + throw new UnexpectedChar(c, locate()); + } + + /** + * Convenience function for throwing unexpected EOF errors. + * @returns {void} + * @throws {UnexpectedEOF} always. + */ + function unexpectedEOF() { + throw new UnexpectedEOF(locate()); + } + + let c = next(); + + while (offset < text.length) { + + while (isWhitespace(c)) { + c = next(); + } + + if (!c) { + break; + } + + const start = locate(); + + // check for easy case + if (knownTokenTypes.has(c)) { + tokens.push(createToken(knownTokenTypes.get(c), c, start)); + c = next(); + } else if (isKeywordStart(c)) { + const result = readKeyword(c); + let value = result.value; + c = result.c; + tokens.push(createToken(knownTokenTypes.get(value), value, start)); + } else if (isNumberStart(c)) { + const result = readNumber(c); + let value = result.value; + c = result.c; + tokens.push(createToken("Number", value, start)); + } else if (c === QUOTE$1) { + const result = readString(c); + let value = result.value; + c = result.c; + tokens.push(createToken("String", value, start)); + } else if (c === SLASH && options.comments) { + const result = readComment(c); + let value = result.value; + c = result.c; + tokens.push(createToken(value.startsWith("//") ? "LineComment" : "BlockComment", value, start, locate())); + } else { + unexpected(c); + } + } + + return tokens; + +} + +/** + * @fileoverview Momoa JSON AST types + * @author Nicholas C. Zakas + */ + +const types$2 = { + document(body, parts = {}) { + return { + type: "Document", + body, + ...parts + }; + }, + string(value, parts = {}) { + return { + type: "String", + value, + ...parts + }; + }, + number(value, parts = {}) { + return { + type: "Number", + value, + ...parts + }; + }, + boolean(value, parts = {}) { + return { + type: "Boolean", + value, + ...parts + }; + }, + null(parts = {}) { + return { + type: "Null", + value: "null", + ...parts + }; + }, + array(elements, parts = {}) { + return { + type: "Array", + elements, + ...parts + }; + }, + object(members, parts = {}) { + return { + type: "Object", + members, + ...parts + }; + }, + member(name, value, parts = {}) { + return { + type: "Member", + name, + value, + ...parts + }; + }, + +}; + +/** + * @fileoverview JSON parser + * @author Nicholas C. Zakas + */ + +//----------------------------------------------------------------------------- +// Helpers +//----------------------------------------------------------------------------- + +const DEFAULT_OPTIONS$1 = { + tokens: false, + comments: false, + ranges: false +}; + +/** + * Converts a JSON-encoded string into a JavaScript string, interpreting each + * escape sequence. + * @param {Token} token The string token to convert into a JavaScript string. + * @returns {string} A JavaScript string. + */ +function getStringValue(token) { + + // slice off the quotation marks + let value = token.value.slice(1, -1); + let result = ""; + let escapeIndex = value.indexOf("\\"); + let lastIndex = 0; + + // While there are escapes, interpret them to build up the result + while (escapeIndex >= 0) { + + // append the text that happened before the escape + result += value.slice(lastIndex, escapeIndex); + + // get the character immediately after the \ + const escapeChar = value.charAt(escapeIndex + 1); + + // check for the non-Unicode escape sequences first + if (escapeToChar.has(escapeChar)) { + result += escapeToChar.get(escapeChar); + lastIndex = escapeIndex + 2; + } else if (escapeChar === "u") { + const hexCode = value.slice(escapeIndex + 2, escapeIndex + 6); + if (hexCode.length < 4 || /[^0-9a-f]/i.test(hexCode)) { + throw new ErrorWithLocation( + `Invalid unicode escape \\u${ hexCode}.`, + { + line: token.loc.start.line, + column: token.loc.start.column + escapeIndex, + offset: token.loc.start.offset + escapeIndex + } + ); + } + + result += String.fromCharCode(parseInt(hexCode, 16)); + lastIndex = escapeIndex + 6; + } else { + throw new ErrorWithLocation( + `Invalid escape \\${ escapeChar }.`, + { + line: token.loc.start.line, + column: token.loc.start.column + escapeIndex, + offset: token.loc.start.offset + escapeIndex + } + ); + } + + // find the next escape sequence + escapeIndex = value.indexOf("\\", lastIndex); + } + + // get the last segment of the string value + result += value.slice(lastIndex); + + return result; +} + +/** + * Gets the JavaScript value represented by a JSON token. + * @param {Token} token The JSON token to get a value for. + * @returns {*} A number, string, boolean, or `null`. + */ +function getLiteralValue(token) { + switch (token.type) { + case "Boolean": + return token.value === "true"; + + case "Number": + return Number(token.value); + + case "Null": + return null; + + case "String": + return getStringValue(token); + } +} + +//----------------------------------------------------------------------------- +// Main Function +//----------------------------------------------------------------------------- + +/** + * + * @param {string} text The text to parse. + * @param {boolean} [options.tokens=false] Determines if tokens are returned in + * the AST. + * @param {boolean} [options.comments=false] Determines if comments are allowed + * in the JSON. + * @param {boolean} [options.ranges=false] Determines if ranges will be returned + * in addition to `loc` properties. + * @returns {Object} The AST representing the parsed JSON. + * @throws {Error} When there is a parsing error. + */ +function parse$6(text, options) { + + options = Object.freeze({ + ...DEFAULT_OPTIONS$1, + ...options + }); + + const tokens = tokenize(text, { + comments: !!options.comments, + ranges: !!options.ranges + }); + let tokenIndex = 0; + + function nextNoComments() { + return tokens[tokenIndex++]; + } + + function nextSkipComments() { + const nextToken = tokens[tokenIndex++]; + if (nextToken && nextToken.type.endsWith("Comment")) { + return nextSkipComments(); + } + + return nextToken; + + } + + // determine correct way to evaluate tokens based on presence of comments + const next = options.comments ? nextSkipComments : nextNoComments; + + function assertTokenValue(token, value) { + if (!token || token.value !== value) { + throw new UnexpectedToken(token); + } + } + + function assertTokenType(token, type) { + if (!token || token.type !== type) { + throw new UnexpectedToken(token); + } + } + + function createRange(start, end) { + return options.ranges ? { + range: [start.offset, end.offset] + } : undefined; + } + + function createLiteralNode(token) { + const range = createRange(token.loc.start, token.loc.end); + + return { + type: token.type, + value: getLiteralValue(token), + loc: { + start: { + ...token.loc.start + }, + end: { + ...token.loc.end + } + }, + ...range + }; + } + + + function parseProperty(token) { + assertTokenType(token, "String"); + const name = createLiteralNode(token); + + token = next(); + assertTokenValue(token, ":"); + const value = parseValue(); + const range = createRange(name.loc.start, value.loc.end); + + return types$2.member(name, value, { + loc: { + start: { + ...name.loc.start + }, + end: { + ...value.loc.end + } + }, + ...range + }); + } + + function parseObject(firstToken) { + + // The first token must be a { or else it's an error + assertTokenValue(firstToken, "{"); + + const members = []; + let token = next(); + + if (token && token.value !== "}") { + do { + + // add the value into the array + members.push(parseProperty(token)); + + token = next(); + + if (token.value === ",") { + token = next(); + } else { + break; + } + } while (token); + } + + assertTokenValue(token, "}"); + const range = createRange(firstToken.loc.start, token.loc.end); + + return types$2.object(members, { + loc: { + start: { + ...firstToken.loc.start + }, + end: { + ...token.loc.end + } + }, + ...range + }); + + } + + function parseArray(firstToken) { + + // The first token must be a [ or else it's an error + assertTokenValue(firstToken, "["); + + const elements = []; + let token = next(); + + if (token && token.value !== "]") { + + do { + + // add the value into the array + elements.push(parseValue(token)); + + token = next(); + + if (token.value === ",") { + token = next(); + } else { + break; + } + } while (token); + } + + assertTokenValue(token, "]"); + const range = createRange(firstToken.loc.start, token.loc.end); + + return types$2.array(elements, { + type: "Array", + elements, + loc: { + start: { + ...firstToken.loc.start + }, + end: { + ...token.loc.end + } + }, + ...range + }); + + } + + + + function parseValue(token) { + + token = token || next(); + + switch (token.type) { + case "String": + case "Boolean": + case "Number": + case "Null": + return createLiteralNode(token); + + case "Punctuator": + if (token.value === "{") { + return parseObject(token); + } else if (token.value === "[") { + return parseArray(token); + } + /*falls through*/ + + default: + throw new UnexpectedToken(token); + } + + } + + + const docBody = parseValue(); + + const unexpectedToken = next(); + if (unexpectedToken) { + throw new UnexpectedToken(unexpectedToken); + } + + + const docParts = { + loc: { + start: { + line: 1, + column: 1, + offset: 0 + }, + end: { + ...docBody.loc.end + } + } + }; + + + if (options.tokens) { + docParts.tokens = tokens; + } + + if (options.ranges) { + docParts.range = createRange(docParts.loc.start, docParts.loc.end); + } + + return types$2.document(docBody, docParts); + +} + +/** + * @fileoverview Traversal approaches for Momoa JSON AST. + * @author Nicholas C. Zakas + */ + +//----------------------------------------------------------------------------- +// Data +//----------------------------------------------------------------------------- + +const childKeys = new Map([ + ["Document", ["body"]], + ["Object", ["members"]], + ["Member", ["name", "value"]], + ["Array", ["elements"]], + ["String", []], + ["Number", []], + ["Boolean", []], + ["Null", []] +]); + +//----------------------------------------------------------------------------- +// Helpers +//----------------------------------------------------------------------------- + +/** + * Determines if a given value is an object. + * @param {*} value The value to check. + * @returns {boolean} True if the value is an object, false if not. + */ +function isObject$j(value) { + return value && (typeof value === "object"); +} + +/** + * Determines if a given value is an AST node. + * @param {*} value The value to check. + * @returns {boolean} True if the value is a node, false if not. + */ +function isNode(value) { + return isObject$j(value) && (typeof value.type === "string"); +} + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +/** + * Traverses an AST from the given node. + * @param {Node} root The node to traverse from + * @param {Object} visitor An object with an `enter` and `exit` method. + */ +function traverse$2(root, visitor) { + + /** + * Recursively visits a node. + * @param {Node} node The node to visit. + * @param {Node} parent The parent of the node to visit. + * @returns {void} + */ + function visitNode(node, parent) { + + if (typeof visitor.enter === "function") { + visitor.enter(node, parent); + } + + for (const key of childKeys.get(node.type)) { + const value = node[key]; + + if (isObject$j(value)) { + if (Array.isArray(value)) { + value.forEach(child => visitNode(child, node)); + } else if (isNode(value)) { + visitNode(value, node); + } + } + } + + if (typeof visitor.exit === "function") { + visitor.exit(node, parent); + } + } + + visitNode(root); +} + +/** + * Creates an iterator over the given AST. + * @param {Node} root The root AST node to traverse. + * @param {Function} [filter] A filter function to determine which steps to + * return; + * @returns {Iterator} An iterator over the AST. + */ +function iterator(root, filter = () => true) { + + const traversal = []; + + traverse$2(root, { + enter(node, parent) { + traversal.push({ node, parent, phase: "enter" }); + }, + exit(node, parent) { + traversal.push({ node, parent, phase: "exit" }); + } + }); + + return traversal.filter(filter).values(); +} + +/** + * @fileoverview Evaluator for Momoa AST. + * @author Nicholas C. Zakas + */ + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +/** + * Evaluates a Momoa AST node into a JavaScript value. + * @param {Node} node The node to interpet. + * @returns {*} The JavaScript value for the node. + */ +function evaluate(node) { + switch (node.type) { + case "String": + case "Number": + case "Boolean": + return node.value; + + case "Null": + return null; + + case "Array": + return node.elements.map(evaluate); + + case "Object": { + + const object = {}; + + node.members.forEach(member => { + object[evaluate(member.name)] = evaluate(member.value); + }); + + return object; + } + + case "Document": + return evaluate(node.body); + + case "Property": + throw new Error("Cannot evaluate object property outside of an object."); + + default: + throw new Error(`Unknown node type ${ node.type }.`); + } +} + +/** + * @fileoverview Printer for Momoa AST. + * @author Nicholas C. Zakas + */ + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +/** + * Converts a Momoa AST back into a JSON string. + * @param {Node} node The node to print. + * @param {int} [options.indent=0] The number of spaces to indent each line. If + * greater than 0, then newlines and indents will be added to output. + * @returns {string} The JSON representation of the AST. + */ +function print(node, { indent = 0 } = {}) { + const value = evaluate(node); + return JSON.stringify(value, null, indent); +} + +/** + * @fileoverview File defining the interface of the package. + * @author Nicholas C. Zakas + */ + +api$1.evaluate = evaluate; +api$1.iterator = iterator; +api$1.parse = parse$6; +api$1.print = print; +api$1.tokenize = tokenize; +api$1.traverse = traverse$2; +api$1.types = types$2; + +var helpers = {}; + +var defineProperty$3 = {exports: {}}; + +var toPropertyKey = {exports: {}}; + +var _typeof = {exports: {}}; + +var hasRequired_typeof; + +function require_typeof () { + if (hasRequired_typeof) return _typeof.exports; + hasRequired_typeof = 1; + (function (module) { + function _typeof(o) { + "@babel/helpers - typeof"; + + return (module.exports = _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { + return typeof o; + } : function (o) { + return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; + }, module.exports.__esModule = true, module.exports["default"] = module.exports), _typeof(o); + } + module.exports = _typeof, module.exports.__esModule = true, module.exports["default"] = module.exports; + } (_typeof)); + return _typeof.exports; +} + +var toPrimitive = {exports: {}}; + +var hasRequiredToPrimitive; + +function requireToPrimitive () { + if (hasRequiredToPrimitive) return toPrimitive.exports; + hasRequiredToPrimitive = 1; + (function (module) { + var _typeof = require_typeof()["default"]; + function _toPrimitive(input, hint) { + if (_typeof(input) !== "object" || input === null) return input; + var prim = input[Symbol.toPrimitive]; + if (prim !== undefined) { + var res = prim.call(input, hint || "default"); + if (_typeof(res) !== "object") return res; + throw new TypeError("@@toPrimitive must return a primitive value."); + } + return (hint === "string" ? String : Number)(input); + } + module.exports = _toPrimitive, module.exports.__esModule = true, module.exports["default"] = module.exports; + } (toPrimitive)); + return toPrimitive.exports; +} + +var hasRequiredToPropertyKey; + +function requireToPropertyKey () { + if (hasRequiredToPropertyKey) return toPropertyKey.exports; + hasRequiredToPropertyKey = 1; + (function (module) { + var _typeof = require_typeof()["default"]; + var toPrimitive = requireToPrimitive(); + function _toPropertyKey(arg) { + var key = toPrimitive(arg, "string"); + return _typeof(key) === "symbol" ? key : String(key); + } + module.exports = _toPropertyKey, module.exports.__esModule = true, module.exports["default"] = module.exports; + } (toPropertyKey)); + return toPropertyKey.exports; +} + +var hasRequiredDefineProperty; + +function requireDefineProperty () { + if (hasRequiredDefineProperty) return defineProperty$3.exports; + hasRequiredDefineProperty = 1; + (function (module) { + var toPropertyKey = requireToPropertyKey(); + function _defineProperty(obj, key, value) { + key = toPropertyKey(key); + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + return obj; + } + module.exports = _defineProperty, module.exports.__esModule = true, module.exports["default"] = module.exports; + } (defineProperty$3)); + return defineProperty$3.exports; +} + +var toConsumableArray = {exports: {}}; + +var arrayWithoutHoles = {exports: {}}; + +var arrayLikeToArray = {exports: {}}; + +var hasRequiredArrayLikeToArray; + +function requireArrayLikeToArray () { + if (hasRequiredArrayLikeToArray) return arrayLikeToArray.exports; + hasRequiredArrayLikeToArray = 1; + (function (module) { + 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.exports = _arrayLikeToArray, module.exports.__esModule = true, module.exports["default"] = module.exports; + } (arrayLikeToArray)); + return arrayLikeToArray.exports; +} + +var hasRequiredArrayWithoutHoles; + +function requireArrayWithoutHoles () { + if (hasRequiredArrayWithoutHoles) return arrayWithoutHoles.exports; + hasRequiredArrayWithoutHoles = 1; + (function (module) { + var arrayLikeToArray = requireArrayLikeToArray(); + function _arrayWithoutHoles(arr) { + if (Array.isArray(arr)) return arrayLikeToArray(arr); + } + module.exports = _arrayWithoutHoles, module.exports.__esModule = true, module.exports["default"] = module.exports; + } (arrayWithoutHoles)); + return arrayWithoutHoles.exports; +} + +var iterableToArray = {exports: {}}; + +var hasRequiredIterableToArray; + +function requireIterableToArray () { + if (hasRequiredIterableToArray) return iterableToArray.exports; + hasRequiredIterableToArray = 1; + (function (module) { + function _iterableToArray(iter) { + if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); + } + module.exports = _iterableToArray, module.exports.__esModule = true, module.exports["default"] = module.exports; + } (iterableToArray)); + return iterableToArray.exports; +} + +var unsupportedIterableToArray = {exports: {}}; + +var hasRequiredUnsupportedIterableToArray; + +function requireUnsupportedIterableToArray () { + if (hasRequiredUnsupportedIterableToArray) return unsupportedIterableToArray.exports; + hasRequiredUnsupportedIterableToArray = 1; + (function (module) { + var arrayLikeToArray = requireArrayLikeToArray(); + 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); + } + module.exports = _unsupportedIterableToArray, module.exports.__esModule = true, module.exports["default"] = module.exports; + } (unsupportedIterableToArray)); + return unsupportedIterableToArray.exports; +} + +var nonIterableSpread = {exports: {}}; + +var hasRequiredNonIterableSpread; + +function requireNonIterableSpread () { + if (hasRequiredNonIterableSpread) return nonIterableSpread.exports; + hasRequiredNonIterableSpread = 1; + (function (module) { + 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."); + } + module.exports = _nonIterableSpread, module.exports.__esModule = true, module.exports["default"] = module.exports; + } (nonIterableSpread)); + return nonIterableSpread.exports; +} + +var hasRequiredToConsumableArray; + +function requireToConsumableArray () { + if (hasRequiredToConsumableArray) return toConsumableArray.exports; + hasRequiredToConsumableArray = 1; + (function (module) { + var arrayWithoutHoles = requireArrayWithoutHoles(); + var iterableToArray = requireIterableToArray(); + var unsupportedIterableToArray = requireUnsupportedIterableToArray(); + var nonIterableSpread = requireNonIterableSpread(); + function _toConsumableArray(arr) { + return arrayWithoutHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableSpread(); + } + module.exports = _toConsumableArray, module.exports.__esModule = true, module.exports["default"] = module.exports; + } (toConsumableArray)); + return toConsumableArray.exports; +} + +var slicedToArray = {exports: {}}; + +var arrayWithHoles = {exports: {}}; + +var hasRequiredArrayWithHoles; + +function requireArrayWithHoles () { + if (hasRequiredArrayWithHoles) return arrayWithHoles.exports; + hasRequiredArrayWithHoles = 1; + (function (module) { + function _arrayWithHoles(arr) { + if (Array.isArray(arr)) return arr; + } + module.exports = _arrayWithHoles, module.exports.__esModule = true, module.exports["default"] = module.exports; + } (arrayWithHoles)); + return arrayWithHoles.exports; +} + +var iterableToArrayLimit = {exports: {}}; + +var hasRequiredIterableToArrayLimit; + +function requireIterableToArrayLimit () { + if (hasRequiredIterableToArrayLimit) return iterableToArrayLimit.exports; + hasRequiredIterableToArrayLimit = 1; + (function (module) { + function _iterableToArrayLimit(r, l) { + var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; + if (null != t) { + var e, + n, + i, + u, + a = [], + f = !0, + o = !1; + try { + if (i = (t = t.call(r)).next, 0 === l) { + if (Object(t) !== t) return; + f = !1; + } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); + } catch (r) { + o = !0, n = r; + } finally { + try { + if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; + } finally { + if (o) throw n; + } + } + return a; + } + } + module.exports = _iterableToArrayLimit, module.exports.__esModule = true, module.exports["default"] = module.exports; + } (iterableToArrayLimit)); + return iterableToArrayLimit.exports; +} + +var nonIterableRest = {exports: {}}; + +var hasRequiredNonIterableRest; + +function requireNonIterableRest () { + if (hasRequiredNonIterableRest) return nonIterableRest.exports; + hasRequiredNonIterableRest = 1; + (function (module) { + 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."); + } + module.exports = _nonIterableRest, module.exports.__esModule = true, module.exports["default"] = module.exports; + } (nonIterableRest)); + return nonIterableRest.exports; +} + +var hasRequiredSlicedToArray; + +function requireSlicedToArray () { + if (hasRequiredSlicedToArray) return slicedToArray.exports; + hasRequiredSlicedToArray = 1; + (function (module) { + var arrayWithHoles = requireArrayWithHoles(); + var iterableToArrayLimit = requireIterableToArrayLimit(); + var unsupportedIterableToArray = requireUnsupportedIterableToArray(); + var nonIterableRest = requireNonIterableRest(); + function _slicedToArray(arr, i) { + return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || unsupportedIterableToArray(arr, i) || nonIterableRest(); + } + module.exports = _slicedToArray, module.exports.__esModule = true, module.exports["default"] = module.exports; + } (slicedToArray)); + return slicedToArray.exports; +} + +var utils$4 = {}; + +var hasRequiredUtils$1; + +function requireUtils$1 () { + if (hasRequiredUtils$1) return utils$4; + hasRequiredUtils$1 = 1; + + Object.defineProperty(utils$4, "__esModule", { + value: true + }); + utils$4.notUndefined = utils$4.isRequiredError = utils$4.isEnumError = utils$4.isAnyOfError = utils$4.getSiblings = utils$4.getErrors = utils$4.getChildren = utils$4.concatAll = void 0; + // Basic + var eq = function eq(x) { + return function (y) { + return x === y; + }; + }; + var not = function not(fn) { + return function (x) { + return !fn(x); + }; + }; + var getValues = function getValues(o) { + return Object.values(o); + }; + var notUndefined = function notUndefined(x) { + return x !== undefined; + }; + + // Error + utils$4.notUndefined = notUndefined; + var isXError = function isXError(x) { + return function (error) { + return error.keyword === x; + }; + }; + var isRequiredError = isXError('required'); + utils$4.isRequiredError = isRequiredError; + var isAnyOfError = isXError('anyOf'); + utils$4.isAnyOfError = isAnyOfError; + var isEnumError = isXError('enum'); + utils$4.isEnumError = isEnumError; + var getErrors = function getErrors(node) { + return node && node.errors || []; + }; + + // Node + utils$4.getErrors = getErrors; + var getChildren = function getChildren(node) { + return node && getValues(node.children) || []; + }; + utils$4.getChildren = getChildren; + var getSiblings = function getSiblings(parent /*: Node */) { + return function /*: $ReadOnlyArray<Node> */ + (node /*: Node */) { + return getChildren(parent).filter(not(eq(node))); + }; + }; + utils$4.getSiblings = getSiblings; + var concatAll = /* ::<T> */ + + function concatAll(xs /*: $ReadOnlyArray<T> */) { + return function /* : $ReadOnlyArray<T> */ + (ys /* : $ReadOnlyArray<T> */) { + return ys.reduce(function (zs, z) { + return zs.concat(z); + }, xs); + }; + }; + utils$4.concatAll = concatAll; + return utils$4; +} + +var validationErrors = {}; + +var additionalProp = {exports: {}}; + +var taggedTemplateLiteral = {exports: {}}; + +var hasRequiredTaggedTemplateLiteral; + +function requireTaggedTemplateLiteral () { + if (hasRequiredTaggedTemplateLiteral) return taggedTemplateLiteral.exports; + hasRequiredTaggedTemplateLiteral = 1; + (function (module) { + function _taggedTemplateLiteral(strings, raw) { + if (!raw) { + raw = strings.slice(0); + } + return Object.freeze(Object.defineProperties(strings, { + raw: { + value: Object.freeze(raw) + } + })); + } + module.exports = _taggedTemplateLiteral, module.exports.__esModule = true, module.exports["default"] = module.exports; + } (taggedTemplateLiteral)); + return taggedTemplateLiteral.exports; +} + +var classCallCheck = {exports: {}}; + +var hasRequiredClassCallCheck; + +function requireClassCallCheck () { + if (hasRequiredClassCallCheck) return classCallCheck.exports; + hasRequiredClassCallCheck = 1; + (function (module) { + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } + module.exports = _classCallCheck, module.exports.__esModule = true, module.exports["default"] = module.exports; + } (classCallCheck)); + return classCallCheck.exports; +} + +var createClass = {exports: {}}; + +var hasRequiredCreateClass; + +function requireCreateClass () { + if (hasRequiredCreateClass) return createClass.exports; + hasRequiredCreateClass = 1; + (function (module) { + var toPropertyKey = requireToPropertyKey(); + function _defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ("value" in descriptor) descriptor.writable = true; + Object.defineProperty(target, toPropertyKey(descriptor.key), descriptor); + } + } + function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + Object.defineProperty(Constructor, "prototype", { + writable: false + }); + return Constructor; + } + module.exports = _createClass, module.exports.__esModule = true, module.exports["default"] = module.exports; + } (createClass)); + return createClass.exports; +} + +var inherits$2 = {exports: {}}; + +var setPrototypeOf = {exports: {}}; + +var hasRequiredSetPrototypeOf; + +function requireSetPrototypeOf () { + if (hasRequiredSetPrototypeOf) return setPrototypeOf.exports; + hasRequiredSetPrototypeOf = 1; + (function (module) { + function _setPrototypeOf(o, p) { + module.exports = _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { + o.__proto__ = p; + return o; + }, module.exports.__esModule = true, module.exports["default"] = module.exports; + return _setPrototypeOf(o, p); + } + module.exports = _setPrototypeOf, module.exports.__esModule = true, module.exports["default"] = module.exports; + } (setPrototypeOf)); + return setPrototypeOf.exports; +} + +var hasRequiredInherits; + +function requireInherits () { + if (hasRequiredInherits) return inherits$2.exports; + hasRequiredInherits = 1; + (function (module) { + var setPrototypeOf = requireSetPrototypeOf(); + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError("Super expression must either be null or a function"); + } + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { + value: subClass, + writable: true, + configurable: true + } + }); + Object.defineProperty(subClass, "prototype", { + writable: false + }); + if (superClass) setPrototypeOf(subClass, superClass); + } + module.exports = _inherits, module.exports.__esModule = true, module.exports["default"] = module.exports; + } (inherits$2)); + return inherits$2.exports; +} + +var possibleConstructorReturn = {exports: {}}; + +var assertThisInitialized = {exports: {}}; + +var hasRequiredAssertThisInitialized; + +function requireAssertThisInitialized () { + if (hasRequiredAssertThisInitialized) return assertThisInitialized.exports; + hasRequiredAssertThisInitialized = 1; + (function (module) { + function _assertThisInitialized(self) { + if (self === void 0) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + return self; + } + module.exports = _assertThisInitialized, module.exports.__esModule = true, module.exports["default"] = module.exports; + } (assertThisInitialized)); + return assertThisInitialized.exports; +} + +var hasRequiredPossibleConstructorReturn; + +function requirePossibleConstructorReturn () { + if (hasRequiredPossibleConstructorReturn) return possibleConstructorReturn.exports; + hasRequiredPossibleConstructorReturn = 1; + (function (module) { + var _typeof = require_typeof()["default"]; + var assertThisInitialized = requireAssertThisInitialized(); + function _possibleConstructorReturn(self, call) { + if (call && (_typeof(call) === "object" || typeof call === "function")) { + return call; + } else if (call !== void 0) { + throw new TypeError("Derived constructors may only return object or undefined"); + } + return assertThisInitialized(self); + } + module.exports = _possibleConstructorReturn, module.exports.__esModule = true, module.exports["default"] = module.exports; + } (possibleConstructorReturn)); + return possibleConstructorReturn.exports; +} + +var getPrototypeOf = {exports: {}}; + +var hasRequiredGetPrototypeOf; + +function requireGetPrototypeOf () { + if (hasRequiredGetPrototypeOf) return getPrototypeOf.exports; + hasRequiredGetPrototypeOf = 1; + (function (module) { + function _getPrototypeOf(o) { + module.exports = _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { + return o.__proto__ || Object.getPrototypeOf(o); + }, module.exports.__esModule = true, module.exports["default"] = module.exports; + return _getPrototypeOf(o); + } + module.exports = _getPrototypeOf, module.exports.__esModule = true, module.exports["default"] = module.exports; + } (getPrototypeOf)); + return getPrototypeOf.exports; +} + +var base = {exports: {}}; + +var lib$e = {}; + +var lib$d = {}; + +var jsTokens = {}; + +var hasRequiredJsTokens; + +function requireJsTokens () { + if (hasRequiredJsTokens) return jsTokens; + hasRequiredJsTokens = 1; + // Copyright 2014, 2015, 2016, 2017, 2018 Simon Lydell + // License: MIT. (See LICENSE.) + + Object.defineProperty(jsTokens, "__esModule", { + value: true + }); + + // This regex comes from regex.coffee, and is inserted here by generate-index.js + // (run `npm run build`). + jsTokens.default = /((['"])(?:(?!\2|\\).|\\(?:\r\n|[\s\S]))*(\2)?|`(?:[^`\\$]|\\[\s\S]|\$(?!\{)|\$\{(?:[^{}]|\{[^}]*\}?)*\}?)*(`)?)|(\/\/.*)|(\/\*(?:[^*]|\*(?!\/))*(\*\/)?)|(\/(?!\*)(?:\[(?:(?![\]\\]).|\\.)*\]|(?![\/\]\\]).|\\.)+\/(?:(?!\s*(?:\b|[\u0080-\uFFFF$\\'"~({]|[+\-!](?!=)|\.?\d))|[gmiyus]{1,6}\b(?![\u0080-\uFFFF$\\]|\s*(?:[+\-*%&|^<>!=?({]|\/(?![\/*])))))|(0[xX][\da-fA-F]+|0[oO][0-7]+|0[bB][01]+|(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?)|((?!\d)(?:(?!\s)[$\w\u0080-\uFFFF]|\\u[\da-fA-F]{4}|\\u\{[\da-fA-F]+\})+)|(--|\+\+|&&|\|\||=>|\.{3}|(?:[+\-\/%&|^]|\*{1,2}|<{1,2}|>{1,3}|!=?|={1,2})=?|[?~.,:;[\](){}])|(\s+)|(^$|[\s\S])/g; + + jsTokens.matchToToken = function(match) { + var token = {type: "invalid", value: match[0], closed: undefined}; + if (match[ 1]) token.type = "string" , token.closed = !!(match[3] || match[4]); + else if (match[ 5]) token.type = "comment"; + else if (match[ 6]) token.type = "comment", token.closed = !!match[7]; + else if (match[ 8]) token.type = "regex"; + else if (match[ 9]) token.type = "number"; + else if (match[10]) token.type = "name"; + else if (match[11]) token.type = "punctuator"; + else if (match[12]) token.type = "whitespace"; + return token + }; + return jsTokens; +} + +var lib$c = {}; + +var identifier = {}; + +var hasRequiredIdentifier; + +function requireIdentifier () { + if (hasRequiredIdentifier) return identifier; + hasRequiredIdentifier = 1; + + Object.defineProperty(identifier, "__esModule", { + value: true + }); + identifier.isIdentifierChar = isIdentifierChar; + identifier.isIdentifierName = isIdentifierName; + identifier.isIdentifierStart = isIdentifierStart; + let nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u0870-\u0887\u0889-\u088e\u08a0-\u08c9\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c5d\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cdd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u1711\u171f-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4c\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7ca\ua7d0\ua7d1\ua7d3\ua7d5-\ua7d9\ua7f2-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc"; + let nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u0898-\u089f\u08ca-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3c\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0cf3\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ece\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u180f-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf-\u1ace\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f"; + const nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]"); + const nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]"); + nonASCIIidentifierStartChars = nonASCIIidentifierChars = null; + const astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 13, 10, 2, 14, 2, 6, 2, 1, 2, 10, 2, 14, 2, 6, 2, 1, 68, 310, 10, 21, 11, 7, 25, 5, 2, 41, 2, 8, 70, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 349, 41, 7, 1, 79, 28, 11, 0, 9, 21, 43, 17, 47, 20, 28, 22, 13, 52, 58, 1, 3, 0, 14, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 20, 1, 64, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 159, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 38, 6, 186, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 19, 72, 264, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 328, 18, 16, 0, 2, 12, 2, 33, 125, 0, 80, 921, 103, 110, 18, 195, 2637, 96, 16, 1071, 18, 5, 4026, 582, 8634, 568, 8, 30, 18, 78, 18, 29, 19, 47, 17, 3, 32, 20, 6, 18, 689, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 1237, 43, 8, 8936, 3, 2, 6, 2, 1, 2, 290, 16, 0, 30, 2, 3, 0, 15, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 1845, 30, 7, 5, 262, 61, 147, 44, 11, 6, 17, 0, 322, 29, 19, 43, 485, 27, 757, 6, 2, 3, 2, 1, 2, 14, 2, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42719, 33, 4153, 7, 221, 3, 5761, 15, 7472, 3104, 541, 1507, 4938, 6, 4191]; + const astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 370, 1, 81, 2, 71, 10, 50, 3, 123, 2, 54, 14, 32, 10, 3, 1, 11, 3, 46, 10, 8, 0, 46, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 3, 0, 158, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 193, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 84, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 406, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 330, 3, 10, 1, 2, 0, 49, 6, 4, 4, 14, 9, 5351, 0, 7, 14, 13835, 9, 87, 9, 39, 4, 60, 6, 26, 9, 1014, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 4706, 45, 3, 22, 543, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 101, 0, 161, 6, 10, 9, 357, 0, 62, 13, 499, 13, 983, 6, 110, 6, 6, 9, 4759, 9, 787719, 239]; + function isInAstralSet(code, set) { + let pos = 0x10000; + for (let i = 0, length = set.length; i < length; i += 2) { + pos += set[i]; + if (pos > code) return false; + pos += set[i + 1]; + if (pos >= code) return true; + } + return false; + } + function isIdentifierStart(code) { + if (code < 65) return code === 36; + if (code <= 90) return true; + if (code < 97) return code === 95; + if (code <= 122) return true; + if (code <= 0xffff) { + return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)); + } + return isInAstralSet(code, astralIdentifierStartCodes); + } + function isIdentifierChar(code) { + if (code < 48) return code === 36; + if (code < 58) return true; + if (code < 65) return false; + if (code <= 90) return true; + if (code < 97) return code === 95; + if (code <= 122) return true; + if (code <= 0xffff) { + return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)); + } + return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes); + } + function isIdentifierName(name) { + let isFirst = true; + for (let i = 0; i < name.length; i++) { + let cp = name.charCodeAt(i); + if ((cp & 0xfc00) === 0xd800 && i + 1 < name.length) { + const trail = name.charCodeAt(++i); + if ((trail & 0xfc00) === 0xdc00) { + cp = 0x10000 + ((cp & 0x3ff) << 10) + (trail & 0x3ff); + } + } + if (isFirst) { + isFirst = false; + if (!isIdentifierStart(cp)) { + return false; + } + } else if (!isIdentifierChar(cp)) { + return false; + } + } + return !isFirst; + } + + + return identifier; +} + +var keyword$1 = {}; + +var hasRequiredKeyword$1; + +function requireKeyword$1 () { + if (hasRequiredKeyword$1) return keyword$1; + hasRequiredKeyword$1 = 1; + + Object.defineProperty(keyword$1, "__esModule", { + value: true + }); + keyword$1.isKeyword = isKeyword; + keyword$1.isReservedWord = isReservedWord; + keyword$1.isStrictBindOnlyReservedWord = isStrictBindOnlyReservedWord; + keyword$1.isStrictBindReservedWord = isStrictBindReservedWord; + keyword$1.isStrictReservedWord = isStrictReservedWord; + const reservedWords = { + keyword: ["break", "case", "catch", "continue", "debugger", "default", "do", "else", "finally", "for", "function", "if", "return", "switch", "throw", "try", "var", "const", "while", "with", "new", "this", "super", "class", "extends", "export", "import", "null", "true", "false", "in", "instanceof", "typeof", "void", "delete"], + strict: ["implements", "interface", "let", "package", "private", "protected", "public", "static", "yield"], + strictBind: ["eval", "arguments"] + }; + const keywords = new Set(reservedWords.keyword); + const reservedWordsStrictSet = new Set(reservedWords.strict); + const reservedWordsStrictBindSet = new Set(reservedWords.strictBind); + function isReservedWord(word, inModule) { + return inModule && word === "await" || word === "enum"; + } + function isStrictReservedWord(word, inModule) { + return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word); + } + function isStrictBindOnlyReservedWord(word) { + return reservedWordsStrictBindSet.has(word); + } + function isStrictBindReservedWord(word, inModule) { + return isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word); + } + function isKeyword(word) { + return keywords.has(word); + } + + + return keyword$1; +} + +var hasRequiredLib$2; + +function requireLib$2 () { + if (hasRequiredLib$2) return lib$c; + hasRequiredLib$2 = 1; + (function (exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + Object.defineProperty(exports, "isIdentifierChar", { + enumerable: true, + get: function () { + return _identifier.isIdentifierChar; + } + }); + Object.defineProperty(exports, "isIdentifierName", { + enumerable: true, + get: function () { + return _identifier.isIdentifierName; + } + }); + Object.defineProperty(exports, "isIdentifierStart", { + enumerable: true, + get: function () { + return _identifier.isIdentifierStart; + } + }); + Object.defineProperty(exports, "isKeyword", { + enumerable: true, + get: function () { + return _keyword.isKeyword; + } + }); + Object.defineProperty(exports, "isReservedWord", { + enumerable: true, + get: function () { + return _keyword.isReservedWord; + } + }); + Object.defineProperty(exports, "isStrictBindOnlyReservedWord", { + enumerable: true, + get: function () { + return _keyword.isStrictBindOnlyReservedWord; + } + }); + Object.defineProperty(exports, "isStrictBindReservedWord", { + enumerable: true, + get: function () { + return _keyword.isStrictBindReservedWord; + } + }); + Object.defineProperty(exports, "isStrictReservedWord", { + enumerable: true, + get: function () { + return _keyword.isStrictReservedWord; + } + }); + var _identifier = requireIdentifier(); + var _keyword = requireKeyword$1(); + + + } (lib$c)); + return lib$c; +} + +var chalk$3 = {exports: {}}; + +var escapeStringRegexp$1; +var hasRequiredEscapeStringRegexp$1; + +function requireEscapeStringRegexp$1 () { + if (hasRequiredEscapeStringRegexp$1) return escapeStringRegexp$1; + hasRequiredEscapeStringRegexp$1 = 1; + + var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; + + escapeStringRegexp$1 = function (str) { + if (typeof str !== 'string') { + throw new TypeError('Expected a string'); + } + + return str.replace(matchOperatorsRe, '\\$&'); + }; + return escapeStringRegexp$1; +} + +var ansiStyles$6 = {exports: {}}; + +var conversions$4 = {exports: {}}; + +var colorName$3; +var hasRequiredColorName$3; + +function requireColorName$3 () { + if (hasRequiredColorName$3) return colorName$3; + hasRequiredColorName$3 = 1; + + colorName$3 = { + "aliceblue": [240, 248, 255], + "antiquewhite": [250, 235, 215], + "aqua": [0, 255, 255], + "aquamarine": [127, 255, 212], + "azure": [240, 255, 255], + "beige": [245, 245, 220], + "bisque": [255, 228, 196], + "black": [0, 0, 0], + "blanchedalmond": [255, 235, 205], + "blue": [0, 0, 255], + "blueviolet": [138, 43, 226], + "brown": [165, 42, 42], + "burlywood": [222, 184, 135], + "cadetblue": [95, 158, 160], + "chartreuse": [127, 255, 0], + "chocolate": [210, 105, 30], + "coral": [255, 127, 80], + "cornflowerblue": [100, 149, 237], + "cornsilk": [255, 248, 220], + "crimson": [220, 20, 60], + "cyan": [0, 255, 255], + "darkblue": [0, 0, 139], + "darkcyan": [0, 139, 139], + "darkgoldenrod": [184, 134, 11], + "darkgray": [169, 169, 169], + "darkgreen": [0, 100, 0], + "darkgrey": [169, 169, 169], + "darkkhaki": [189, 183, 107], + "darkmagenta": [139, 0, 139], + "darkolivegreen": [85, 107, 47], + "darkorange": [255, 140, 0], + "darkorchid": [153, 50, 204], + "darkred": [139, 0, 0], + "darksalmon": [233, 150, 122], + "darkseagreen": [143, 188, 143], + "darkslateblue": [72, 61, 139], + "darkslategray": [47, 79, 79], + "darkslategrey": [47, 79, 79], + "darkturquoise": [0, 206, 209], + "darkviolet": [148, 0, 211], + "deeppink": [255, 20, 147], + "deepskyblue": [0, 191, 255], + "dimgray": [105, 105, 105], + "dimgrey": [105, 105, 105], + "dodgerblue": [30, 144, 255], + "firebrick": [178, 34, 34], + "floralwhite": [255, 250, 240], + "forestgreen": [34, 139, 34], + "fuchsia": [255, 0, 255], + "gainsboro": [220, 220, 220], + "ghostwhite": [248, 248, 255], + "gold": [255, 215, 0], + "goldenrod": [218, 165, 32], + "gray": [128, 128, 128], + "green": [0, 128, 0], + "greenyellow": [173, 255, 47], + "grey": [128, 128, 128], + "honeydew": [240, 255, 240], + "hotpink": [255, 105, 180], + "indianred": [205, 92, 92], + "indigo": [75, 0, 130], + "ivory": [255, 255, 240], + "khaki": [240, 230, 140], + "lavender": [230, 230, 250], + "lavenderblush": [255, 240, 245], + "lawngreen": [124, 252, 0], + "lemonchiffon": [255, 250, 205], + "lightblue": [173, 216, 230], + "lightcoral": [240, 128, 128], + "lightcyan": [224, 255, 255], + "lightgoldenrodyellow": [250, 250, 210], + "lightgray": [211, 211, 211], + "lightgreen": [144, 238, 144], + "lightgrey": [211, 211, 211], + "lightpink": [255, 182, 193], + "lightsalmon": [255, 160, 122], + "lightseagreen": [32, 178, 170], + "lightskyblue": [135, 206, 250], + "lightslategray": [119, 136, 153], + "lightslategrey": [119, 136, 153], + "lightsteelblue": [176, 196, 222], + "lightyellow": [255, 255, 224], + "lime": [0, 255, 0], + "limegreen": [50, 205, 50], + "linen": [250, 240, 230], + "magenta": [255, 0, 255], + "maroon": [128, 0, 0], + "mediumaquamarine": [102, 205, 170], + "mediumblue": [0, 0, 205], + "mediumorchid": [186, 85, 211], + "mediumpurple": [147, 112, 219], + "mediumseagreen": [60, 179, 113], + "mediumslateblue": [123, 104, 238], + "mediumspringgreen": [0, 250, 154], + "mediumturquoise": [72, 209, 204], + "mediumvioletred": [199, 21, 133], + "midnightblue": [25, 25, 112], + "mintcream": [245, 255, 250], + "mistyrose": [255, 228, 225], + "moccasin": [255, 228, 181], + "navajowhite": [255, 222, 173], + "navy": [0, 0, 128], + "oldlace": [253, 245, 230], + "olive": [128, 128, 0], + "olivedrab": [107, 142, 35], + "orange": [255, 165, 0], + "orangered": [255, 69, 0], + "orchid": [218, 112, 214], + "palegoldenrod": [238, 232, 170], + "palegreen": [152, 251, 152], + "paleturquoise": [175, 238, 238], + "palevioletred": [219, 112, 147], + "papayawhip": [255, 239, 213], + "peachpuff": [255, 218, 185], + "peru": [205, 133, 63], + "pink": [255, 192, 203], + "plum": [221, 160, 221], + "powderblue": [176, 224, 230], + "purple": [128, 0, 128], + "rebeccapurple": [102, 51, 153], + "red": [255, 0, 0], + "rosybrown": [188, 143, 143], + "royalblue": [65, 105, 225], + "saddlebrown": [139, 69, 19], + "salmon": [250, 128, 114], + "sandybrown": [244, 164, 96], + "seagreen": [46, 139, 87], + "seashell": [255, 245, 238], + "sienna": [160, 82, 45], + "silver": [192, 192, 192], + "skyblue": [135, 206, 235], + "slateblue": [106, 90, 205], + "slategray": [112, 128, 144], + "slategrey": [112, 128, 144], + "snow": [255, 250, 250], + "springgreen": [0, 255, 127], + "steelblue": [70, 130, 180], + "tan": [210, 180, 140], + "teal": [0, 128, 128], + "thistle": [216, 191, 216], + "tomato": [255, 99, 71], + "turquoise": [64, 224, 208], + "violet": [238, 130, 238], + "wheat": [245, 222, 179], + "white": [255, 255, 255], + "whitesmoke": [245, 245, 245], + "yellow": [255, 255, 0], + "yellowgreen": [154, 205, 50] + }; + return colorName$3; +} + +/* MIT license */ + +var hasRequiredConversions$3; + +function requireConversions$3 () { + if (hasRequiredConversions$3) return conversions$4.exports; + hasRequiredConversions$3 = 1; + var cssKeywords = requireColorName$3(); + + // NOTE: conversions should only return primitive values (i.e. arrays, or + // values that give correct `typeof` results). + // do not use box values types (i.e. Number(), String(), etc.) + + var reverseKeywords = {}; + for (var key in cssKeywords) { + if (cssKeywords.hasOwnProperty(key)) { + reverseKeywords[cssKeywords[key]] = key; + } + } + + var convert = conversions$4.exports = { + rgb: {channels: 3, labels: 'rgb'}, + hsl: {channels: 3, labels: 'hsl'}, + hsv: {channels: 3, labels: 'hsv'}, + hwb: {channels: 3, labels: 'hwb'}, + cmyk: {channels: 4, labels: 'cmyk'}, + xyz: {channels: 3, labels: 'xyz'}, + lab: {channels: 3, labels: 'lab'}, + lch: {channels: 3, labels: 'lch'}, + hex: {channels: 1, labels: ['hex']}, + keyword: {channels: 1, labels: ['keyword']}, + ansi16: {channels: 1, labels: ['ansi16']}, + ansi256: {channels: 1, labels: ['ansi256']}, + hcg: {channels: 3, labels: ['h', 'c', 'g']}, + apple: {channels: 3, labels: ['r16', 'g16', 'b16']}, + gray: {channels: 1, labels: ['gray']} + }; + + // hide .channels and .labels properties + for (var model in convert) { + if (convert.hasOwnProperty(model)) { + if (!('channels' in convert[model])) { + throw new Error('missing channels property: ' + model); + } + + if (!('labels' in convert[model])) { + throw new Error('missing channel labels property: ' + model); + } + + if (convert[model].labels.length !== convert[model].channels) { + throw new Error('channel and label counts mismatch: ' + model); + } + + var channels = convert[model].channels; + var labels = convert[model].labels; + delete convert[model].channels; + delete convert[model].labels; + Object.defineProperty(convert[model], 'channels', {value: channels}); + Object.defineProperty(convert[model], 'labels', {value: labels}); + } + } + + convert.rgb.hsl = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var min = Math.min(r, g, b); + var max = Math.max(r, g, b); + var delta = max - min; + var h; + var s; + var l; + + if (max === min) { + h = 0; + } else if (r === max) { + h = (g - b) / delta; + } else if (g === max) { + h = 2 + (b - r) / delta; + } else if (b === max) { + h = 4 + (r - g) / delta; + } + + h = Math.min(h * 60, 360); + + if (h < 0) { + h += 360; + } + + l = (min + max) / 2; + + if (max === min) { + s = 0; + } else if (l <= 0.5) { + s = delta / (max + min); + } else { + s = delta / (2 - max - min); + } + + return [h, s * 100, l * 100]; + }; + + convert.rgb.hsv = function (rgb) { + var rdif; + var gdif; + var bdif; + var h; + var s; + + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var v = Math.max(r, g, b); + var diff = v - Math.min(r, g, b); + var diffc = function (c) { + return (v - c) / 6 / diff + 1 / 2; + }; + + if (diff === 0) { + h = s = 0; + } else { + s = diff / v; + rdif = diffc(r); + gdif = diffc(g); + bdif = diffc(b); + + if (r === v) { + h = bdif - gdif; + } else if (g === v) { + h = (1 / 3) + rdif - bdif; + } else if (b === v) { + h = (2 / 3) + gdif - rdif; + } + if (h < 0) { + h += 1; + } else if (h > 1) { + h -= 1; + } + } + + return [ + h * 360, + s * 100, + v * 100 + ]; + }; + + convert.rgb.hwb = function (rgb) { + var r = rgb[0]; + var g = rgb[1]; + var b = rgb[2]; + var h = convert.rgb.hsl(rgb)[0]; + var w = 1 / 255 * Math.min(r, Math.min(g, b)); + + b = 1 - 1 / 255 * Math.max(r, Math.max(g, b)); + + return [h, w * 100, b * 100]; + }; + + convert.rgb.cmyk = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var c; + var m; + var y; + var k; + + k = Math.min(1 - r, 1 - g, 1 - b); + c = (1 - r - k) / (1 - k) || 0; + m = (1 - g - k) / (1 - k) || 0; + y = (1 - b - k) / (1 - k) || 0; + + return [c * 100, m * 100, y * 100, k * 100]; + }; + + /** + * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance + * */ + function comparativeDistance(x, y) { + return ( + Math.pow(x[0] - y[0], 2) + + Math.pow(x[1] - y[1], 2) + + Math.pow(x[2] - y[2], 2) + ); + } + + convert.rgb.keyword = function (rgb) { + var reversed = reverseKeywords[rgb]; + if (reversed) { + return reversed; + } + + var currentClosestDistance = Infinity; + var currentClosestKeyword; + + for (var keyword in cssKeywords) { + if (cssKeywords.hasOwnProperty(keyword)) { + var value = cssKeywords[keyword]; + + // Compute comparative distance + var distance = comparativeDistance(rgb, value); + + // Check if its less, if so set as closest + if (distance < currentClosestDistance) { + currentClosestDistance = distance; + currentClosestKeyword = keyword; + } + } + } + + return currentClosestKeyword; + }; + + convert.keyword.rgb = function (keyword) { + return cssKeywords[keyword]; + }; + + convert.rgb.xyz = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + + // assume sRGB + r = r > 0.04045 ? Math.pow(((r + 0.055) / 1.055), 2.4) : (r / 12.92); + g = g > 0.04045 ? Math.pow(((g + 0.055) / 1.055), 2.4) : (g / 12.92); + b = b > 0.04045 ? Math.pow(((b + 0.055) / 1.055), 2.4) : (b / 12.92); + + var x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805); + var y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722); + var z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505); + + return [x * 100, y * 100, z * 100]; + }; + + convert.rgb.lab = function (rgb) { + var xyz = convert.rgb.xyz(rgb); + var x = xyz[0]; + var y = xyz[1]; + var z = xyz[2]; + var l; + var a; + var b; + + x /= 95.047; + y /= 100; + z /= 108.883; + + x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116); + y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116); + z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116); + + l = (116 * y) - 16; + a = 500 * (x - y); + b = 200 * (y - z); + + return [l, a, b]; + }; + + convert.hsl.rgb = function (hsl) { + var h = hsl[0] / 360; + var s = hsl[1] / 100; + var l = hsl[2] / 100; + var t1; + var t2; + var t3; + var rgb; + var val; + + if (s === 0) { + val = l * 255; + return [val, val, val]; + } + + if (l < 0.5) { + t2 = l * (1 + s); + } else { + t2 = l + s - l * s; + } + + t1 = 2 * l - t2; + + rgb = [0, 0, 0]; + for (var i = 0; i < 3; i++) { + t3 = h + 1 / 3 * -(i - 1); + if (t3 < 0) { + t3++; + } + if (t3 > 1) { + t3--; + } + + if (6 * t3 < 1) { + val = t1 + (t2 - t1) * 6 * t3; + } else if (2 * t3 < 1) { + val = t2; + } else if (3 * t3 < 2) { + val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; + } else { + val = t1; + } + + rgb[i] = val * 255; + } + + return rgb; + }; + + convert.hsl.hsv = function (hsl) { + var h = hsl[0]; + var s = hsl[1] / 100; + var l = hsl[2] / 100; + var smin = s; + var lmin = Math.max(l, 0.01); + var sv; + var v; + + l *= 2; + s *= (l <= 1) ? l : 2 - l; + smin *= lmin <= 1 ? lmin : 2 - lmin; + v = (l + s) / 2; + sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s); + + return [h, sv * 100, v * 100]; + }; + + convert.hsv.rgb = function (hsv) { + var h = hsv[0] / 60; + var s = hsv[1] / 100; + var v = hsv[2] / 100; + var hi = Math.floor(h) % 6; + + var f = h - Math.floor(h); + var p = 255 * v * (1 - s); + var q = 255 * v * (1 - (s * f)); + var t = 255 * v * (1 - (s * (1 - f))); + v *= 255; + + switch (hi) { + case 0: + return [v, t, p]; + case 1: + return [q, v, p]; + case 2: + return [p, v, t]; + case 3: + return [p, q, v]; + case 4: + return [t, p, v]; + case 5: + return [v, p, q]; + } + }; + + convert.hsv.hsl = function (hsv) { + var h = hsv[0]; + var s = hsv[1] / 100; + var v = hsv[2] / 100; + var vmin = Math.max(v, 0.01); + var lmin; + var sl; + var l; + + l = (2 - s) * v; + lmin = (2 - s) * vmin; + sl = s * vmin; + sl /= (lmin <= 1) ? lmin : 2 - lmin; + sl = sl || 0; + l /= 2; + + return [h, sl * 100, l * 100]; + }; + + // http://dev.w3.org/csswg/css-color/#hwb-to-rgb + convert.hwb.rgb = function (hwb) { + var h = hwb[0] / 360; + var wh = hwb[1] / 100; + var bl = hwb[2] / 100; + var ratio = wh + bl; + var i; + var v; + var f; + var n; + + // wh + bl cant be > 1 + if (ratio > 1) { + wh /= ratio; + bl /= ratio; + } + + i = Math.floor(6 * h); + v = 1 - bl; + f = 6 * h - i; + + if ((i & 0x01) !== 0) { + f = 1 - f; + } + + n = wh + f * (v - wh); // linear interpolation + + var r; + var g; + var b; + switch (i) { + default: + case 6: + case 0: r = v; g = n; b = wh; break; + case 1: r = n; g = v; b = wh; break; + case 2: r = wh; g = v; b = n; break; + case 3: r = wh; g = n; b = v; break; + case 4: r = n; g = wh; b = v; break; + case 5: r = v; g = wh; b = n; break; + } + + return [r * 255, g * 255, b * 255]; + }; + + convert.cmyk.rgb = function (cmyk) { + var c = cmyk[0] / 100; + var m = cmyk[1] / 100; + var y = cmyk[2] / 100; + var k = cmyk[3] / 100; + var r; + var g; + var b; + + r = 1 - Math.min(1, c * (1 - k) + k); + g = 1 - Math.min(1, m * (1 - k) + k); + b = 1 - Math.min(1, y * (1 - k) + k); + + return [r * 255, g * 255, b * 255]; + }; + + convert.xyz.rgb = function (xyz) { + var x = xyz[0] / 100; + var y = xyz[1] / 100; + var z = xyz[2] / 100; + var r; + var g; + var b; + + r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986); + g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415); + b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570); + + // assume sRGB + r = r > 0.0031308 + ? ((1.055 * Math.pow(r, 1.0 / 2.4)) - 0.055) + : r * 12.92; + + g = g > 0.0031308 + ? ((1.055 * Math.pow(g, 1.0 / 2.4)) - 0.055) + : g * 12.92; + + b = b > 0.0031308 + ? ((1.055 * Math.pow(b, 1.0 / 2.4)) - 0.055) + : b * 12.92; + + r = Math.min(Math.max(0, r), 1); + g = Math.min(Math.max(0, g), 1); + b = Math.min(Math.max(0, b), 1); + + return [r * 255, g * 255, b * 255]; + }; + + convert.xyz.lab = function (xyz) { + var x = xyz[0]; + var y = xyz[1]; + var z = xyz[2]; + var l; + var a; + var b; + + x /= 95.047; + y /= 100; + z /= 108.883; + + x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116); + y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116); + z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116); + + l = (116 * y) - 16; + a = 500 * (x - y); + b = 200 * (y - z); + + return [l, a, b]; + }; + + convert.lab.xyz = function (lab) { + var l = lab[0]; + var a = lab[1]; + var b = lab[2]; + var x; + var y; + var z; + + y = (l + 16) / 116; + x = a / 500 + y; + z = y - b / 200; + + var y2 = Math.pow(y, 3); + var x2 = Math.pow(x, 3); + var z2 = Math.pow(z, 3); + y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787; + x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787; + z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787; + + x *= 95.047; + y *= 100; + z *= 108.883; + + return [x, y, z]; + }; + + convert.lab.lch = function (lab) { + var l = lab[0]; + var a = lab[1]; + var b = lab[2]; + var hr; + var h; + var c; + + hr = Math.atan2(b, a); + h = hr * 360 / 2 / Math.PI; + + if (h < 0) { + h += 360; + } + + c = Math.sqrt(a * a + b * b); + + return [l, c, h]; + }; + + convert.lch.lab = function (lch) { + var l = lch[0]; + var c = lch[1]; + var h = lch[2]; + var a; + var b; + var hr; + + hr = h / 360 * 2 * Math.PI; + a = c * Math.cos(hr); + b = c * Math.sin(hr); + + return [l, a, b]; + }; + + convert.rgb.ansi16 = function (args) { + var r = args[0]; + var g = args[1]; + var b = args[2]; + var value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; // hsv -> ansi16 optimization + + value = Math.round(value / 50); + + if (value === 0) { + return 30; + } + + var ansi = 30 + + ((Math.round(b / 255) << 2) + | (Math.round(g / 255) << 1) + | Math.round(r / 255)); + + if (value === 2) { + ansi += 60; + } + + return ansi; + }; + + convert.hsv.ansi16 = function (args) { + // optimization here; we already know the value and don't need to get + // it converted for us. + return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]); + }; + + convert.rgb.ansi256 = function (args) { + var r = args[0]; + var g = args[1]; + var b = args[2]; + + // we use the extended greyscale palette here, with the exception of + // black and white. normal palette only has 4 greyscale shades. + if (r === g && g === b) { + if (r < 8) { + return 16; + } + + if (r > 248) { + return 231; + } + + return Math.round(((r - 8) / 247) * 24) + 232; + } + + var ansi = 16 + + (36 * Math.round(r / 255 * 5)) + + (6 * Math.round(g / 255 * 5)) + + Math.round(b / 255 * 5); + + return ansi; + }; + + convert.ansi16.rgb = function (args) { + var color = args % 10; + + // handle greyscale + if (color === 0 || color === 7) { + if (args > 50) { + color += 3.5; + } + + color = color / 10.5 * 255; + + return [color, color, color]; + } + + var mult = (~~(args > 50) + 1) * 0.5; + var r = ((color & 1) * mult) * 255; + var g = (((color >> 1) & 1) * mult) * 255; + var b = (((color >> 2) & 1) * mult) * 255; + + return [r, g, b]; + }; + + convert.ansi256.rgb = function (args) { + // handle greyscale + if (args >= 232) { + var c = (args - 232) * 10 + 8; + return [c, c, c]; + } + + args -= 16; + + var rem; + var r = Math.floor(args / 36) / 5 * 255; + var g = Math.floor((rem = args % 36) / 6) / 5 * 255; + var b = (rem % 6) / 5 * 255; + + return [r, g, b]; + }; + + convert.rgb.hex = function (args) { + var integer = ((Math.round(args[0]) & 0xFF) << 16) + + ((Math.round(args[1]) & 0xFF) << 8) + + (Math.round(args[2]) & 0xFF); + + var string = integer.toString(16).toUpperCase(); + return '000000'.substring(string.length) + string; + }; + + convert.hex.rgb = function (args) { + var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i); + if (!match) { + return [0, 0, 0]; + } + + var colorString = match[0]; + + if (match[0].length === 3) { + colorString = colorString.split('').map(function (char) { + return char + char; + }).join(''); + } + + var integer = parseInt(colorString, 16); + var r = (integer >> 16) & 0xFF; + var g = (integer >> 8) & 0xFF; + var b = integer & 0xFF; + + return [r, g, b]; + }; + + convert.rgb.hcg = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var max = Math.max(Math.max(r, g), b); + var min = Math.min(Math.min(r, g), b); + var chroma = (max - min); + var grayscale; + var hue; + + if (chroma < 1) { + grayscale = min / (1 - chroma); + } else { + grayscale = 0; + } + + if (chroma <= 0) { + hue = 0; + } else + if (max === r) { + hue = ((g - b) / chroma) % 6; + } else + if (max === g) { + hue = 2 + (b - r) / chroma; + } else { + hue = 4 + (r - g) / chroma + 4; + } + + hue /= 6; + hue %= 1; + + return [hue * 360, chroma * 100, grayscale * 100]; + }; + + convert.hsl.hcg = function (hsl) { + var s = hsl[1] / 100; + var l = hsl[2] / 100; + var c = 1; + var f = 0; + + if (l < 0.5) { + c = 2.0 * s * l; + } else { + c = 2.0 * s * (1.0 - l); + } + + if (c < 1.0) { + f = (l - 0.5 * c) / (1.0 - c); + } + + return [hsl[0], c * 100, f * 100]; + }; + + convert.hsv.hcg = function (hsv) { + var s = hsv[1] / 100; + var v = hsv[2] / 100; + + var c = s * v; + var f = 0; + + if (c < 1.0) { + f = (v - c) / (1 - c); + } + + return [hsv[0], c * 100, f * 100]; + }; + + convert.hcg.rgb = function (hcg) { + var h = hcg[0] / 360; + var c = hcg[1] / 100; + var g = hcg[2] / 100; + + if (c === 0.0) { + return [g * 255, g * 255, g * 255]; + } + + var pure = [0, 0, 0]; + var hi = (h % 1) * 6; + var v = hi % 1; + var w = 1 - v; + var mg = 0; + + switch (Math.floor(hi)) { + case 0: + pure[0] = 1; pure[1] = v; pure[2] = 0; break; + case 1: + pure[0] = w; pure[1] = 1; pure[2] = 0; break; + case 2: + pure[0] = 0; pure[1] = 1; pure[2] = v; break; + case 3: + pure[0] = 0; pure[1] = w; pure[2] = 1; break; + case 4: + pure[0] = v; pure[1] = 0; pure[2] = 1; break; + default: + pure[0] = 1; pure[1] = 0; pure[2] = w; + } + + mg = (1.0 - c) * g; + + return [ + (c * pure[0] + mg) * 255, + (c * pure[1] + mg) * 255, + (c * pure[2] + mg) * 255 + ]; + }; + + convert.hcg.hsv = function (hcg) { + var c = hcg[1] / 100; + var g = hcg[2] / 100; + + var v = c + g * (1.0 - c); + var f = 0; + + if (v > 0.0) { + f = c / v; + } + + return [hcg[0], f * 100, v * 100]; + }; + + convert.hcg.hsl = function (hcg) { + var c = hcg[1] / 100; + var g = hcg[2] / 100; + + var l = g * (1.0 - c) + 0.5 * c; + var s = 0; + + if (l > 0.0 && l < 0.5) { + s = c / (2 * l); + } else + if (l >= 0.5 && l < 1.0) { + s = c / (2 * (1 - l)); + } + + return [hcg[0], s * 100, l * 100]; + }; + + convert.hcg.hwb = function (hcg) { + var c = hcg[1] / 100; + var g = hcg[2] / 100; + var v = c + g * (1.0 - c); + return [hcg[0], (v - c) * 100, (1 - v) * 100]; + }; + + convert.hwb.hcg = function (hwb) { + var w = hwb[1] / 100; + var b = hwb[2] / 100; + var v = 1 - b; + var c = v - w; + var g = 0; + + if (c < 1) { + g = (v - c) / (1 - c); + } + + return [hwb[0], c * 100, g * 100]; + }; + + convert.apple.rgb = function (apple) { + return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255]; + }; + + convert.rgb.apple = function (rgb) { + return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535]; + }; + + convert.gray.rgb = function (args) { + return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255]; + }; + + convert.gray.hsl = convert.gray.hsv = function (args) { + return [0, 0, args[0]]; + }; + + convert.gray.hwb = function (gray) { + return [0, 100, gray[0]]; + }; + + convert.gray.cmyk = function (gray) { + return [0, 0, 0, gray[0]]; + }; + + convert.gray.lab = function (gray) { + return [gray[0], 0, 0]; + }; + + convert.gray.hex = function (gray) { + var val = Math.round(gray[0] / 100 * 255) & 0xFF; + var integer = (val << 16) + (val << 8) + val; + + var string = integer.toString(16).toUpperCase(); + return '000000'.substring(string.length) + string; + }; + + convert.rgb.gray = function (rgb) { + var val = (rgb[0] + rgb[1] + rgb[2]) / 3; + return [val / 255 * 100]; + }; + return conversions$4.exports; +} + +var route$3; +var hasRequiredRoute$3; + +function requireRoute$3 () { + if (hasRequiredRoute$3) return route$3; + hasRequiredRoute$3 = 1; + var conversions = requireConversions$3(); + + /* + this function routes a model to all other models. + + all functions that are routed have a property `.conversion` attached + to the returned synthetic function. This property is an array + of strings, each with the steps in between the 'from' and 'to' + color models (inclusive). + + conversions that are not possible simply are not included. + */ + + function buildGraph() { + var graph = {}; + // https://jsperf.com/object-keys-vs-for-in-with-closure/3 + var models = Object.keys(conversions); + + for (var len = models.length, i = 0; i < len; i++) { + graph[models[i]] = { + // http://jsperf.com/1-vs-infinity + // micro-opt, but this is simple. + distance: -1, + parent: null + }; + } + + return graph; + } + + // https://en.wikipedia.org/wiki/Breadth-first_search + function deriveBFS(fromModel) { + var graph = buildGraph(); + var queue = [fromModel]; // unshift -> queue -> pop + + graph[fromModel].distance = 0; + + while (queue.length) { + var current = queue.pop(); + var adjacents = Object.keys(conversions[current]); + + for (var len = adjacents.length, i = 0; i < len; i++) { + var adjacent = adjacents[i]; + var node = graph[adjacent]; + + if (node.distance === -1) { + node.distance = graph[current].distance + 1; + node.parent = current; + queue.unshift(adjacent); + } + } + } + + return graph; + } + + function link(from, to) { + return function (args) { + return to(from(args)); + }; + } + + function wrapConversion(toModel, graph) { + var path = [graph[toModel].parent, toModel]; + var fn = conversions[graph[toModel].parent][toModel]; + + var cur = graph[toModel].parent; + while (graph[cur].parent) { + path.unshift(graph[cur].parent); + fn = link(conversions[graph[cur].parent][cur], fn); + cur = graph[cur].parent; + } + + fn.conversion = path; + return fn; + } + + route$3 = function (fromModel) { + var graph = deriveBFS(fromModel); + var conversion = {}; + + var models = Object.keys(graph); + for (var len = models.length, i = 0; i < len; i++) { + var toModel = models[i]; + var node = graph[toModel]; + + if (node.parent === null) { + // no possible conversion, or this node is the source model. + continue; + } + + conversion[toModel] = wrapConversion(toModel, graph); + } + + return conversion; + }; + return route$3; +} + +var colorConvert$3; +var hasRequiredColorConvert$3; + +function requireColorConvert$3 () { + if (hasRequiredColorConvert$3) return colorConvert$3; + hasRequiredColorConvert$3 = 1; + var conversions = requireConversions$3(); + var route = requireRoute$3(); + + var convert = {}; + + var models = Object.keys(conversions); + + function wrapRaw(fn) { + var wrappedFn = function (args) { + if (args === undefined || args === null) { + return args; + } + + if (arguments.length > 1) { + args = Array.prototype.slice.call(arguments); + } + + return fn(args); + }; + + // preserve .conversion property if there is one + if ('conversion' in fn) { + wrappedFn.conversion = fn.conversion; + } + + return wrappedFn; + } + + function wrapRounded(fn) { + var wrappedFn = function (args) { + if (args === undefined || args === null) { + return args; + } + + if (arguments.length > 1) { + args = Array.prototype.slice.call(arguments); + } + + var result = fn(args); + + // we're assuming the result is an array here. + // see notice in conversions.js; don't use box types + // in conversion functions. + if (typeof result === 'object') { + for (var len = result.length, i = 0; i < len; i++) { + result[i] = Math.round(result[i]); + } + } + + return result; + }; + + // preserve .conversion property if there is one + if ('conversion' in fn) { + wrappedFn.conversion = fn.conversion; + } + + return wrappedFn; + } + + models.forEach(function (fromModel) { + convert[fromModel] = {}; + + Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels}); + Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels}); + + var routes = route(fromModel); + var routeModels = Object.keys(routes); + + routeModels.forEach(function (toModel) { + var fn = routes[toModel]; + + convert[fromModel][toModel] = wrapRounded(fn); + convert[fromModel][toModel].raw = wrapRaw(fn); + }); + }); + + colorConvert$3 = convert; + return colorConvert$3; +} + +ansiStyles$6.exports; + +var hasRequiredAnsiStyles$2; + +function requireAnsiStyles$2 () { + if (hasRequiredAnsiStyles$2) return ansiStyles$6.exports; + hasRequiredAnsiStyles$2 = 1; + (function (module) { + const colorConvert = requireColorConvert$3(); + + const wrapAnsi16 = (fn, offset) => function () { + const code = fn.apply(colorConvert, arguments); + return `\u001B[${code + offset}m`; + }; + + const wrapAnsi256 = (fn, offset) => function () { + const code = fn.apply(colorConvert, arguments); + return `\u001B[${38 + offset};5;${code}m`; + }; + + const wrapAnsi16m = (fn, offset) => function () { + const rgb = fn.apply(colorConvert, arguments); + return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; + }; + + function assembleStyles() { + const codes = new Map(); + const styles = { + modifier: { + reset: [0, 0], + // 21 isn't widely supported and 22 does the same thing + bold: [1, 22], + dim: [2, 22], + italic: [3, 23], + underline: [4, 24], + inverse: [7, 27], + hidden: [8, 28], + strikethrough: [9, 29] + }, + color: { + black: [30, 39], + red: [31, 39], + green: [32, 39], + yellow: [33, 39], + blue: [34, 39], + magenta: [35, 39], + cyan: [36, 39], + white: [37, 39], + gray: [90, 39], + + // Bright color + redBright: [91, 39], + greenBright: [92, 39], + yellowBright: [93, 39], + blueBright: [94, 39], + magentaBright: [95, 39], + cyanBright: [96, 39], + whiteBright: [97, 39] + }, + bgColor: { + bgBlack: [40, 49], + bgRed: [41, 49], + bgGreen: [42, 49], + bgYellow: [43, 49], + bgBlue: [44, 49], + bgMagenta: [45, 49], + bgCyan: [46, 49], + bgWhite: [47, 49], + + // Bright color + bgBlackBright: [100, 49], + bgRedBright: [101, 49], + bgGreenBright: [102, 49], + bgYellowBright: [103, 49], + bgBlueBright: [104, 49], + bgMagentaBright: [105, 49], + bgCyanBright: [106, 49], + bgWhiteBright: [107, 49] + } + }; + + // Fix humans + styles.color.grey = styles.color.gray; + + for (const groupName of Object.keys(styles)) { + const group = styles[groupName]; + + for (const styleName of Object.keys(group)) { + const style = group[styleName]; + + styles[styleName] = { + open: `\u001B[${style[0]}m`, + close: `\u001B[${style[1]}m` + }; + + group[styleName] = styles[styleName]; + + codes.set(style[0], style[1]); + } + + Object.defineProperty(styles, groupName, { + value: group, + enumerable: false + }); + + Object.defineProperty(styles, 'codes', { + value: codes, + enumerable: false + }); + } + + const ansi2ansi = n => n; + const rgb2rgb = (r, g, b) => [r, g, b]; + + styles.color.close = '\u001B[39m'; + styles.bgColor.close = '\u001B[49m'; + + styles.color.ansi = { + ansi: wrapAnsi16(ansi2ansi, 0) + }; + styles.color.ansi256 = { + ansi256: wrapAnsi256(ansi2ansi, 0) + }; + styles.color.ansi16m = { + rgb: wrapAnsi16m(rgb2rgb, 0) + }; + + styles.bgColor.ansi = { + ansi: wrapAnsi16(ansi2ansi, 10) + }; + styles.bgColor.ansi256 = { + ansi256: wrapAnsi256(ansi2ansi, 10) + }; + styles.bgColor.ansi16m = { + rgb: wrapAnsi16m(rgb2rgb, 10) + }; + + for (let key of Object.keys(colorConvert)) { + if (typeof colorConvert[key] !== 'object') { + continue; + } + + const suite = colorConvert[key]; + + if (key === 'ansi16') { + key = 'ansi'; + } + + if ('ansi16' in suite) { + styles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0); + styles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10); + } + + if ('ansi256' in suite) { + styles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0); + styles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10); + } + + if ('rgb' in suite) { + styles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0); + styles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10); + } + } + + return styles; + } + + // Make the export immutable + Object.defineProperty(module, 'exports', { + enumerable: true, + get: assembleStyles + }); + } (ansiStyles$6)); + return ansiStyles$6.exports; +} + +var hasFlag$1; +var hasRequiredHasFlag$1; + +function requireHasFlag$1 () { + if (hasRequiredHasFlag$1) return hasFlag$1; + hasRequiredHasFlag$1 = 1; + hasFlag$1 = (flag, argv) => { + argv = argv || process.argv; + const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); + const pos = argv.indexOf(prefix + flag); + const terminatorPos = argv.indexOf('--'); + return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos); + }; + return hasFlag$1; +} + +var supportsColor_1$1; +var hasRequiredSupportsColor$1; + +function requireSupportsColor$1 () { + if (hasRequiredSupportsColor$1) return supportsColor_1$1; + hasRequiredSupportsColor$1 = 1; + const os = require$$0$7; + const hasFlag = requireHasFlag$1(); + + const env = process.env; + + let forceColor; + if (hasFlag('no-color') || + hasFlag('no-colors') || + hasFlag('color=false')) { + forceColor = false; + } else if (hasFlag('color') || + hasFlag('colors') || + hasFlag('color=true') || + hasFlag('color=always')) { + forceColor = true; + } + if ('FORCE_COLOR' in env) { + forceColor = env.FORCE_COLOR.length === 0 || parseInt(env.FORCE_COLOR, 10) !== 0; + } + + function translateLevel(level) { + if (level === 0) { + return false; + } + + return { + level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3 + }; + } + + function supportsColor(stream) { + if (forceColor === false) { + return 0; + } + + if (hasFlag('color=16m') || + hasFlag('color=full') || + hasFlag('color=truecolor')) { + return 3; + } + + if (hasFlag('color=256')) { + return 2; + } + + if (stream && !stream.isTTY && forceColor !== true) { + return 0; + } + + const min = forceColor ? 1 : 0; + + if (process.platform === 'win32') { + // Node.js 7.5.0 is the first version of Node.js to include a patch to + // libuv that enables 256 color output on Windows. Anything earlier and it + // won't work. However, here we target Node.js 8 at minimum as it is an LTS + // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows + // release that supports 256 colors. Windows 10 build 14931 is the first release + // that supports 16m/TrueColor. + const osRelease = os.release().split('.'); + if ( + Number(process.versions.node.split('.')[0]) >= 8 && + Number(osRelease[0]) >= 10 && + Number(osRelease[2]) >= 10586 + ) { + return Number(osRelease[2]) >= 14931 ? 3 : 2; + } + + return 1; + } + + if ('CI' in env) { + if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env) || env.CI_NAME === 'codeship') { + return 1; + } + + return min; + } + + if ('TEAMCITY_VERSION' in env) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; + } + + if (env.COLORTERM === 'truecolor') { + return 3; + } + + if ('TERM_PROGRAM' in env) { + const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); + + switch (env.TERM_PROGRAM) { + case 'iTerm.app': + return version >= 3 ? 3 : 2; + case 'Apple_Terminal': + return 2; + // No default + } + } + + if (/-256(color)?$/i.test(env.TERM)) { + return 2; + } + + if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { + return 1; + } + + if ('COLORTERM' in env) { + return 1; + } + + if (env.TERM === 'dumb') { + return min; + } + + return min; + } + + function getSupportLevel(stream) { + const level = supportsColor(stream); + return translateLevel(level); + } + + supportsColor_1$1 = { + supportsColor: getSupportLevel, + stdout: getSupportLevel(process.stdout), + stderr: getSupportLevel(process.stderr) + }; + return supportsColor_1$1; +} + +var templates$3; +var hasRequiredTemplates$3; + +function requireTemplates$3 () { + if (hasRequiredTemplates$3) return templates$3; + hasRequiredTemplates$3 = 1; + const TEMPLATE_REGEX = /(?:\\(u[a-f\d]{4}|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi; + const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g; + const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/; + const ESCAPE_REGEX = /\\(u[a-f\d]{4}|x[a-f\d]{2}|.)|([^\\])/gi; + + const ESCAPES = new Map([ + ['n', '\n'], + ['r', '\r'], + ['t', '\t'], + ['b', '\b'], + ['f', '\f'], + ['v', '\v'], + ['0', '\0'], + ['\\', '\\'], + ['e', '\u001B'], + ['a', '\u0007'] + ]); + + function unescape(c) { + if ((c[0] === 'u' && c.length === 5) || (c[0] === 'x' && c.length === 3)) { + return String.fromCharCode(parseInt(c.slice(1), 16)); + } + + return ESCAPES.get(c) || c; + } + + function parseArguments(name, args) { + const results = []; + const chunks = args.trim().split(/\s*,\s*/g); + let matches; + + for (const chunk of chunks) { + if (!isNaN(chunk)) { + results.push(Number(chunk)); + } else if ((matches = chunk.match(STRING_REGEX))) { + results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, chr) => escape ? unescape(escape) : chr)); + } else { + throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`); + } + } + + return results; + } + + function parseStyle(style) { + STYLE_REGEX.lastIndex = 0; + + const results = []; + let matches; + + while ((matches = STYLE_REGEX.exec(style)) !== null) { + const name = matches[1]; + + if (matches[2]) { + const args = parseArguments(name, matches[2]); + results.push([name].concat(args)); + } else { + results.push([name]); + } + } + + return results; + } + + function buildStyle(chalk, styles) { + const enabled = {}; + + for (const layer of styles) { + for (const style of layer.styles) { + enabled[style[0]] = layer.inverse ? null : style.slice(1); + } + } + + let current = chalk; + for (const styleName of Object.keys(enabled)) { + if (Array.isArray(enabled[styleName])) { + if (!(styleName in current)) { + throw new Error(`Unknown Chalk style: ${styleName}`); + } + + if (enabled[styleName].length > 0) { + current = current[styleName].apply(current, enabled[styleName]); + } else { + current = current[styleName]; + } + } + } + + return current; + } + + templates$3 = (chalk, tmp) => { + const styles = []; + const chunks = []; + let chunk = []; + + // eslint-disable-next-line max-params + tmp.replace(TEMPLATE_REGEX, (m, escapeChar, inverse, style, close, chr) => { + if (escapeChar) { + chunk.push(unescape(escapeChar)); + } else if (style) { + const str = chunk.join(''); + chunk = []; + chunks.push(styles.length === 0 ? str : buildStyle(chalk, styles)(str)); + styles.push({inverse, styles: parseStyle(style)}); + } else if (close) { + if (styles.length === 0) { + throw new Error('Found extraneous } in Chalk template literal'); + } + + chunks.push(buildStyle(chalk, styles)(chunk.join(''))); + chunk = []; + styles.pop(); + } else { + chunk.push(chr); + } + }); + + chunks.push(chunk.join('')); + + if (styles.length > 0) { + const errMsg = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`; + throw new Error(errMsg); + } + + return chunks.join(''); + }; + return templates$3; +} + +var hasRequiredChalk$1; + +function requireChalk$1 () { + if (hasRequiredChalk$1) return chalk$3.exports; + hasRequiredChalk$1 = 1; + (function (module) { + const escapeStringRegexp = requireEscapeStringRegexp$1(); + const ansiStyles = requireAnsiStyles$2(); + const stdoutColor = requireSupportsColor$1().stdout; + + const template = requireTemplates$3(); + + const isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm'); + + // `supportsColor.level` → `ansiStyles.color[name]` mapping + const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m']; + + // `color-convert` models to exclude from the Chalk API due to conflicts and such + const skipModels = new Set(['gray']); + + const styles = Object.create(null); + + function applyOptions(obj, options) { + options = options || {}; + + // Detect level if not set manually + const scLevel = stdoutColor ? stdoutColor.level : 0; + obj.level = options.level === undefined ? scLevel : options.level; + obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0; + } + + function Chalk(options) { + // We check for this.template here since calling `chalk.constructor()` + // by itself will have a `this` of a previously constructed chalk object + if (!this || !(this instanceof Chalk) || this.template) { + const chalk = {}; + applyOptions(chalk, options); + + chalk.template = function () { + const args = [].slice.call(arguments); + return chalkTag.apply(null, [chalk.template].concat(args)); + }; + + Object.setPrototypeOf(chalk, Chalk.prototype); + Object.setPrototypeOf(chalk.template, chalk); + + chalk.template.constructor = Chalk; + + return chalk.template; + } + + applyOptions(this, options); + } + + // Use bright blue on Windows as the normal blue color is illegible + if (isSimpleWindowsTerm) { + ansiStyles.blue.open = '\u001B[94m'; + } + + for (const key of Object.keys(ansiStyles)) { + ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g'); + + styles[key] = { + get() { + const codes = ansiStyles[key]; + return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key); + } + }; + } + + styles.visible = { + get() { + return build.call(this, this._styles || [], true, 'visible'); + } + }; + + ansiStyles.color.closeRe = new RegExp(escapeStringRegexp(ansiStyles.color.close), 'g'); + for (const model of Object.keys(ansiStyles.color.ansi)) { + if (skipModels.has(model)) { + continue; + } + + styles[model] = { + get() { + const level = this.level; + return function () { + const open = ansiStyles.color[levelMapping[level]][model].apply(null, arguments); + const codes = { + open, + close: ansiStyles.color.close, + closeRe: ansiStyles.color.closeRe + }; + return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); + }; + } + }; + } + + ansiStyles.bgColor.closeRe = new RegExp(escapeStringRegexp(ansiStyles.bgColor.close), 'g'); + for (const model of Object.keys(ansiStyles.bgColor.ansi)) { + if (skipModels.has(model)) { + continue; + } + + const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); + styles[bgModel] = { + get() { + const level = this.level; + return function () { + const open = ansiStyles.bgColor[levelMapping[level]][model].apply(null, arguments); + const codes = { + open, + close: ansiStyles.bgColor.close, + closeRe: ansiStyles.bgColor.closeRe + }; + return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); + }; + } + }; + } + + const proto = Object.defineProperties(() => {}, styles); + + function build(_styles, _empty, key) { + const builder = function () { + return applyStyle.apply(builder, arguments); + }; + + builder._styles = _styles; + builder._empty = _empty; + + const self = this; + + Object.defineProperty(builder, 'level', { + enumerable: true, + get() { + return self.level; + }, + set(level) { + self.level = level; + } + }); + + Object.defineProperty(builder, 'enabled', { + enumerable: true, + get() { + return self.enabled; + }, + set(enabled) { + self.enabled = enabled; + } + }); + + // See below for fix regarding invisible grey/dim combination on Windows + builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey'; + + // `__proto__` is used because we must return a function, but there is + // no way to create a function with a different prototype + builder.__proto__ = proto; // eslint-disable-line no-proto + + return builder; + } + + function applyStyle() { + // Support varags, but simply cast to string in case there's only one arg + const args = arguments; + const argsLen = args.length; + let str = String(arguments[0]); + + if (argsLen === 0) { + return ''; + } + + if (argsLen > 1) { + // Don't slice `arguments`, it prevents V8 optimizations + for (let a = 1; a < argsLen; a++) { + str += ' ' + args[a]; + } + } + + if (!this.enabled || this.level <= 0 || !str) { + return this._empty ? '' : str; + } + + // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe, + // see https://github.com/chalk/chalk/issues/58 + // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop. + const originalDim = ansiStyles.dim.open; + if (isSimpleWindowsTerm && this.hasGrey) { + ansiStyles.dim.open = ''; + } + + for (const code of this._styles.slice().reverse()) { + // Replace any instances already present with a re-opening code + // otherwise only the part of the string until said closing code + // will be colored, and the rest will simply be 'plain'. + str = code.open + str.replace(code.closeRe, code.open) + code.close; + + // Close the styling before a linebreak and reopen + // after next line to fix a bleed issue on macOS + // https://github.com/chalk/chalk/pull/92 + str = str.replace(/\r?\n/g, `${code.close}$&${code.open}`); + } + + // Reset the original `dim` if we changed it to work around the Windows dimmed gray issue + ansiStyles.dim.open = originalDim; + + return str; + } + + function chalkTag(chalk, strings) { + if (!Array.isArray(strings)) { + // If chalk() was called by itself or with a string, + // return the string itself as a string. + return [].slice.call(arguments, 1).join(' '); + } + + const args = [].slice.call(arguments, 2); + const parts = [strings.raw[0]]; + + for (let i = 1; i < strings.length; i++) { + parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&')); + parts.push(String(strings.raw[i])); + } + + return template(chalk, parts.join('')); + } + + Object.defineProperties(Chalk.prototype, styles); + + module.exports = Chalk(); // eslint-disable-line new-cap + module.exports.supportsColor = stdoutColor; + module.exports.default = module.exports; // For TypeScript + } (chalk$3)); + return chalk$3.exports; +} + +var hasRequiredLib$1; + +function requireLib$1 () { + if (hasRequiredLib$1) return lib$d; + hasRequiredLib$1 = 1; + + Object.defineProperty(lib$d, "__esModule", { + value: true + }); + lib$d.default = highlight; + lib$d.shouldHighlight = shouldHighlight; + var _jsTokens = requireJsTokens(); + var _helperValidatorIdentifier = requireLib$2(); + var _chalk = _interopRequireWildcard(requireChalk$1(), true); + function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } + function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && 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; } + const sometimesKeywords = new Set(["as", "async", "from", "get", "of", "set"]); + function getDefs(chalk) { + return { + keyword: chalk.cyan, + capitalized: chalk.yellow, + jsxIdentifier: chalk.yellow, + punctuator: chalk.yellow, + number: chalk.magenta, + string: chalk.green, + regex: chalk.magenta, + comment: chalk.grey, + invalid: chalk.white.bgRed.bold + }; + } + const NEWLINE = /\r\n|[\n\r\u2028\u2029]/; + const BRACKET = /^[()[\]{}]$/; + let tokenize; + { + const JSX_TAG = /^[a-z][\w-]*$/i; + const getTokenType = function (token, offset, text) { + if (token.type === "name") { + if ((0, _helperValidatorIdentifier.isKeyword)(token.value) || (0, _helperValidatorIdentifier.isStrictReservedWord)(token.value, true) || sometimesKeywords.has(token.value)) { + return "keyword"; + } + if (JSX_TAG.test(token.value) && (text[offset - 1] === "<" || text.slice(offset - 2, offset) == "</")) { + return "jsxIdentifier"; + } + if (token.value[0] !== token.value[0].toLowerCase()) { + return "capitalized"; + } + } + if (token.type === "punctuator" && BRACKET.test(token.value)) { + return "bracket"; + } + if (token.type === "invalid" && (token.value === "@" || token.value === "#")) { + return "punctuator"; + } + return token.type; + }; + tokenize = function* (text) { + let match; + while (match = _jsTokens.default.exec(text)) { + const token = _jsTokens.matchToToken(match); + yield { + type: getTokenType(token, match.index, text), + value: token.value + }; + } + }; + } + function highlightTokens(defs, text) { + let highlighted = ""; + for (const { + type, + value + } of tokenize(text)) { + const colorize = defs[type]; + if (colorize) { + highlighted += value.split(NEWLINE).map(str => colorize(str)).join("\n"); + } else { + highlighted += value; + } + } + return highlighted; + } + function shouldHighlight(options) { + return _chalk.default.level > 0 || options.forceColor; + } + let chalkWithForcedColor = undefined; + function getChalk(forceColor) { + if (forceColor) { + var _chalkWithForcedColor; + (_chalkWithForcedColor = chalkWithForcedColor) != null ? _chalkWithForcedColor : chalkWithForcedColor = new _chalk.default.constructor({ + enabled: true, + level: 1 + }); + return chalkWithForcedColor; + } + return _chalk.default; + } + { + { + lib$d.getChalk = options => getChalk(options.forceColor); + } + } + function highlight(code, options = {}) { + if (code !== "" && shouldHighlight(options)) { + const defs = getDefs(getChalk(options.forceColor)); + return highlightTokens(defs, code); + } else { + return code; + } + } + + + return lib$d; +} + +var chalk$2 = {exports: {}}; + +var escapeStringRegexp; +var hasRequiredEscapeStringRegexp; + +function requireEscapeStringRegexp () { + if (hasRequiredEscapeStringRegexp) return escapeStringRegexp; + hasRequiredEscapeStringRegexp = 1; + + var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; + + escapeStringRegexp = function (str) { + if (typeof str !== 'string') { + throw new TypeError('Expected a string'); + } + + return str.replace(matchOperatorsRe, '\\$&'); + }; + return escapeStringRegexp; +} + +var ansiStyles$5 = {exports: {}}; + +ansiStyles$5.exports; + +var hasRequiredAnsiStyles$1; + +function requireAnsiStyles$1 () { + if (hasRequiredAnsiStyles$1) return ansiStyles$5.exports; + hasRequiredAnsiStyles$1 = 1; + (function (module) { + const colorConvert = requireColorConvert$3(); + + const wrapAnsi16 = (fn, offset) => function () { + const code = fn.apply(colorConvert, arguments); + return `\u001B[${code + offset}m`; + }; + + const wrapAnsi256 = (fn, offset) => function () { + const code = fn.apply(colorConvert, arguments); + return `\u001B[${38 + offset};5;${code}m`; + }; + + const wrapAnsi16m = (fn, offset) => function () { + const rgb = fn.apply(colorConvert, arguments); + return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; + }; + + function assembleStyles() { + const codes = new Map(); + const styles = { + modifier: { + reset: [0, 0], + // 21 isn't widely supported and 22 does the same thing + bold: [1, 22], + dim: [2, 22], + italic: [3, 23], + underline: [4, 24], + inverse: [7, 27], + hidden: [8, 28], + strikethrough: [9, 29] + }, + color: { + black: [30, 39], + red: [31, 39], + green: [32, 39], + yellow: [33, 39], + blue: [34, 39], + magenta: [35, 39], + cyan: [36, 39], + white: [37, 39], + gray: [90, 39], + + // Bright color + redBright: [91, 39], + greenBright: [92, 39], + yellowBright: [93, 39], + blueBright: [94, 39], + magentaBright: [95, 39], + cyanBright: [96, 39], + whiteBright: [97, 39] + }, + bgColor: { + bgBlack: [40, 49], + bgRed: [41, 49], + bgGreen: [42, 49], + bgYellow: [43, 49], + bgBlue: [44, 49], + bgMagenta: [45, 49], + bgCyan: [46, 49], + bgWhite: [47, 49], + + // Bright color + bgBlackBright: [100, 49], + bgRedBright: [101, 49], + bgGreenBright: [102, 49], + bgYellowBright: [103, 49], + bgBlueBright: [104, 49], + bgMagentaBright: [105, 49], + bgCyanBright: [106, 49], + bgWhiteBright: [107, 49] + } + }; + + // Fix humans + styles.color.grey = styles.color.gray; + + for (const groupName of Object.keys(styles)) { + const group = styles[groupName]; + + for (const styleName of Object.keys(group)) { + const style = group[styleName]; + + styles[styleName] = { + open: `\u001B[${style[0]}m`, + close: `\u001B[${style[1]}m` + }; + + group[styleName] = styles[styleName]; + + codes.set(style[0], style[1]); + } + + Object.defineProperty(styles, groupName, { + value: group, + enumerable: false + }); + + Object.defineProperty(styles, 'codes', { + value: codes, + enumerable: false + }); + } + + const ansi2ansi = n => n; + const rgb2rgb = (r, g, b) => [r, g, b]; + + styles.color.close = '\u001B[39m'; + styles.bgColor.close = '\u001B[49m'; + + styles.color.ansi = { + ansi: wrapAnsi16(ansi2ansi, 0) + }; + styles.color.ansi256 = { + ansi256: wrapAnsi256(ansi2ansi, 0) + }; + styles.color.ansi16m = { + rgb: wrapAnsi16m(rgb2rgb, 0) + }; + + styles.bgColor.ansi = { + ansi: wrapAnsi16(ansi2ansi, 10) + }; + styles.bgColor.ansi256 = { + ansi256: wrapAnsi256(ansi2ansi, 10) + }; + styles.bgColor.ansi16m = { + rgb: wrapAnsi16m(rgb2rgb, 10) + }; + + for (let key of Object.keys(colorConvert)) { + if (typeof colorConvert[key] !== 'object') { + continue; + } + + const suite = colorConvert[key]; + + if (key === 'ansi16') { + key = 'ansi'; + } + + if ('ansi16' in suite) { + styles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0); + styles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10); + } + + if ('ansi256' in suite) { + styles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0); + styles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10); + } + + if ('rgb' in suite) { + styles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0); + styles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10); + } + } + + return styles; + } + + // Make the export immutable + Object.defineProperty(module, 'exports', { + enumerable: true, + get: assembleStyles + }); + } (ansiStyles$5)); + return ansiStyles$5.exports; +} + +var hasFlag; +var hasRequiredHasFlag; + +function requireHasFlag () { + if (hasRequiredHasFlag) return hasFlag; + hasRequiredHasFlag = 1; + hasFlag = (flag, argv) => { + argv = argv || process.argv; + const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); + const pos = argv.indexOf(prefix + flag); + const terminatorPos = argv.indexOf('--'); + return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos); + }; + return hasFlag; +} + +var supportsColor_1; +var hasRequiredSupportsColor; + +function requireSupportsColor () { + if (hasRequiredSupportsColor) return supportsColor_1; + hasRequiredSupportsColor = 1; + const os = require$$0$7; + const hasFlag = requireHasFlag(); + + const env = process.env; + + let forceColor; + if (hasFlag('no-color') || + hasFlag('no-colors') || + hasFlag('color=false')) { + forceColor = false; + } else if (hasFlag('color') || + hasFlag('colors') || + hasFlag('color=true') || + hasFlag('color=always')) { + forceColor = true; + } + if ('FORCE_COLOR' in env) { + forceColor = env.FORCE_COLOR.length === 0 || parseInt(env.FORCE_COLOR, 10) !== 0; + } + + function translateLevel(level) { + if (level === 0) { + return false; + } + + return { + level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3 + }; + } + + function supportsColor(stream) { + if (forceColor === false) { + return 0; + } + + if (hasFlag('color=16m') || + hasFlag('color=full') || + hasFlag('color=truecolor')) { + return 3; + } + + if (hasFlag('color=256')) { + return 2; + } + + if (stream && !stream.isTTY && forceColor !== true) { + return 0; + } + + const min = forceColor ? 1 : 0; + + if (process.platform === 'win32') { + // Node.js 7.5.0 is the first version of Node.js to include a patch to + // libuv that enables 256 color output on Windows. Anything earlier and it + // won't work. However, here we target Node.js 8 at minimum as it is an LTS + // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows + // release that supports 256 colors. Windows 10 build 14931 is the first release + // that supports 16m/TrueColor. + const osRelease = os.release().split('.'); + if ( + Number(process.versions.node.split('.')[0]) >= 8 && + Number(osRelease[0]) >= 10 && + Number(osRelease[2]) >= 10586 + ) { + return Number(osRelease[2]) >= 14931 ? 3 : 2; + } + + return 1; + } + + if ('CI' in env) { + if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env) || env.CI_NAME === 'codeship') { + return 1; + } + + return min; + } + + if ('TEAMCITY_VERSION' in env) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; + } + + if (env.COLORTERM === 'truecolor') { + return 3; + } + + if ('TERM_PROGRAM' in env) { + const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); + + switch (env.TERM_PROGRAM) { + case 'iTerm.app': + return version >= 3 ? 3 : 2; + case 'Apple_Terminal': + return 2; + // No default + } + } + + if (/-256(color)?$/i.test(env.TERM)) { + return 2; + } + + if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { + return 1; + } + + if ('COLORTERM' in env) { + return 1; + } + + if (env.TERM === 'dumb') { + return min; + } + + return min; + } + + function getSupportLevel(stream) { + const level = supportsColor(stream); + return translateLevel(level); + } + + supportsColor_1 = { + supportsColor: getSupportLevel, + stdout: getSupportLevel(process.stdout), + stderr: getSupportLevel(process.stderr) + }; + return supportsColor_1; +} + +var templates$2; +var hasRequiredTemplates$2; + +function requireTemplates$2 () { + if (hasRequiredTemplates$2) return templates$2; + hasRequiredTemplates$2 = 1; + const TEMPLATE_REGEX = /(?:\\(u[a-f\d]{4}|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi; + const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g; + const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/; + const ESCAPE_REGEX = /\\(u[a-f\d]{4}|x[a-f\d]{2}|.)|([^\\])/gi; + + const ESCAPES = new Map([ + ['n', '\n'], + ['r', '\r'], + ['t', '\t'], + ['b', '\b'], + ['f', '\f'], + ['v', '\v'], + ['0', '\0'], + ['\\', '\\'], + ['e', '\u001B'], + ['a', '\u0007'] + ]); + + function unescape(c) { + if ((c[0] === 'u' && c.length === 5) || (c[0] === 'x' && c.length === 3)) { + return String.fromCharCode(parseInt(c.slice(1), 16)); + } + + return ESCAPES.get(c) || c; + } + + function parseArguments(name, args) { + const results = []; + const chunks = args.trim().split(/\s*,\s*/g); + let matches; + + for (const chunk of chunks) { + if (!isNaN(chunk)) { + results.push(Number(chunk)); + } else if ((matches = chunk.match(STRING_REGEX))) { + results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, chr) => escape ? unescape(escape) : chr)); + } else { + throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`); + } + } + + return results; + } + + function parseStyle(style) { + STYLE_REGEX.lastIndex = 0; + + const results = []; + let matches; + + while ((matches = STYLE_REGEX.exec(style)) !== null) { + const name = matches[1]; + + if (matches[2]) { + const args = parseArguments(name, matches[2]); + results.push([name].concat(args)); + } else { + results.push([name]); + } + } + + return results; + } + + function buildStyle(chalk, styles) { + const enabled = {}; + + for (const layer of styles) { + for (const style of layer.styles) { + enabled[style[0]] = layer.inverse ? null : style.slice(1); + } + } + + let current = chalk; + for (const styleName of Object.keys(enabled)) { + if (Array.isArray(enabled[styleName])) { + if (!(styleName in current)) { + throw new Error(`Unknown Chalk style: ${styleName}`); + } + + if (enabled[styleName].length > 0) { + current = current[styleName].apply(current, enabled[styleName]); + } else { + current = current[styleName]; + } + } + } + + return current; + } + + templates$2 = (chalk, tmp) => { + const styles = []; + const chunks = []; + let chunk = []; + + // eslint-disable-next-line max-params + tmp.replace(TEMPLATE_REGEX, (m, escapeChar, inverse, style, close, chr) => { + if (escapeChar) { + chunk.push(unescape(escapeChar)); + } else if (style) { + const str = chunk.join(''); + chunk = []; + chunks.push(styles.length === 0 ? str : buildStyle(chalk, styles)(str)); + styles.push({inverse, styles: parseStyle(style)}); + } else if (close) { + if (styles.length === 0) { + throw new Error('Found extraneous } in Chalk template literal'); + } + + chunks.push(buildStyle(chalk, styles)(chunk.join(''))); + chunk = []; + styles.pop(); + } else { + chunk.push(chr); + } + }); + + chunks.push(chunk.join('')); + + if (styles.length > 0) { + const errMsg = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`; + throw new Error(errMsg); + } + + return chunks.join(''); + }; + return templates$2; +} + +var hasRequiredChalk; + +function requireChalk () { + if (hasRequiredChalk) return chalk$2.exports; + hasRequiredChalk = 1; + (function (module) { + const escapeStringRegexp = requireEscapeStringRegexp(); + const ansiStyles = requireAnsiStyles$1(); + const stdoutColor = requireSupportsColor().stdout; + + const template = requireTemplates$2(); + + const isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm'); + + // `supportsColor.level` → `ansiStyles.color[name]` mapping + const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m']; + + // `color-convert` models to exclude from the Chalk API due to conflicts and such + const skipModels = new Set(['gray']); + + const styles = Object.create(null); + + function applyOptions(obj, options) { + options = options || {}; + + // Detect level if not set manually + const scLevel = stdoutColor ? stdoutColor.level : 0; + obj.level = options.level === undefined ? scLevel : options.level; + obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0; + } + + function Chalk(options) { + // We check for this.template here since calling `chalk.constructor()` + // by itself will have a `this` of a previously constructed chalk object + if (!this || !(this instanceof Chalk) || this.template) { + const chalk = {}; + applyOptions(chalk, options); + + chalk.template = function () { + const args = [].slice.call(arguments); + return chalkTag.apply(null, [chalk.template].concat(args)); + }; + + Object.setPrototypeOf(chalk, Chalk.prototype); + Object.setPrototypeOf(chalk.template, chalk); + + chalk.template.constructor = Chalk; + + return chalk.template; + } + + applyOptions(this, options); + } + + // Use bright blue on Windows as the normal blue color is illegible + if (isSimpleWindowsTerm) { + ansiStyles.blue.open = '\u001B[94m'; + } + + for (const key of Object.keys(ansiStyles)) { + ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g'); + + styles[key] = { + get() { + const codes = ansiStyles[key]; + return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key); + } + }; + } + + styles.visible = { + get() { + return build.call(this, this._styles || [], true, 'visible'); + } + }; + + ansiStyles.color.closeRe = new RegExp(escapeStringRegexp(ansiStyles.color.close), 'g'); + for (const model of Object.keys(ansiStyles.color.ansi)) { + if (skipModels.has(model)) { + continue; + } + + styles[model] = { + get() { + const level = this.level; + return function () { + const open = ansiStyles.color[levelMapping[level]][model].apply(null, arguments); + const codes = { + open, + close: ansiStyles.color.close, + closeRe: ansiStyles.color.closeRe + }; + return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); + }; + } + }; + } + + ansiStyles.bgColor.closeRe = new RegExp(escapeStringRegexp(ansiStyles.bgColor.close), 'g'); + for (const model of Object.keys(ansiStyles.bgColor.ansi)) { + if (skipModels.has(model)) { + continue; + } + + const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); + styles[bgModel] = { + get() { + const level = this.level; + return function () { + const open = ansiStyles.bgColor[levelMapping[level]][model].apply(null, arguments); + const codes = { + open, + close: ansiStyles.bgColor.close, + closeRe: ansiStyles.bgColor.closeRe + }; + return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); + }; + } + }; + } + + const proto = Object.defineProperties(() => {}, styles); + + function build(_styles, _empty, key) { + const builder = function () { + return applyStyle.apply(builder, arguments); + }; + + builder._styles = _styles; + builder._empty = _empty; + + const self = this; + + Object.defineProperty(builder, 'level', { + enumerable: true, + get() { + return self.level; + }, + set(level) { + self.level = level; + } + }); + + Object.defineProperty(builder, 'enabled', { + enumerable: true, + get() { + return self.enabled; + }, + set(enabled) { + self.enabled = enabled; + } + }); + + // See below for fix regarding invisible grey/dim combination on Windows + builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey'; + + // `__proto__` is used because we must return a function, but there is + // no way to create a function with a different prototype + builder.__proto__ = proto; // eslint-disable-line no-proto + + return builder; + } + + function applyStyle() { + // Support varags, but simply cast to string in case there's only one arg + const args = arguments; + const argsLen = args.length; + let str = String(arguments[0]); + + if (argsLen === 0) { + return ''; + } + + if (argsLen > 1) { + // Don't slice `arguments`, it prevents V8 optimizations + for (let a = 1; a < argsLen; a++) { + str += ' ' + args[a]; + } + } + + if (!this.enabled || this.level <= 0 || !str) { + return this._empty ? '' : str; + } + + // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe, + // see https://github.com/chalk/chalk/issues/58 + // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop. + const originalDim = ansiStyles.dim.open; + if (isSimpleWindowsTerm && this.hasGrey) { + ansiStyles.dim.open = ''; + } + + for (const code of this._styles.slice().reverse()) { + // Replace any instances already present with a re-opening code + // otherwise only the part of the string until said closing code + // will be colored, and the rest will simply be 'plain'. + str = code.open + str.replace(code.closeRe, code.open) + code.close; + + // Close the styling before a linebreak and reopen + // after next line to fix a bleed issue on macOS + // https://github.com/chalk/chalk/pull/92 + str = str.replace(/\r?\n/g, `${code.close}$&${code.open}`); + } + + // Reset the original `dim` if we changed it to work around the Windows dimmed gray issue + ansiStyles.dim.open = originalDim; + + return str; + } + + function chalkTag(chalk, strings) { + if (!Array.isArray(strings)) { + // If chalk() was called by itself or with a string, + // return the string itself as a string. + return [].slice.call(arguments, 1).join(' '); + } + + const args = [].slice.call(arguments, 2); + const parts = [strings.raw[0]]; + + for (let i = 1; i < strings.length; i++) { + parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&')); + parts.push(String(strings.raw[i])); + } + + return template(chalk, parts.join('')); + } + + Object.defineProperties(Chalk.prototype, styles); + + module.exports = Chalk(); // eslint-disable-line new-cap + module.exports.supportsColor = stdoutColor; + module.exports.default = module.exports; // For TypeScript + } (chalk$2)); + return chalk$2.exports; +} + +var hasRequiredLib; + +function requireLib () { + if (hasRequiredLib) return lib$e; + hasRequiredLib = 1; + + Object.defineProperty(lib$e, "__esModule", { + value: true + }); + lib$e.codeFrameColumns = codeFrameColumns; + lib$e.default = _default; + var _highlight = requireLib$1(); + var _chalk = _interopRequireWildcard(requireChalk(), true); + function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } + function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && 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; } + let chalkWithForcedColor = undefined; + function getChalk(forceColor) { + if (forceColor) { + var _chalkWithForcedColor; + (_chalkWithForcedColor = chalkWithForcedColor) != null ? _chalkWithForcedColor : chalkWithForcedColor = new _chalk.default.constructor({ + enabled: true, + level: 1 + }); + return chalkWithForcedColor; + } + return _chalk.default; + } + let deprecationWarningShown = false; + function getDefs(chalk) { + return { + gutter: chalk.grey, + marker: chalk.red.bold, + message: chalk.red.bold + }; + } + const NEWLINE = /\r\n|[\n\r\u2028\u2029]/; + function getMarkerLines(loc, source, opts) { + const startLoc = Object.assign({ + column: 0, + line: -1 + }, loc.start); + const endLoc = Object.assign({}, startLoc, loc.end); + const { + linesAbove = 2, + linesBelow = 3 + } = opts || {}; + const startLine = startLoc.line; + const startColumn = startLoc.column; + const endLine = endLoc.line; + const endColumn = endLoc.column; + let start = Math.max(startLine - (linesAbove + 1), 0); + let end = Math.min(source.length, endLine + linesBelow); + if (startLine === -1) { + start = 0; + } + if (endLine === -1) { + end = source.length; + } + const lineDiff = endLine - startLine; + const markerLines = {}; + if (lineDiff) { + for (let i = 0; i <= lineDiff; i++) { + const lineNumber = i + startLine; + if (!startColumn) { + markerLines[lineNumber] = true; + } else if (i === 0) { + const sourceLength = source[lineNumber - 1].length; + markerLines[lineNumber] = [startColumn, sourceLength - startColumn + 1]; + } else if (i === lineDiff) { + markerLines[lineNumber] = [0, endColumn]; + } else { + const sourceLength = source[lineNumber - i].length; + markerLines[lineNumber] = [0, sourceLength]; + } + } + } else { + if (startColumn === endColumn) { + if (startColumn) { + markerLines[startLine] = [startColumn, 0]; + } else { + markerLines[startLine] = true; + } + } else { + markerLines[startLine] = [startColumn, endColumn - startColumn]; + } + } + return { + start, + end, + markerLines + }; + } + function codeFrameColumns(rawLines, loc, opts = {}) { + const highlighted = (opts.highlightCode || opts.forceColor) && (0, _highlight.shouldHighlight)(opts); + const chalk = getChalk(opts.forceColor); + const defs = getDefs(chalk); + const maybeHighlight = (chalkFn, string) => { + return highlighted ? chalkFn(string) : string; + }; + const lines = rawLines.split(NEWLINE); + const { + start, + end, + markerLines + } = getMarkerLines(loc, lines, opts); + const hasColumns = loc.start && typeof loc.start.column === "number"; + const numberMaxWidth = String(end).length; + const highlightedLines = highlighted ? (0, _highlight.default)(rawLines, opts) : rawLines; + let frame = highlightedLines.split(NEWLINE, end).slice(start, end).map((line, index) => { + const number = start + 1 + index; + const paddedNumber = ` ${number}`.slice(-numberMaxWidth); + const gutter = ` ${paddedNumber} |`; + const hasMarker = markerLines[number]; + const lastMarkerLine = !markerLines[number + 1]; + if (hasMarker) { + let markerLine = ""; + if (Array.isArray(hasMarker)) { + const markerSpacing = line.slice(0, Math.max(hasMarker[0] - 1, 0)).replace(/[^\t]/g, " "); + const numberOfMarkers = hasMarker[1] || 1; + markerLine = ["\n ", maybeHighlight(defs.gutter, gutter.replace(/\d/g, " ")), " ", markerSpacing, maybeHighlight(defs.marker, "^").repeat(numberOfMarkers)].join(""); + if (lastMarkerLine && opts.message) { + markerLine += " " + maybeHighlight(defs.message, opts.message); + } + } + return [maybeHighlight(defs.marker, ">"), maybeHighlight(defs.gutter, gutter), line.length > 0 ? ` ${line}` : "", markerLine].join(""); + } else { + return ` ${maybeHighlight(defs.gutter, gutter)}${line.length > 0 ? ` ${line}` : ""}`; + } + }).join("\n"); + if (opts.message && !hasColumns) { + frame = `${" ".repeat(numberMaxWidth + 1)}${opts.message}\n${frame}`; + } + if (highlighted) { + return chalk.reset(frame); + } else { + return frame; + } + } + function _default(rawLines, lineNumber, colNumber, opts = {}) { + if (!deprecationWarningShown) { + deprecationWarningShown = true; + const message = "Passing lineNumber and colNumber is deprecated to @babel/code-frame. Please use `codeFrameColumns`."; + if (process.emitWarning) { + process.emitWarning(message, "DeprecationWarning"); + } else { + const deprecationError = new Error(message); + deprecationError.name = "DeprecationWarning"; + console.warn(new Error(message)); + } + } + colNumber = Math.max(colNumber, 0); + const location = { + start: { + column: colNumber, + line: lineNumber + } + }; + return codeFrameColumns(rawLines, location, opts); + } + + + return lib$e; +} + +var ansiStyles$4 = {exports: {}}; + +var colorName$2; +var hasRequiredColorName$2; + +function requireColorName$2 () { + if (hasRequiredColorName$2) return colorName$2; + hasRequiredColorName$2 = 1; + + colorName$2 = { + "aliceblue": [240, 248, 255], + "antiquewhite": [250, 235, 215], + "aqua": [0, 255, 255], + "aquamarine": [127, 255, 212], + "azure": [240, 255, 255], + "beige": [245, 245, 220], + "bisque": [255, 228, 196], + "black": [0, 0, 0], + "blanchedalmond": [255, 235, 205], + "blue": [0, 0, 255], + "blueviolet": [138, 43, 226], + "brown": [165, 42, 42], + "burlywood": [222, 184, 135], + "cadetblue": [95, 158, 160], + "chartreuse": [127, 255, 0], + "chocolate": [210, 105, 30], + "coral": [255, 127, 80], + "cornflowerblue": [100, 149, 237], + "cornsilk": [255, 248, 220], + "crimson": [220, 20, 60], + "cyan": [0, 255, 255], + "darkblue": [0, 0, 139], + "darkcyan": [0, 139, 139], + "darkgoldenrod": [184, 134, 11], + "darkgray": [169, 169, 169], + "darkgreen": [0, 100, 0], + "darkgrey": [169, 169, 169], + "darkkhaki": [189, 183, 107], + "darkmagenta": [139, 0, 139], + "darkolivegreen": [85, 107, 47], + "darkorange": [255, 140, 0], + "darkorchid": [153, 50, 204], + "darkred": [139, 0, 0], + "darksalmon": [233, 150, 122], + "darkseagreen": [143, 188, 143], + "darkslateblue": [72, 61, 139], + "darkslategray": [47, 79, 79], + "darkslategrey": [47, 79, 79], + "darkturquoise": [0, 206, 209], + "darkviolet": [148, 0, 211], + "deeppink": [255, 20, 147], + "deepskyblue": [0, 191, 255], + "dimgray": [105, 105, 105], + "dimgrey": [105, 105, 105], + "dodgerblue": [30, 144, 255], + "firebrick": [178, 34, 34], + "floralwhite": [255, 250, 240], + "forestgreen": [34, 139, 34], + "fuchsia": [255, 0, 255], + "gainsboro": [220, 220, 220], + "ghostwhite": [248, 248, 255], + "gold": [255, 215, 0], + "goldenrod": [218, 165, 32], + "gray": [128, 128, 128], + "green": [0, 128, 0], + "greenyellow": [173, 255, 47], + "grey": [128, 128, 128], + "honeydew": [240, 255, 240], + "hotpink": [255, 105, 180], + "indianred": [205, 92, 92], + "indigo": [75, 0, 130], + "ivory": [255, 255, 240], + "khaki": [240, 230, 140], + "lavender": [230, 230, 250], + "lavenderblush": [255, 240, 245], + "lawngreen": [124, 252, 0], + "lemonchiffon": [255, 250, 205], + "lightblue": [173, 216, 230], + "lightcoral": [240, 128, 128], + "lightcyan": [224, 255, 255], + "lightgoldenrodyellow": [250, 250, 210], + "lightgray": [211, 211, 211], + "lightgreen": [144, 238, 144], + "lightgrey": [211, 211, 211], + "lightpink": [255, 182, 193], + "lightsalmon": [255, 160, 122], + "lightseagreen": [32, 178, 170], + "lightskyblue": [135, 206, 250], + "lightslategray": [119, 136, 153], + "lightslategrey": [119, 136, 153], + "lightsteelblue": [176, 196, 222], + "lightyellow": [255, 255, 224], + "lime": [0, 255, 0], + "limegreen": [50, 205, 50], + "linen": [250, 240, 230], + "magenta": [255, 0, 255], + "maroon": [128, 0, 0], + "mediumaquamarine": [102, 205, 170], + "mediumblue": [0, 0, 205], + "mediumorchid": [186, 85, 211], + "mediumpurple": [147, 112, 219], + "mediumseagreen": [60, 179, 113], + "mediumslateblue": [123, 104, 238], + "mediumspringgreen": [0, 250, 154], + "mediumturquoise": [72, 209, 204], + "mediumvioletred": [199, 21, 133], + "midnightblue": [25, 25, 112], + "mintcream": [245, 255, 250], + "mistyrose": [255, 228, 225], + "moccasin": [255, 228, 181], + "navajowhite": [255, 222, 173], + "navy": [0, 0, 128], + "oldlace": [253, 245, 230], + "olive": [128, 128, 0], + "olivedrab": [107, 142, 35], + "orange": [255, 165, 0], + "orangered": [255, 69, 0], + "orchid": [218, 112, 214], + "palegoldenrod": [238, 232, 170], + "palegreen": [152, 251, 152], + "paleturquoise": [175, 238, 238], + "palevioletred": [219, 112, 147], + "papayawhip": [255, 239, 213], + "peachpuff": [255, 218, 185], + "peru": [205, 133, 63], + "pink": [255, 192, 203], + "plum": [221, 160, 221], + "powderblue": [176, 224, 230], + "purple": [128, 0, 128], + "rebeccapurple": [102, 51, 153], + "red": [255, 0, 0], + "rosybrown": [188, 143, 143], + "royalblue": [65, 105, 225], + "saddlebrown": [139, 69, 19], + "salmon": [250, 128, 114], + "sandybrown": [244, 164, 96], + "seagreen": [46, 139, 87], + "seashell": [255, 245, 238], + "sienna": [160, 82, 45], + "silver": [192, 192, 192], + "skyblue": [135, 206, 235], + "slateblue": [106, 90, 205], + "slategray": [112, 128, 144], + "slategrey": [112, 128, 144], + "snow": [255, 250, 250], + "springgreen": [0, 255, 127], + "steelblue": [70, 130, 180], + "tan": [210, 180, 140], + "teal": [0, 128, 128], + "thistle": [216, 191, 216], + "tomato": [255, 99, 71], + "turquoise": [64, 224, 208], + "violet": [238, 130, 238], + "wheat": [245, 222, 179], + "white": [255, 255, 255], + "whitesmoke": [245, 245, 245], + "yellow": [255, 255, 0], + "yellowgreen": [154, 205, 50] + }; + return colorName$2; +} + +/* MIT license */ + +var conversions$3; +var hasRequiredConversions$2; + +function requireConversions$2 () { + if (hasRequiredConversions$2) return conversions$3; + hasRequiredConversions$2 = 1; + /* eslint-disable no-mixed-operators */ + const cssKeywords = requireColorName$2(); + + // NOTE: conversions should only return primitive values (i.e. arrays, or + // values that give correct `typeof` results). + // do not use box values types (i.e. Number(), String(), etc.) + + const reverseKeywords = {}; + for (const key of Object.keys(cssKeywords)) { + reverseKeywords[cssKeywords[key]] = key; + } + + const convert = { + rgb: {channels: 3, labels: 'rgb'}, + hsl: {channels: 3, labels: 'hsl'}, + hsv: {channels: 3, labels: 'hsv'}, + hwb: {channels: 3, labels: 'hwb'}, + cmyk: {channels: 4, labels: 'cmyk'}, + xyz: {channels: 3, labels: 'xyz'}, + lab: {channels: 3, labels: 'lab'}, + lch: {channels: 3, labels: 'lch'}, + hex: {channels: 1, labels: ['hex']}, + keyword: {channels: 1, labels: ['keyword']}, + ansi16: {channels: 1, labels: ['ansi16']}, + ansi256: {channels: 1, labels: ['ansi256']}, + hcg: {channels: 3, labels: ['h', 'c', 'g']}, + apple: {channels: 3, labels: ['r16', 'g16', 'b16']}, + gray: {channels: 1, labels: ['gray']} + }; + + conversions$3 = convert; + + // Hide .channels and .labels properties + for (const model of Object.keys(convert)) { + if (!('channels' in convert[model])) { + throw new Error('missing channels property: ' + model); + } + + if (!('labels' in convert[model])) { + throw new Error('missing channel labels property: ' + model); + } + + if (convert[model].labels.length !== convert[model].channels) { + throw new Error('channel and label counts mismatch: ' + model); + } + + const {channels, labels} = convert[model]; + delete convert[model].channels; + delete convert[model].labels; + Object.defineProperty(convert[model], 'channels', {value: channels}); + Object.defineProperty(convert[model], 'labels', {value: labels}); + } + + convert.rgb.hsl = function (rgb) { + const r = rgb[0] / 255; + const g = rgb[1] / 255; + const b = rgb[2] / 255; + const min = Math.min(r, g, b); + const max = Math.max(r, g, b); + const delta = max - min; + let h; + let s; + + if (max === min) { + h = 0; + } else if (r === max) { + h = (g - b) / delta; + } else if (g === max) { + h = 2 + (b - r) / delta; + } else if (b === max) { + h = 4 + (r - g) / delta; + } + + h = Math.min(h * 60, 360); + + if (h < 0) { + h += 360; + } + + const l = (min + max) / 2; + + if (max === min) { + s = 0; + } else if (l <= 0.5) { + s = delta / (max + min); + } else { + s = delta / (2 - max - min); + } + + return [h, s * 100, l * 100]; + }; + + convert.rgb.hsv = function (rgb) { + let rdif; + let gdif; + let bdif; + let h; + let s; + + const r = rgb[0] / 255; + const g = rgb[1] / 255; + const b = rgb[2] / 255; + const v = Math.max(r, g, b); + const diff = v - Math.min(r, g, b); + const diffc = function (c) { + return (v - c) / 6 / diff + 1 / 2; + }; + + if (diff === 0) { + h = 0; + s = 0; + } else { + s = diff / v; + rdif = diffc(r); + gdif = diffc(g); + bdif = diffc(b); + + if (r === v) { + h = bdif - gdif; + } else if (g === v) { + h = (1 / 3) + rdif - bdif; + } else if (b === v) { + h = (2 / 3) + gdif - rdif; + } + + if (h < 0) { + h += 1; + } else if (h > 1) { + h -= 1; + } + } + + return [ + h * 360, + s * 100, + v * 100 + ]; + }; + + convert.rgb.hwb = function (rgb) { + const r = rgb[0]; + const g = rgb[1]; + let b = rgb[2]; + const h = convert.rgb.hsl(rgb)[0]; + const w = 1 / 255 * Math.min(r, Math.min(g, b)); + + b = 1 - 1 / 255 * Math.max(r, Math.max(g, b)); + + return [h, w * 100, b * 100]; + }; + + convert.rgb.cmyk = function (rgb) { + const r = rgb[0] / 255; + const g = rgb[1] / 255; + const b = rgb[2] / 255; + + const k = Math.min(1 - r, 1 - g, 1 - b); + const c = (1 - r - k) / (1 - k) || 0; + const m = (1 - g - k) / (1 - k) || 0; + const y = (1 - b - k) / (1 - k) || 0; + + return [c * 100, m * 100, y * 100, k * 100]; + }; + + function comparativeDistance(x, y) { + /* + See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance + */ + return ( + ((x[0] - y[0]) ** 2) + + ((x[1] - y[1]) ** 2) + + ((x[2] - y[2]) ** 2) + ); + } + + convert.rgb.keyword = function (rgb) { + const reversed = reverseKeywords[rgb]; + if (reversed) { + return reversed; + } + + let currentClosestDistance = Infinity; + let currentClosestKeyword; + + for (const keyword of Object.keys(cssKeywords)) { + const value = cssKeywords[keyword]; + + // Compute comparative distance + const distance = comparativeDistance(rgb, value); + + // Check if its less, if so set as closest + if (distance < currentClosestDistance) { + currentClosestDistance = distance; + currentClosestKeyword = keyword; + } + } + + return currentClosestKeyword; + }; + + convert.keyword.rgb = function (keyword) { + return cssKeywords[keyword]; + }; + + convert.rgb.xyz = function (rgb) { + let r = rgb[0] / 255; + let g = rgb[1] / 255; + let b = rgb[2] / 255; + + // Assume sRGB + r = r > 0.04045 ? (((r + 0.055) / 1.055) ** 2.4) : (r / 12.92); + g = g > 0.04045 ? (((g + 0.055) / 1.055) ** 2.4) : (g / 12.92); + b = b > 0.04045 ? (((b + 0.055) / 1.055) ** 2.4) : (b / 12.92); + + const x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805); + const y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722); + const z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505); + + return [x * 100, y * 100, z * 100]; + }; + + convert.rgb.lab = function (rgb) { + const xyz = convert.rgb.xyz(rgb); + let x = xyz[0]; + let y = xyz[1]; + let z = xyz[2]; + + x /= 95.047; + y /= 100; + z /= 108.883; + + x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116); + y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116); + z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116); + + const l = (116 * y) - 16; + const a = 500 * (x - y); + const b = 200 * (y - z); + + return [l, a, b]; + }; + + convert.hsl.rgb = function (hsl) { + const h = hsl[0] / 360; + const s = hsl[1] / 100; + const l = hsl[2] / 100; + let t2; + let t3; + let val; + + if (s === 0) { + val = l * 255; + return [val, val, val]; + } + + if (l < 0.5) { + t2 = l * (1 + s); + } else { + t2 = l + s - l * s; + } + + const t1 = 2 * l - t2; + + const rgb = [0, 0, 0]; + for (let i = 0; i < 3; i++) { + t3 = h + 1 / 3 * -(i - 1); + if (t3 < 0) { + t3++; + } + + if (t3 > 1) { + t3--; + } + + if (6 * t3 < 1) { + val = t1 + (t2 - t1) * 6 * t3; + } else if (2 * t3 < 1) { + val = t2; + } else if (3 * t3 < 2) { + val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; + } else { + val = t1; + } + + rgb[i] = val * 255; + } + + return rgb; + }; + + convert.hsl.hsv = function (hsl) { + const h = hsl[0]; + let s = hsl[1] / 100; + let l = hsl[2] / 100; + let smin = s; + const lmin = Math.max(l, 0.01); + + l *= 2; + s *= (l <= 1) ? l : 2 - l; + smin *= lmin <= 1 ? lmin : 2 - lmin; + const v = (l + s) / 2; + const sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s); + + return [h, sv * 100, v * 100]; + }; + + convert.hsv.rgb = function (hsv) { + const h = hsv[0] / 60; + const s = hsv[1] / 100; + let v = hsv[2] / 100; + const hi = Math.floor(h) % 6; + + const f = h - Math.floor(h); + const p = 255 * v * (1 - s); + const q = 255 * v * (1 - (s * f)); + const t = 255 * v * (1 - (s * (1 - f))); + v *= 255; + + switch (hi) { + case 0: + return [v, t, p]; + case 1: + return [q, v, p]; + case 2: + return [p, v, t]; + case 3: + return [p, q, v]; + case 4: + return [t, p, v]; + case 5: + return [v, p, q]; + } + }; + + convert.hsv.hsl = function (hsv) { + const h = hsv[0]; + const s = hsv[1] / 100; + const v = hsv[2] / 100; + const vmin = Math.max(v, 0.01); + let sl; + let l; + + l = (2 - s) * v; + const lmin = (2 - s) * vmin; + sl = s * vmin; + sl /= (lmin <= 1) ? lmin : 2 - lmin; + sl = sl || 0; + l /= 2; + + return [h, sl * 100, l * 100]; + }; + + // http://dev.w3.org/csswg/css-color/#hwb-to-rgb + convert.hwb.rgb = function (hwb) { + const h = hwb[0] / 360; + let wh = hwb[1] / 100; + let bl = hwb[2] / 100; + const ratio = wh + bl; + let f; + + // Wh + bl cant be > 1 + if (ratio > 1) { + wh /= ratio; + bl /= ratio; + } + + const i = Math.floor(6 * h); + const v = 1 - bl; + f = 6 * h - i; + + if ((i & 0x01) !== 0) { + f = 1 - f; + } + + const n = wh + f * (v - wh); // Linear interpolation + + let r; + let g; + let b; + /* eslint-disable max-statements-per-line,no-multi-spaces */ + switch (i) { + default: + case 6: + case 0: r = v; g = n; b = wh; break; + case 1: r = n; g = v; b = wh; break; + case 2: r = wh; g = v; b = n; break; + case 3: r = wh; g = n; b = v; break; + case 4: r = n; g = wh; b = v; break; + case 5: r = v; g = wh; b = n; break; + } + /* eslint-enable max-statements-per-line,no-multi-spaces */ + + return [r * 255, g * 255, b * 255]; + }; + + convert.cmyk.rgb = function (cmyk) { + const c = cmyk[0] / 100; + const m = cmyk[1] / 100; + const y = cmyk[2] / 100; + const k = cmyk[3] / 100; + + const r = 1 - Math.min(1, c * (1 - k) + k); + const g = 1 - Math.min(1, m * (1 - k) + k); + const b = 1 - Math.min(1, y * (1 - k) + k); + + return [r * 255, g * 255, b * 255]; + }; + + convert.xyz.rgb = function (xyz) { + const x = xyz[0] / 100; + const y = xyz[1] / 100; + const z = xyz[2] / 100; + let r; + let g; + let b; + + r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986); + g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415); + b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570); + + // Assume sRGB + r = r > 0.0031308 + ? ((1.055 * (r ** (1.0 / 2.4))) - 0.055) + : r * 12.92; + + g = g > 0.0031308 + ? ((1.055 * (g ** (1.0 / 2.4))) - 0.055) + : g * 12.92; + + b = b > 0.0031308 + ? ((1.055 * (b ** (1.0 / 2.4))) - 0.055) + : b * 12.92; + + r = Math.min(Math.max(0, r), 1); + g = Math.min(Math.max(0, g), 1); + b = Math.min(Math.max(0, b), 1); + + return [r * 255, g * 255, b * 255]; + }; + + convert.xyz.lab = function (xyz) { + let x = xyz[0]; + let y = xyz[1]; + let z = xyz[2]; + + x /= 95.047; + y /= 100; + z /= 108.883; + + x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116); + y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116); + z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116); + + const l = (116 * y) - 16; + const a = 500 * (x - y); + const b = 200 * (y - z); + + return [l, a, b]; + }; + + convert.lab.xyz = function (lab) { + const l = lab[0]; + const a = lab[1]; + const b = lab[2]; + let x; + let y; + let z; + + y = (l + 16) / 116; + x = a / 500 + y; + z = y - b / 200; + + const y2 = y ** 3; + const x2 = x ** 3; + const z2 = z ** 3; + y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787; + x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787; + z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787; + + x *= 95.047; + y *= 100; + z *= 108.883; + + return [x, y, z]; + }; + + convert.lab.lch = function (lab) { + const l = lab[0]; + const a = lab[1]; + const b = lab[2]; + let h; + + const hr = Math.atan2(b, a); + h = hr * 360 / 2 / Math.PI; + + if (h < 0) { + h += 360; + } + + const c = Math.sqrt(a * a + b * b); + + return [l, c, h]; + }; + + convert.lch.lab = function (lch) { + const l = lch[0]; + const c = lch[1]; + const h = lch[2]; + + const hr = h / 360 * 2 * Math.PI; + const a = c * Math.cos(hr); + const b = c * Math.sin(hr); + + return [l, a, b]; + }; + + convert.rgb.ansi16 = function (args, saturation = null) { + const [r, g, b] = args; + let value = saturation === null ? convert.rgb.hsv(args)[2] : saturation; // Hsv -> ansi16 optimization + + value = Math.round(value / 50); + + if (value === 0) { + return 30; + } + + let ansi = 30 + + ((Math.round(b / 255) << 2) + | (Math.round(g / 255) << 1) + | Math.round(r / 255)); + + if (value === 2) { + ansi += 60; + } + + return ansi; + }; + + convert.hsv.ansi16 = function (args) { + // Optimization here; we already know the value and don't need to get + // it converted for us. + return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]); + }; + + convert.rgb.ansi256 = function (args) { + const r = args[0]; + const g = args[1]; + const b = args[2]; + + // We use the extended greyscale palette here, with the exception of + // black and white. normal palette only has 4 greyscale shades. + if (r === g && g === b) { + if (r < 8) { + return 16; + } + + if (r > 248) { + return 231; + } + + return Math.round(((r - 8) / 247) * 24) + 232; + } + + const ansi = 16 + + (36 * Math.round(r / 255 * 5)) + + (6 * Math.round(g / 255 * 5)) + + Math.round(b / 255 * 5); + + return ansi; + }; + + convert.ansi16.rgb = function (args) { + let color = args % 10; + + // Handle greyscale + if (color === 0 || color === 7) { + if (args > 50) { + color += 3.5; + } + + color = color / 10.5 * 255; + + return [color, color, color]; + } + + const mult = (~~(args > 50) + 1) * 0.5; + const r = ((color & 1) * mult) * 255; + const g = (((color >> 1) & 1) * mult) * 255; + const b = (((color >> 2) & 1) * mult) * 255; + + return [r, g, b]; + }; + + convert.ansi256.rgb = function (args) { + // Handle greyscale + if (args >= 232) { + const c = (args - 232) * 10 + 8; + return [c, c, c]; + } + + args -= 16; + + let rem; + const r = Math.floor(args / 36) / 5 * 255; + const g = Math.floor((rem = args % 36) / 6) / 5 * 255; + const b = (rem % 6) / 5 * 255; + + return [r, g, b]; + }; + + convert.rgb.hex = function (args) { + const integer = ((Math.round(args[0]) & 0xFF) << 16) + + ((Math.round(args[1]) & 0xFF) << 8) + + (Math.round(args[2]) & 0xFF); + + const string = integer.toString(16).toUpperCase(); + return '000000'.substring(string.length) + string; + }; + + convert.hex.rgb = function (args) { + const match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i); + if (!match) { + return [0, 0, 0]; + } + + let colorString = match[0]; + + if (match[0].length === 3) { + colorString = colorString.split('').map(char => { + return char + char; + }).join(''); + } + + const integer = parseInt(colorString, 16); + const r = (integer >> 16) & 0xFF; + const g = (integer >> 8) & 0xFF; + const b = integer & 0xFF; + + return [r, g, b]; + }; + + convert.rgb.hcg = function (rgb) { + const r = rgb[0] / 255; + const g = rgb[1] / 255; + const b = rgb[2] / 255; + const max = Math.max(Math.max(r, g), b); + const min = Math.min(Math.min(r, g), b); + const chroma = (max - min); + let grayscale; + let hue; + + if (chroma < 1) { + grayscale = min / (1 - chroma); + } else { + grayscale = 0; + } + + if (chroma <= 0) { + hue = 0; + } else + if (max === r) { + hue = ((g - b) / chroma) % 6; + } else + if (max === g) { + hue = 2 + (b - r) / chroma; + } else { + hue = 4 + (r - g) / chroma; + } + + hue /= 6; + hue %= 1; + + return [hue * 360, chroma * 100, grayscale * 100]; + }; + + convert.hsl.hcg = function (hsl) { + const s = hsl[1] / 100; + const l = hsl[2] / 100; + + const c = l < 0.5 ? (2.0 * s * l) : (2.0 * s * (1.0 - l)); + + let f = 0; + if (c < 1.0) { + f = (l - 0.5 * c) / (1.0 - c); + } + + return [hsl[0], c * 100, f * 100]; + }; + + convert.hsv.hcg = function (hsv) { + const s = hsv[1] / 100; + const v = hsv[2] / 100; + + const c = s * v; + let f = 0; + + if (c < 1.0) { + f = (v - c) / (1 - c); + } + + return [hsv[0], c * 100, f * 100]; + }; + + convert.hcg.rgb = function (hcg) { + const h = hcg[0] / 360; + const c = hcg[1] / 100; + const g = hcg[2] / 100; + + if (c === 0.0) { + return [g * 255, g * 255, g * 255]; + } + + const pure = [0, 0, 0]; + const hi = (h % 1) * 6; + const v = hi % 1; + const w = 1 - v; + let mg = 0; + + /* eslint-disable max-statements-per-line */ + switch (Math.floor(hi)) { + case 0: + pure[0] = 1; pure[1] = v; pure[2] = 0; break; + case 1: + pure[0] = w; pure[1] = 1; pure[2] = 0; break; + case 2: + pure[0] = 0; pure[1] = 1; pure[2] = v; break; + case 3: + pure[0] = 0; pure[1] = w; pure[2] = 1; break; + case 4: + pure[0] = v; pure[1] = 0; pure[2] = 1; break; + default: + pure[0] = 1; pure[1] = 0; pure[2] = w; + } + /* eslint-enable max-statements-per-line */ + + mg = (1.0 - c) * g; + + return [ + (c * pure[0] + mg) * 255, + (c * pure[1] + mg) * 255, + (c * pure[2] + mg) * 255 + ]; + }; + + convert.hcg.hsv = function (hcg) { + const c = hcg[1] / 100; + const g = hcg[2] / 100; + + const v = c + g * (1.0 - c); + let f = 0; + + if (v > 0.0) { + f = c / v; + } + + return [hcg[0], f * 100, v * 100]; + }; + + convert.hcg.hsl = function (hcg) { + const c = hcg[1] / 100; + const g = hcg[2] / 100; + + const l = g * (1.0 - c) + 0.5 * c; + let s = 0; + + if (l > 0.0 && l < 0.5) { + s = c / (2 * l); + } else + if (l >= 0.5 && l < 1.0) { + s = c / (2 * (1 - l)); + } + + return [hcg[0], s * 100, l * 100]; + }; + + convert.hcg.hwb = function (hcg) { + const c = hcg[1] / 100; + const g = hcg[2] / 100; + const v = c + g * (1.0 - c); + return [hcg[0], (v - c) * 100, (1 - v) * 100]; + }; + + convert.hwb.hcg = function (hwb) { + const w = hwb[1] / 100; + const b = hwb[2] / 100; + const v = 1 - b; + const c = v - w; + let g = 0; + + if (c < 1) { + g = (v - c) / (1 - c); + } + + return [hwb[0], c * 100, g * 100]; + }; + + convert.apple.rgb = function (apple) { + return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255]; + }; + + convert.rgb.apple = function (rgb) { + return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535]; + }; + + convert.gray.rgb = function (args) { + return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255]; + }; + + convert.gray.hsl = function (args) { + return [0, 0, args[0]]; + }; + + convert.gray.hsv = convert.gray.hsl; + + convert.gray.hwb = function (gray) { + return [0, 100, gray[0]]; + }; + + convert.gray.cmyk = function (gray) { + return [0, 0, 0, gray[0]]; + }; + + convert.gray.lab = function (gray) { + return [gray[0], 0, 0]; + }; + + convert.gray.hex = function (gray) { + const val = Math.round(gray[0] / 100 * 255) & 0xFF; + const integer = (val << 16) + (val << 8) + val; + + const string = integer.toString(16).toUpperCase(); + return '000000'.substring(string.length) + string; + }; + + convert.rgb.gray = function (rgb) { + const val = (rgb[0] + rgb[1] + rgb[2]) / 3; + return [val / 255 * 100]; + }; + return conversions$3; +} + +var route$2; +var hasRequiredRoute$2; + +function requireRoute$2 () { + if (hasRequiredRoute$2) return route$2; + hasRequiredRoute$2 = 1; + const conversions = requireConversions$2(); + + /* + This function routes a model to all other models. + + all functions that are routed have a property `.conversion` attached + to the returned synthetic function. This property is an array + of strings, each with the steps in between the 'from' and 'to' + color models (inclusive). + + conversions that are not possible simply are not included. + */ + + function buildGraph() { + const graph = {}; + // https://jsperf.com/object-keys-vs-for-in-with-closure/3 + const models = Object.keys(conversions); + + for (let len = models.length, i = 0; i < len; i++) { + graph[models[i]] = { + // http://jsperf.com/1-vs-infinity + // micro-opt, but this is simple. + distance: -1, + parent: null + }; + } + + return graph; + } + + // https://en.wikipedia.org/wiki/Breadth-first_search + function deriveBFS(fromModel) { + const graph = buildGraph(); + const queue = [fromModel]; // Unshift -> queue -> pop + + graph[fromModel].distance = 0; + + while (queue.length) { + const current = queue.pop(); + const adjacents = Object.keys(conversions[current]); + + for (let len = adjacents.length, i = 0; i < len; i++) { + const adjacent = adjacents[i]; + const node = graph[adjacent]; + + if (node.distance === -1) { + node.distance = graph[current].distance + 1; + node.parent = current; + queue.unshift(adjacent); + } + } + } + + return graph; + } + + function link(from, to) { + return function (args) { + return to(from(args)); + }; + } + + function wrapConversion(toModel, graph) { + const path = [graph[toModel].parent, toModel]; + let fn = conversions[graph[toModel].parent][toModel]; + + let cur = graph[toModel].parent; + while (graph[cur].parent) { + path.unshift(graph[cur].parent); + fn = link(conversions[graph[cur].parent][cur], fn); + cur = graph[cur].parent; + } + + fn.conversion = path; + return fn; + } + + route$2 = function (fromModel) { + const graph = deriveBFS(fromModel); + const conversion = {}; + + const models = Object.keys(graph); + for (let len = models.length, i = 0; i < len; i++) { + const toModel = models[i]; + const node = graph[toModel]; + + if (node.parent === null) { + // No possible conversion, or this node is the source model. + continue; + } + + conversion[toModel] = wrapConversion(toModel, graph); + } + + return conversion; + }; + return route$2; +} + +var colorConvert$2; +var hasRequiredColorConvert$2; + +function requireColorConvert$2 () { + if (hasRequiredColorConvert$2) return colorConvert$2; + hasRequiredColorConvert$2 = 1; + const conversions = requireConversions$2(); + const route = requireRoute$2(); + + const convert = {}; + + const models = Object.keys(conversions); + + function wrapRaw(fn) { + const wrappedFn = function (...args) { + const arg0 = args[0]; + if (arg0 === undefined || arg0 === null) { + return arg0; + } + + if (arg0.length > 1) { + args = arg0; + } + + return fn(args); + }; + + // Preserve .conversion property if there is one + if ('conversion' in fn) { + wrappedFn.conversion = fn.conversion; + } + + return wrappedFn; + } + + function wrapRounded(fn) { + const wrappedFn = function (...args) { + const arg0 = args[0]; + + if (arg0 === undefined || arg0 === null) { + return arg0; + } + + if (arg0.length > 1) { + args = arg0; + } + + const result = fn(args); + + // We're assuming the result is an array here. + // see notice in conversions.js; don't use box types + // in conversion functions. + if (typeof result === 'object') { + for (let len = result.length, i = 0; i < len; i++) { + result[i] = Math.round(result[i]); + } + } + + return result; + }; + + // Preserve .conversion property if there is one + if ('conversion' in fn) { + wrappedFn.conversion = fn.conversion; + } + + return wrappedFn; + } + + models.forEach(fromModel => { + convert[fromModel] = {}; + + Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels}); + Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels}); + + const routes = route(fromModel); + const routeModels = Object.keys(routes); + + routeModels.forEach(toModel => { + const fn = routes[toModel]; + + convert[fromModel][toModel] = wrapRounded(fn); + convert[fromModel][toModel].raw = wrapRaw(fn); + }); + }); + + colorConvert$2 = convert; + return colorConvert$2; +} + +ansiStyles$4.exports; + +var hasRequiredAnsiStyles; + +function requireAnsiStyles () { + if (hasRequiredAnsiStyles) return ansiStyles$4.exports; + hasRequiredAnsiStyles = 1; + (function (module) { + + const wrapAnsi16 = (fn, offset) => (...args) => { + const code = fn(...args); + return `\u001B[${code + offset}m`; + }; + + const wrapAnsi256 = (fn, offset) => (...args) => { + const code = fn(...args); + return `\u001B[${38 + offset};5;${code}m`; + }; + + const wrapAnsi16m = (fn, offset) => (...args) => { + const rgb = fn(...args); + return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; + }; + + const ansi2ansi = n => n; + const rgb2rgb = (r, g, b) => [r, g, b]; + + const setLazyProperty = (object, property, get) => { + Object.defineProperty(object, property, { + get: () => { + const value = get(); + + Object.defineProperty(object, property, { + value, + enumerable: true, + configurable: true + }); + + return value; + }, + enumerable: true, + configurable: true + }); + }; + + /** @type {typeof import('color-convert')} */ + let colorConvert; + const makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => { + if (colorConvert === undefined) { + colorConvert = requireColorConvert$2(); + } + + const offset = isBackground ? 10 : 0; + const styles = {}; + + for (const [sourceSpace, suite] of Object.entries(colorConvert)) { + const name = sourceSpace === 'ansi16' ? 'ansi' : sourceSpace; + if (sourceSpace === targetSpace) { + styles[name] = wrap(identity, offset); + } else if (typeof suite === 'object') { + styles[name] = wrap(suite[targetSpace], offset); + } + } + + return styles; + }; + + function assembleStyles() { + const codes = new Map(); + const styles = { + modifier: { + reset: [0, 0], + // 21 isn't widely supported and 22 does the same thing + bold: [1, 22], + dim: [2, 22], + italic: [3, 23], + underline: [4, 24], + inverse: [7, 27], + hidden: [8, 28], + strikethrough: [9, 29] + }, + color: { + black: [30, 39], + red: [31, 39], + green: [32, 39], + yellow: [33, 39], + blue: [34, 39], + magenta: [35, 39], + cyan: [36, 39], + white: [37, 39], + + // Bright color + blackBright: [90, 39], + redBright: [91, 39], + greenBright: [92, 39], + yellowBright: [93, 39], + blueBright: [94, 39], + magentaBright: [95, 39], + cyanBright: [96, 39], + whiteBright: [97, 39] + }, + bgColor: { + bgBlack: [40, 49], + bgRed: [41, 49], + bgGreen: [42, 49], + bgYellow: [43, 49], + bgBlue: [44, 49], + bgMagenta: [45, 49], + bgCyan: [46, 49], + bgWhite: [47, 49], + + // Bright color + bgBlackBright: [100, 49], + bgRedBright: [101, 49], + bgGreenBright: [102, 49], + bgYellowBright: [103, 49], + bgBlueBright: [104, 49], + bgMagentaBright: [105, 49], + bgCyanBright: [106, 49], + bgWhiteBright: [107, 49] + } + }; + + // Alias bright black as gray (and grey) + styles.color.gray = styles.color.blackBright; + styles.bgColor.bgGray = styles.bgColor.bgBlackBright; + styles.color.grey = styles.color.blackBright; + styles.bgColor.bgGrey = styles.bgColor.bgBlackBright; + + for (const [groupName, group] of Object.entries(styles)) { + for (const [styleName, style] of Object.entries(group)) { + styles[styleName] = { + open: `\u001B[${style[0]}m`, + close: `\u001B[${style[1]}m` + }; + + group[styleName] = styles[styleName]; + + codes.set(style[0], style[1]); + } + + Object.defineProperty(styles, groupName, { + value: group, + enumerable: false + }); + } + + Object.defineProperty(styles, 'codes', { + value: codes, + enumerable: false + }); + + styles.color.close = '\u001B[39m'; + styles.bgColor.close = '\u001B[49m'; + + setLazyProperty(styles.color, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, false)); + setLazyProperty(styles.color, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, false)); + setLazyProperty(styles.color, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, false)); + setLazyProperty(styles.bgColor, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, true)); + setLazyProperty(styles.bgColor, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, true)); + setLazyProperty(styles.bgColor, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, true)); + + return styles; + } + + // Make the export immutable + Object.defineProperty(module, 'exports', { + enumerable: true, + get: assembleStyles + }); + } (ansiStyles$4)); + return ansiStyles$4.exports; +} + +var util$7; +var hasRequiredUtil; + +function requireUtil () { + if (hasRequiredUtil) return util$7; + hasRequiredUtil = 1; + + const stringReplaceAll = (string, substring, replacer) => { + let index = string.indexOf(substring); + if (index === -1) { + return string; + } + + const substringLength = substring.length; + let endIndex = 0; + let returnValue = ''; + do { + returnValue += string.substr(endIndex, index - endIndex) + substring + replacer; + endIndex = index + substringLength; + index = string.indexOf(substring, endIndex); + } while (index !== -1); + + returnValue += string.substr(endIndex); + return returnValue; + }; + + const stringEncaseCRLFWithFirstIndex = (string, prefix, postfix, index) => { + let endIndex = 0; + let returnValue = ''; + do { + const gotCR = string[index - 1] === '\r'; + returnValue += string.substr(endIndex, (gotCR ? index - 1 : index) - endIndex) + prefix + (gotCR ? '\r\n' : '\n') + postfix; + endIndex = index + 1; + index = string.indexOf('\n', endIndex); + } while (index !== -1); + + returnValue += string.substr(endIndex); + return returnValue; + }; + + util$7 = { + stringReplaceAll, + stringEncaseCRLFWithFirstIndex + }; + return util$7; +} + +var templates$1; +var hasRequiredTemplates$1; + +function requireTemplates$1 () { + if (hasRequiredTemplates$1) return templates$1; + hasRequiredTemplates$1 = 1; + const TEMPLATE_REGEX = /(?:\\(u(?:[a-f\d]{4}|\{[a-f\d]{1,6}\})|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi; + const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g; + const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/; + const ESCAPE_REGEX = /\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi; + + const ESCAPES = new Map([ + ['n', '\n'], + ['r', '\r'], + ['t', '\t'], + ['b', '\b'], + ['f', '\f'], + ['v', '\v'], + ['0', '\0'], + ['\\', '\\'], + ['e', '\u001B'], + ['a', '\u0007'] + ]); + + function unescape(c) { + const u = c[0] === 'u'; + const bracket = c[1] === '{'; + + if ((u && !bracket && c.length === 5) || (c[0] === 'x' && c.length === 3)) { + return String.fromCharCode(parseInt(c.slice(1), 16)); + } + + if (u && bracket) { + return String.fromCodePoint(parseInt(c.slice(2, -1), 16)); + } + + return ESCAPES.get(c) || c; + } + + function parseArguments(name, arguments_) { + const results = []; + const chunks = arguments_.trim().split(/\s*,\s*/g); + let matches; + + for (const chunk of chunks) { + const number = Number(chunk); + if (!Number.isNaN(number)) { + results.push(number); + } else if ((matches = chunk.match(STRING_REGEX))) { + results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, character) => escape ? unescape(escape) : character)); + } else { + throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`); + } + } + + return results; + } + + function parseStyle(style) { + STYLE_REGEX.lastIndex = 0; + + const results = []; + let matches; + + while ((matches = STYLE_REGEX.exec(style)) !== null) { + const name = matches[1]; + + if (matches[2]) { + const args = parseArguments(name, matches[2]); + results.push([name].concat(args)); + } else { + results.push([name]); + } + } + + return results; + } + + function buildStyle(chalk, styles) { + const enabled = {}; + + for (const layer of styles) { + for (const style of layer.styles) { + enabled[style[0]] = layer.inverse ? null : style.slice(1); + } + } + + let current = chalk; + for (const [styleName, styles] of Object.entries(enabled)) { + if (!Array.isArray(styles)) { + continue; + } + + if (!(styleName in current)) { + throw new Error(`Unknown Chalk style: ${styleName}`); + } + + current = styles.length > 0 ? current[styleName](...styles) : current[styleName]; + } + + return current; + } + + templates$1 = (chalk, temporary) => { + const styles = []; + const chunks = []; + let chunk = []; + + // eslint-disable-next-line max-params + temporary.replace(TEMPLATE_REGEX, (m, escapeCharacter, inverse, style, close, character) => { + if (escapeCharacter) { + chunk.push(unescape(escapeCharacter)); + } else if (style) { + const string = chunk.join(''); + chunk = []; + chunks.push(styles.length === 0 ? string : buildStyle(chalk, styles)(string)); + styles.push({inverse, styles: parseStyle(style)}); + } else if (close) { + if (styles.length === 0) { + throw new Error('Found extraneous } in Chalk template literal'); + } + + chunks.push(buildStyle(chalk, styles)(chunk.join(''))); + chunk = []; + styles.pop(); + } else { + chunk.push(character); + } + }); + + chunks.push(chunk.join('')); + + if (styles.length > 0) { + const errMessage = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`; + throw new Error(errMessage); + } + + return chunks.join(''); + }; + return templates$1; +} + +var source$1; +var hasRequiredSource; + +function requireSource () { + if (hasRequiredSource) return source$1; + hasRequiredSource = 1; + const ansiStyles = requireAnsiStyles(); + const {stdout: stdoutColor, stderr: stderrColor} = requireSupportsColor$2(); + const { + stringReplaceAll, + stringEncaseCRLFWithFirstIndex + } = requireUtil(); + + const {isArray} = Array; + + // `supportsColor.level` → `ansiStyles.color[name]` mapping + const levelMapping = [ + 'ansi', + 'ansi', + 'ansi256', + 'ansi16m' + ]; + + const styles = Object.create(null); + + const applyOptions = (object, options = {}) => { + if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) { + throw new Error('The `level` option should be an integer from 0 to 3'); + } + + // Detect level if not set manually + const colorLevel = stdoutColor ? stdoutColor.level : 0; + object.level = options.level === undefined ? colorLevel : options.level; + }; + + class ChalkClass { + constructor(options) { + // eslint-disable-next-line no-constructor-return + return chalkFactory(options); + } + } + + const chalkFactory = options => { + const chalk = {}; + applyOptions(chalk, options); + + chalk.template = (...arguments_) => chalkTag(chalk.template, ...arguments_); + + Object.setPrototypeOf(chalk, Chalk.prototype); + Object.setPrototypeOf(chalk.template, chalk); + + chalk.template.constructor = () => { + throw new Error('`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.'); + }; + + chalk.template.Instance = ChalkClass; + + return chalk.template; + }; + + function Chalk(options) { + return chalkFactory(options); + } + + for (const [styleName, style] of Object.entries(ansiStyles)) { + styles[styleName] = { + get() { + const builder = createBuilder(this, createStyler(style.open, style.close, this._styler), this._isEmpty); + Object.defineProperty(this, styleName, {value: builder}); + return builder; + } + }; + } + + styles.visible = { + get() { + const builder = createBuilder(this, this._styler, true); + Object.defineProperty(this, 'visible', {value: builder}); + return builder; + } + }; + + const usedModels = ['rgb', 'hex', 'keyword', 'hsl', 'hsv', 'hwb', 'ansi', 'ansi256']; + + for (const model of usedModels) { + styles[model] = { + get() { + const {level} = this; + return function (...arguments_) { + const styler = createStyler(ansiStyles.color[levelMapping[level]][model](...arguments_), ansiStyles.color.close, this._styler); + return createBuilder(this, styler, this._isEmpty); + }; + } + }; + } + + for (const model of usedModels) { + const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); + styles[bgModel] = { + get() { + const {level} = this; + return function (...arguments_) { + const styler = createStyler(ansiStyles.bgColor[levelMapping[level]][model](...arguments_), ansiStyles.bgColor.close, this._styler); + return createBuilder(this, styler, this._isEmpty); + }; + } + }; + } + + const proto = Object.defineProperties(() => {}, { + ...styles, + level: { + enumerable: true, + get() { + return this._generator.level; + }, + set(level) { + this._generator.level = level; + } + } + }); + + const createStyler = (open, close, parent) => { + let openAll; + let closeAll; + if (parent === undefined) { + openAll = open; + closeAll = close; + } else { + openAll = parent.openAll + open; + closeAll = close + parent.closeAll; + } + + return { + open, + close, + openAll, + closeAll, + parent + }; + }; + + const createBuilder = (self, _styler, _isEmpty) => { + const builder = (...arguments_) => { + if (isArray(arguments_[0]) && isArray(arguments_[0].raw)) { + // Called as a template literal, for example: chalk.red`2 + 3 = {bold ${2+3}}` + return applyStyle(builder, chalkTag(builder, ...arguments_)); + } + + // Single argument is hot path, implicit coercion is faster than anything + // eslint-disable-next-line no-implicit-coercion + return applyStyle(builder, (arguments_.length === 1) ? ('' + arguments_[0]) : arguments_.join(' ')); + }; + + // We alter the prototype because we must return a function, but there is + // no way to create a function with a different prototype + Object.setPrototypeOf(builder, proto); + + builder._generator = self; + builder._styler = _styler; + builder._isEmpty = _isEmpty; + + return builder; + }; + + const applyStyle = (self, string) => { + if (self.level <= 0 || !string) { + return self._isEmpty ? '' : string; + } + + let styler = self._styler; + + if (styler === undefined) { + return string; + } + + const {openAll, closeAll} = styler; + if (string.indexOf('\u001B') !== -1) { + while (styler !== undefined) { + // Replace any instances already present with a re-opening code + // otherwise only the part of the string until said closing code + // will be colored, and the rest will simply be 'plain'. + string = stringReplaceAll(string, styler.close, styler.open); + + styler = styler.parent; + } + } + + // We can move both next actions out of loop, because remaining actions in loop won't have + // any/visible effect on parts we add here. Close the styling before a linebreak and reopen + // after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92 + const lfIndex = string.indexOf('\n'); + if (lfIndex !== -1) { + string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex); + } + + return openAll + string + closeAll; + }; + + let template; + const chalkTag = (chalk, ...strings) => { + const [firstString] = strings; + + if (!isArray(firstString) || !isArray(firstString.raw)) { + // If chalk() was called by itself or with a string, + // return the string itself as a string. + return strings.join(' '); + } + + const arguments_ = strings.slice(1); + const parts = [firstString.raw[0]]; + + for (let i = 1; i < firstString.length; i++) { + parts.push( + String(arguments_[i - 1]).replace(/[{}\\]/g, '\\$&'), + String(firstString.raw[i]) + ); + } + + if (template === undefined) { + template = requireTemplates$1(); + } + + return template(chalk, parts.join('')); + }; + + Object.defineProperties(Chalk.prototype, styles); + + const chalk = Chalk(); // eslint-disable-line new-cap + chalk.supportsColor = stdoutColor; + chalk.stderr = Chalk({level: stderrColor ? stderrColor.level : 0}); // eslint-disable-line new-cap + chalk.stderr.supportsColor = stderrColor; + + source$1 = chalk; + return source$1; +} + +var json$1 = {}; + +var getMetaFromPath = {exports: {}}; + +var utils$3 = {}; + +var hasRequiredUtils; + +function requireUtils () { + if (hasRequiredUtils) return utils$3; + hasRequiredUtils = 1; + + Object.defineProperty(utils$3, "__esModule", { + value: true + }); + utils$3.getPointers = void 0; + // TODO: Better error handling + var getPointers = function getPointers(dataPath) { + var pointers = dataPath.split('/').slice(1); + for (var index in pointers) { + pointers[index] = pointers[index].split('~1').join('/').split('~0').join('~'); + } + return pointers; + }; + utils$3.getPointers = getPointers; + return utils$3; +} + +var hasRequiredGetMetaFromPath; + +function requireGetMetaFromPath () { + if (hasRequiredGetMetaFromPath) return getMetaFromPath.exports; + hasRequiredGetMetaFromPath = 1; + (function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports["default"] = getMetaFromPath; + var _utils = requireUtils(); + function getMetaFromPath(jsonAst, dataPath, includeIdentifierLocation) { + var pointers = (0, _utils.getPointers)(dataPath); + var lastPointerIndex = pointers.length - 1; + return pointers.reduce(function (obj, pointer, idx) { + switch (obj.type) { + case 'Object': + { + var filtered = obj.members.filter(function (child) { + return child.name.value === pointer; + }); + if (filtered.length !== 1) { + throw new Error("Couldn't find property ".concat(pointer, " of ").concat(dataPath)); + } + var _filtered$ = filtered[0], + name = _filtered$.name, + value = _filtered$.value; + return includeIdentifierLocation && idx === lastPointerIndex ? name : value; + } + case 'Array': + return obj.elements[pointer]; + default: + // eslint-disable-next-line no-console + console.log(obj); + } + }, jsonAst.body); + } + module.exports = exports.default; + } (getMetaFromPath, getMetaFromPath.exports)); + return getMetaFromPath.exports; +} + +var getDecoratedDataPath = {exports: {}}; + +var hasRequiredGetDecoratedDataPath; + +function requireGetDecoratedDataPath () { + if (hasRequiredGetDecoratedDataPath) return getDecoratedDataPath.exports; + hasRequiredGetDecoratedDataPath = 1; + (function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports["default"] = getDecoratedDataPath; + var _utils = requireUtils(); + function getTypeName(obj) { + if (!obj || !obj.elements) { + return ''; + } + var type = obj.elements.filter(function (child) { + return child && child.name && child.name.value === 'type'; + }); + if (!type.length) { + return ''; + } + return type[0].value && ":".concat(type[0].value.value) || ''; + } + function getDecoratedDataPath(jsonAst, dataPath) { + var decoratedPath = ''; + (0, _utils.getPointers)(dataPath).reduce(function (obj, pointer) { + switch (obj.type) { + case 'Object': + { + decoratedPath += "/".concat(pointer); + var filtered = obj.members.filter(function (child) { + return child.name.value === pointer; + }); + if (filtered.length !== 1) { + throw new Error("Couldn't find property ".concat(pointer, " of ").concat(dataPath)); + } + return filtered[0].value; + } + case 'Array': + { + decoratedPath += "/".concat(pointer).concat(getTypeName(obj.elements[pointer])); + return obj.elements[pointer]; + } + default: + // eslint-disable-next-line no-console + console.log(obj); + } + }, jsonAst.body); + return decoratedPath; + } + module.exports = exports.default; + } (getDecoratedDataPath, getDecoratedDataPath.exports)); + return getDecoratedDataPath.exports; +} + +var hasRequiredJson; + +function requireJson () { + if (hasRequiredJson) return json$1; + hasRequiredJson = 1; + (function (exports) { + + var _interopRequireDefault = interopRequireDefaultExports; + Object.defineProperty(exports, "__esModule", { + value: true + }); + Object.defineProperty(exports, "getDecoratedDataPath", { + enumerable: true, + get: function get() { + return _getDecoratedDataPath["default"]; + } + }); + Object.defineProperty(exports, "getMetaFromPath", { + enumerable: true, + get: function get() { + return _getMetaFromPath["default"]; + } + }); + var _getMetaFromPath = _interopRequireDefault(requireGetMetaFromPath()); + var _getDecoratedDataPath = _interopRequireDefault(requireGetDecoratedDataPath()); + } (json$1)); + return json$1; +} + +var hasRequiredBase; + +function requireBase () { + if (hasRequiredBase) return base.exports; + hasRequiredBase = 1; + (function (module, exports) { + + var _interopRequireDefault = interopRequireDefaultExports; + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports["default"] = void 0; + var _classCallCheck2 = _interopRequireDefault(requireClassCallCheck()); + var _createClass2 = _interopRequireDefault(requireCreateClass()); + var _codeFrame = requireLib(); + var _chalk = _interopRequireDefault(requireSource()); + var _json = requireJson(); + var BaseValidationError = /*#__PURE__*/function () { + // eslint-disable-next-line default-param-last + function BaseValidationError() { + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : { + isIdentifierLocation: false + }; + var _ref = arguments.length > 1 ? arguments[1] : undefined, + colorize = _ref.colorize, + data = _ref.data, + schema = _ref.schema, + jsonAst = _ref.jsonAst, + jsonRaw = _ref.jsonRaw; + (0, _classCallCheck2["default"])(this, BaseValidationError); + this.options = options; + this.colorize = !!(!!colorize || colorize === undefined); + this.data = data; + this.schema = schema; + this.jsonAst = jsonAst; + this.jsonRaw = jsonRaw; + } + (0, _createClass2["default"])(BaseValidationError, [{ + key: "getChalk", + value: function getChalk() { + return this.colorize ? _chalk["default"] : new _chalk["default"].Instance({ + level: 0 + }); + } + }, { + key: "getLocation", + value: function getLocation() { + var dataPath = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.instancePath; + var _this$options = this.options, + isIdentifierLocation = _this$options.isIdentifierLocation, + isSkipEndLocation = _this$options.isSkipEndLocation; + var _getMetaFromPath = (0, _json.getMetaFromPath)(this.jsonAst, dataPath, isIdentifierLocation), + loc = _getMetaFromPath.loc; + return { + start: loc.start, + end: isSkipEndLocation ? undefined : loc.end + }; + } + }, { + key: "getDecoratedPath", + value: function getDecoratedPath() { + var dataPath = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.instancePath; + return (0, _json.getDecoratedDataPath)(this.jsonAst, dataPath); + } + }, { + key: "getCodeFrame", + value: function getCodeFrame(message) { + var dataPath = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.instancePath; + return (0, _codeFrame.codeFrameColumns)(this.jsonRaw, this.getLocation(dataPath), { + /** + * `@babel/highlight`, by way of `@babel/code-frame`, highlights out entire block of raw JSON + * instead of just our `location` block -- so if you have a block of raw JSON that's upwards + * of 2mb+ and have a lot of errors to generate code frames for then we're re-highlighting + * the same huge chunk of code over and over and over and over again, all just so + * `@babel/code-frame` will eventually extract a small <10 line chunk out of it to return to + * us. + * + * Disabling `highlightCode` here will only disable highlighting the code we're showing users; + * if `options.colorize` is supplied to this library then the error message we're adding will + * still be highlighted. + */ + highlightCode: false, + message: message + }); + } + + /** + * @return {string} + */ + }, { + key: "instancePath", + get: function get() { + return typeof this.options.instancePath !== 'undefined' ? this.options.instancePath : this.options.dataPath; + } + }, { + key: "print", + value: function print() { + throw new Error("Implement the 'print' method inside ".concat(this.constructor.name, "!")); + } + }, { + key: "getError", + value: function getError() { + throw new Error("Implement the 'getError' method inside ".concat(this.constructor.name, "!")); + } + }]); + return BaseValidationError; + }(); + exports["default"] = BaseValidationError; + module.exports = exports.default; + } (base, base.exports)); + return base.exports; +} + +var hasRequiredAdditionalProp; + +function requireAdditionalProp () { + if (hasRequiredAdditionalProp) return additionalProp.exports; + hasRequiredAdditionalProp = 1; + (function (module, exports) { + + var _interopRequireDefault = interopRequireDefaultExports; + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports["default"] = void 0; + var _defineProperty2 = _interopRequireDefault(requireDefineProperty()); + var _taggedTemplateLiteral2 = _interopRequireDefault(requireTaggedTemplateLiteral()); + var _classCallCheck2 = _interopRequireDefault(requireClassCallCheck()); + var _createClass2 = _interopRequireDefault(requireCreateClass()); + var _inherits2 = _interopRequireDefault(requireInherits()); + var _possibleConstructorReturn2 = _interopRequireDefault(requirePossibleConstructorReturn()); + var _getPrototypeOf2 = _interopRequireDefault(requireGetPrototypeOf()); + var _base = _interopRequireDefault(requireBase()); + var _templateObject, _templateObject2; + 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) { (0, _defineProperty2["default"])(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 _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2["default"])(this, result); }; } + function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } + var AdditionalPropValidationError = /*#__PURE__*/function (_BaseValidationError) { + (0, _inherits2["default"])(AdditionalPropValidationError, _BaseValidationError); + var _super = _createSuper(AdditionalPropValidationError); + function AdditionalPropValidationError() { + var _this; + (0, _classCallCheck2["default"])(this, AdditionalPropValidationError); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + _this = _super.call.apply(_super, [this].concat(args)); + _this.name = 'AdditionalPropValidationError'; + _this.options.isIdentifierLocation = true; + return _this; + } + (0, _createClass2["default"])(AdditionalPropValidationError, [{ + key: "print", + value: function print() { + var _this$options = this.options, + message = _this$options.message, + params = _this$options.params; + var chalk = this.getChalk(); + var output = [chalk(_templateObject || (_templateObject = (0, _taggedTemplateLiteral2["default"])(["{red {bold ADDITIONAL PROPERTY} ", "}\n"], ["{red {bold ADDITIONAL PROPERTY} ", "}\\n"])), message)]; + return output.concat(this.getCodeFrame(chalk(_templateObject2 || (_templateObject2 = (0, _taggedTemplateLiteral2["default"])(["\uD83D\uDE32 {magentaBright ", "} is not expected to be here!"])), params.additionalProperty), "".concat(this.instancePath, "/").concat(params.additionalProperty))); + } + }, { + key: "getError", + value: function getError() { + var params = this.options.params; + return _objectSpread(_objectSpread({}, this.getLocation("".concat(this.instancePath, "/").concat(params.additionalProperty))), {}, { + error: "".concat(this.getDecoratedPath(), " Property ").concat(params.additionalProperty, " is not expected to be here"), + path: this.instancePath + }); + } + }]); + return AdditionalPropValidationError; + }(_base["default"]); + exports["default"] = AdditionalPropValidationError; + module.exports = exports.default; + } (additionalProp, additionalProp.exports)); + return additionalProp.exports; +} + +var _default = {exports: {}}; + +var hasRequired_default; + +function require_default () { + if (hasRequired_default) return _default.exports; + hasRequired_default = 1; + (function (module, exports) { + + var _interopRequireDefault = interopRequireDefaultExports; + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports["default"] = void 0; + var _defineProperty2 = _interopRequireDefault(requireDefineProperty()); + var _taggedTemplateLiteral2 = _interopRequireDefault(requireTaggedTemplateLiteral()); + var _classCallCheck2 = _interopRequireDefault(requireClassCallCheck()); + var _createClass2 = _interopRequireDefault(requireCreateClass()); + var _inherits2 = _interopRequireDefault(requireInherits()); + var _possibleConstructorReturn2 = _interopRequireDefault(requirePossibleConstructorReturn()); + var _getPrototypeOf2 = _interopRequireDefault(requireGetPrototypeOf()); + var _base = _interopRequireDefault(requireBase()); + var _templateObject, _templateObject2; + 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) { (0, _defineProperty2["default"])(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 _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2["default"])(this, result); }; } + function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } + var DefaultValidationError = /*#__PURE__*/function (_BaseValidationError) { + (0, _inherits2["default"])(DefaultValidationError, _BaseValidationError); + var _super = _createSuper(DefaultValidationError); + function DefaultValidationError() { + var _this; + (0, _classCallCheck2["default"])(this, DefaultValidationError); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + _this = _super.call.apply(_super, [this].concat(args)); + _this.name = 'DefaultValidationError'; + _this.options.isSkipEndLocation = true; + return _this; + } + (0, _createClass2["default"])(DefaultValidationError, [{ + key: "print", + value: function print() { + var _this$options = this.options, + keyword = _this$options.keyword, + message = _this$options.message; + var chalk = this.getChalk(); + var output = [chalk(_templateObject || (_templateObject = (0, _taggedTemplateLiteral2["default"])(["{red {bold ", "} ", "}\n"], ["{red {bold ", "} ", "}\\n"])), keyword.toUpperCase(), message)]; + return output.concat(this.getCodeFrame(chalk(_templateObject2 || (_templateObject2 = (0, _taggedTemplateLiteral2["default"])(["\uD83D\uDC48\uD83C\uDFFD {magentaBright ", "} ", ""])), keyword, message))); + } + }, { + key: "getError", + value: function getError() { + var _this$options2 = this.options, + keyword = _this$options2.keyword, + message = _this$options2.message; + return _objectSpread(_objectSpread({}, this.getLocation()), {}, { + error: "".concat(this.getDecoratedPath(), ": ").concat(keyword, " ").concat(message), + path: this.instancePath + }); + } + }]); + return DefaultValidationError; + }(_base["default"]); + exports["default"] = DefaultValidationError; + module.exports = exports.default; + } (_default, _default.exports)); + return _default.exports; +} + +var _enum$1 = {exports: {}}; + +var jsonpointer = {}; + +var hasExcape = /~/; +var escapeMatcher = /~[01]/g; +function escapeReplacer (m) { + switch (m) { + case '~1': return '/' + case '~0': return '~' + } + throw new Error('Invalid tilde escape: ' + m) +} + +function untilde (str) { + if (!hasExcape.test(str)) return str + return str.replace(escapeMatcher, escapeReplacer) +} + +function setter (obj, pointer, value) { + var part; + var hasNextPart; + + for (var p = 1, len = pointer.length; p < len;) { + if (pointer[p] === 'constructor' || pointer[p] === 'prototype' || pointer[p] === '__proto__') return obj + + part = untilde(pointer[p++]); + hasNextPart = len > p; + + if (typeof obj[part] === 'undefined') { + // support setting of /- + if (Array.isArray(obj) && part === '-') { + part = obj.length; + } + + // support nested objects/array when setting values + if (hasNextPart) { + if ((pointer[p] !== '' && pointer[p] < Infinity) || pointer[p] === '-') obj[part] = []; + else obj[part] = {}; + } + } + + if (!hasNextPart) break + obj = obj[part]; + } + + var oldValue = obj[part]; + if (value === undefined) delete obj[part]; + else obj[part] = value; + return oldValue +} + +function compilePointer (pointer) { + if (typeof pointer === 'string') { + pointer = pointer.split('/'); + if (pointer[0] === '') return pointer + throw new Error('Invalid JSON pointer.') + } else if (Array.isArray(pointer)) { + for (const part of pointer) { + if (typeof part !== 'string' && typeof part !== 'number') { + throw new Error('Invalid JSON pointer. Must be of type string or number.') + } + } + return pointer + } + + throw new Error('Invalid JSON pointer.') +} + +function get$7 (obj, pointer) { + if (typeof obj !== 'object') throw new Error('Invalid input object.') + pointer = compilePointer(pointer); + var len = pointer.length; + if (len === 1) return obj + + for (var p = 1; p < len;) { + obj = obj[untilde(pointer[p++])]; + if (len === p) return obj + if (typeof obj !== 'object' || obj === null) return undefined + } +} + +function set$1 (obj, pointer, value) { + if (typeof obj !== 'object') throw new Error('Invalid input object.') + pointer = compilePointer(pointer); + if (pointer.length === 0) throw new Error('Invalid JSON pointer for set.') + return setter(obj, pointer, value) +} + +function compile$1 (pointer) { + var compiled = compilePointer(pointer); + return { + get: function (object) { + return get$7(object, compiled) + }, + set: function (object, value) { + return set$1(object, compiled, value) + } + } +} + +jsonpointer.get = get$7; +jsonpointer.set = set$1; +jsonpointer.compile = compile$1; + +var leven = {exports: {}}; + +var hasRequiredLeven; + +function requireLeven () { + if (hasRequiredLeven) return leven.exports; + hasRequiredLeven = 1; + const array = []; + const charCodeCache = []; + + const leven$1 = (left, right) => { + if (left === right) { + return 0; + } + + const swap = left; + + // Swapping the strings if `a` is longer than `b` so we know which one is the + // shortest & which one is the longest + if (left.length > right.length) { + left = right; + right = swap; + } + + let leftLength = left.length; + let rightLength = right.length; + + // Performing suffix trimming: + // We can linearly drop suffix common to both strings since they + // don't increase distance at all + // Note: `~-` is the bitwise way to perform a `- 1` operation + while (leftLength > 0 && (left.charCodeAt(~-leftLength) === right.charCodeAt(~-rightLength))) { + leftLength--; + rightLength--; + } + + // Performing prefix trimming + // We can linearly drop prefix common to both strings since they + // don't increase distance at all + let start = 0; + + while (start < leftLength && (left.charCodeAt(start) === right.charCodeAt(start))) { + start++; + } + + leftLength -= start; + rightLength -= start; + + if (leftLength === 0) { + return rightLength; + } + + let bCharCode; + let result; + let temp; + let temp2; + let i = 0; + let j = 0; + + while (i < leftLength) { + charCodeCache[i] = left.charCodeAt(start + i); + array[i] = ++i; + } + + while (j < rightLength) { + bCharCode = right.charCodeAt(start + j); + temp = j++; + result = j; + + for (i = 0; i < leftLength; i++) { + temp2 = bCharCode === charCodeCache[i] ? temp : temp + 1; + temp = array[i]; + // eslint-disable-next-line no-multi-assign + result = array[i] = temp > result ? temp2 > result ? result + 1 : temp2 : temp2 > temp ? temp + 1 : temp2; + } + } + + return result; + }; + + leven.exports = leven$1; + // TODO: Remove this for the next major release + leven.exports.default = leven$1; + return leven.exports; +} + +var hasRequired_enum; + +function require_enum () { + if (hasRequired_enum) return _enum$1.exports; + hasRequired_enum = 1; + (function (module, exports) { + + var _interopRequireDefault = interopRequireDefaultExports; + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports["default"] = void 0; + var _defineProperty2 = _interopRequireDefault(requireDefineProperty()); + var _taggedTemplateLiteral2 = _interopRequireDefault(requireTaggedTemplateLiteral()); + var _classCallCheck2 = _interopRequireDefault(requireClassCallCheck()); + var _createClass2 = _interopRequireDefault(requireCreateClass()); + var _inherits2 = _interopRequireDefault(requireInherits()); + var _possibleConstructorReturn2 = _interopRequireDefault(requirePossibleConstructorReturn()); + var _getPrototypeOf2 = _interopRequireDefault(requireGetPrototypeOf()); + var _jsonpointer = _interopRequireDefault(jsonpointer); + var _leven = _interopRequireDefault(requireLeven()); + var _base = _interopRequireDefault(requireBase()); + var _templateObject, _templateObject2, _templateObject3, _templateObject4; + 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) { (0, _defineProperty2["default"])(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 _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2["default"])(this, result); }; } + function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } + var EnumValidationError = /*#__PURE__*/function (_BaseValidationError) { + (0, _inherits2["default"])(EnumValidationError, _BaseValidationError); + var _super = _createSuper(EnumValidationError); + function EnumValidationError() { + var _this; + (0, _classCallCheck2["default"])(this, EnumValidationError); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + _this = _super.call.apply(_super, [this].concat(args)); + _this.name = 'EnumValidationError'; + return _this; + } + (0, _createClass2["default"])(EnumValidationError, [{ + key: "print", + value: function print() { + var _this$options = this.options, + message = _this$options.message, + allowedValues = _this$options.params.allowedValues; + var chalk = this.getChalk(); + var bestMatch = this.findBestMatch(); + var output = [chalk(_templateObject || (_templateObject = (0, _taggedTemplateLiteral2["default"])(["{red {bold ENUM} ", "}"])), message), chalk(_templateObject2 || (_templateObject2 = (0, _taggedTemplateLiteral2["default"])(["{red (", ")}\n"], ["{red (", ")}\\n"])), allowedValues.join(', '))]; + return output.concat(this.getCodeFrame(bestMatch !== null ? chalk(_templateObject3 || (_templateObject3 = (0, _taggedTemplateLiteral2["default"])(["\uD83D\uDC48\uD83C\uDFFD Did you mean {magentaBright ", "} here?"])), bestMatch) : chalk(_templateObject4 || (_templateObject4 = (0, _taggedTemplateLiteral2["default"])(["\uD83D\uDC48\uD83C\uDFFD Unexpected value, should be equal to one of the allowed values"]))))); + } + }, { + key: "getError", + value: function getError() { + var _this$options2 = this.options, + message = _this$options2.message, + params = _this$options2.params; + var bestMatch = this.findBestMatch(); + var allowedValues = params.allowedValues.join(', '); + var output = _objectSpread(_objectSpread({}, this.getLocation()), {}, { + error: "".concat(this.getDecoratedPath(), " ").concat(message, ": ").concat(allowedValues), + path: this.instancePath + }); + if (bestMatch !== null) { + output.suggestion = "Did you mean ".concat(bestMatch, "?"); + } + return output; + } + }, { + key: "findBestMatch", + value: function findBestMatch() { + var allowedValues = this.options.params.allowedValues; + var currentValue = this.instancePath === '' ? this.data : _jsonpointer["default"].get(this.data, this.instancePath); + if (!currentValue) { + return null; + } + var bestMatch = allowedValues.map(function (value) { + return { + value: value, + weight: (0, _leven["default"])(value, currentValue.toString()) + }; + }).sort(function (x, y) { + return x.weight > y.weight ? 1 : x.weight < y.weight ? -1 : 0; + })[0]; + return allowedValues.length === 1 || bestMatch.weight < bestMatch.value.length ? bestMatch.value : null; + } + }]); + return EnumValidationError; + }(_base["default"]); + exports["default"] = EnumValidationError; + module.exports = exports.default; + } (_enum$1, _enum$1.exports)); + return _enum$1.exports; +} + +var pattern$1 = {exports: {}}; + +var hasRequiredPattern; + +function requirePattern () { + if (hasRequiredPattern) return pattern$1.exports; + hasRequiredPattern = 1; + (function (module, exports) { + + var _interopRequireDefault = interopRequireDefaultExports; + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports["default"] = void 0; + var _defineProperty2 = _interopRequireDefault(requireDefineProperty()); + var _taggedTemplateLiteral2 = _interopRequireDefault(requireTaggedTemplateLiteral()); + var _classCallCheck2 = _interopRequireDefault(requireClassCallCheck()); + var _createClass2 = _interopRequireDefault(requireCreateClass()); + var _inherits2 = _interopRequireDefault(requireInherits()); + var _possibleConstructorReturn2 = _interopRequireDefault(requirePossibleConstructorReturn()); + var _getPrototypeOf2 = _interopRequireDefault(requireGetPrototypeOf()); + var _base = _interopRequireDefault(requireBase()); + var _templateObject, _templateObject2; + 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) { (0, _defineProperty2["default"])(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 _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2["default"])(this, result); }; } + function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } + var PatternValidationError = /*#__PURE__*/function (_BaseValidationError) { + (0, _inherits2["default"])(PatternValidationError, _BaseValidationError); + var _super = _createSuper(PatternValidationError); + function PatternValidationError() { + var _this; + (0, _classCallCheck2["default"])(this, PatternValidationError); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + _this = _super.call.apply(_super, [this].concat(args)); + _this.name = 'PatternValidationError'; + _this.options.isIdentifierLocation = true; + return _this; + } + (0, _createClass2["default"])(PatternValidationError, [{ + key: "print", + value: function print() { + var _this$options = this.options, + message = _this$options.message, + params = _this$options.params, + propertyName = _this$options.propertyName; + var chalk = this.getChalk(); + var output = [chalk(_templateObject || (_templateObject = (0, _taggedTemplateLiteral2["default"])(["{red {bold PROPERTY} ", "}\n"], ["{red {bold PROPERTY} ", "}\\n"])), message)]; + return output.concat(this.getCodeFrame(chalk(_templateObject2 || (_templateObject2 = (0, _taggedTemplateLiteral2["default"])(["\uD83D\uDE32 must match pattern {magentaBright ", "}"])), params.pattern), "".concat(this.instancePath, "/").concat(propertyName))); + } + }, { + key: "getError", + value: function getError() { + var _this$options2 = this.options, + params = _this$options2.params, + propertyName = _this$options2.propertyName; + return _objectSpread(_objectSpread({}, this.getLocation()), {}, { + error: "".concat(this.getDecoratedPath(), " Property \"").concat(propertyName, "\" must match pattern ").concat(params.pattern), + path: this.instancePath + }); + } + }]); + return PatternValidationError; + }(_base["default"]); + exports["default"] = PatternValidationError; + module.exports = exports.default; + } (pattern$1, pattern$1.exports)); + return pattern$1.exports; +} + +var required$3 = {exports: {}}; + +var get$6 = {exports: {}}; + +var superPropBase = {exports: {}}; + +var hasRequiredSuperPropBase; + +function requireSuperPropBase () { + if (hasRequiredSuperPropBase) return superPropBase.exports; + hasRequiredSuperPropBase = 1; + (function (module) { + var getPrototypeOf = requireGetPrototypeOf(); + function _superPropBase(object, property) { + while (!Object.prototype.hasOwnProperty.call(object, property)) { + object = getPrototypeOf(object); + if (object === null) break; + } + return object; + } + module.exports = _superPropBase, module.exports.__esModule = true, module.exports["default"] = module.exports; + } (superPropBase)); + return superPropBase.exports; +} + +var hasRequiredGet$1; + +function requireGet$1 () { + if (hasRequiredGet$1) return get$6.exports; + hasRequiredGet$1 = 1; + (function (module) { + var superPropBase = requireSuperPropBase(); + function _get() { + if (typeof Reflect !== "undefined" && Reflect.get) { + module.exports = _get = Reflect.get.bind(), module.exports.__esModule = true, module.exports["default"] = module.exports; + } else { + module.exports = _get = function _get(target, property, receiver) { + var base = superPropBase(target, property); + if (!base) return; + var desc = Object.getOwnPropertyDescriptor(base, property); + if (desc.get) { + return desc.get.call(arguments.length < 3 ? target : receiver); + } + return desc.value; + }, module.exports.__esModule = true, module.exports["default"] = module.exports; + } + return _get.apply(this, arguments); + } + module.exports = _get, module.exports.__esModule = true, module.exports["default"] = module.exports; + } (get$6)); + return get$6.exports; +} + +var hasRequiredRequired; + +function requireRequired () { + if (hasRequiredRequired) return required$3.exports; + hasRequiredRequired = 1; + (function (module, exports) { + + var _interopRequireDefault = interopRequireDefaultExports; + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports["default"] = void 0; + var _defineProperty2 = _interopRequireDefault(requireDefineProperty()); + var _taggedTemplateLiteral2 = _interopRequireDefault(requireTaggedTemplateLiteral()); + var _classCallCheck2 = _interopRequireDefault(requireClassCallCheck()); + var _createClass2 = _interopRequireDefault(requireCreateClass()); + var _get2 = _interopRequireDefault(requireGet$1()); + var _inherits2 = _interopRequireDefault(requireInherits()); + var _possibleConstructorReturn2 = _interopRequireDefault(requirePossibleConstructorReturn()); + var _getPrototypeOf2 = _interopRequireDefault(requireGetPrototypeOf()); + var _base = _interopRequireDefault(requireBase()); + var _templateObject, _templateObject2; + 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) { (0, _defineProperty2["default"])(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 _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2["default"])(this, result); }; } + function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } + var RequiredValidationError = /*#__PURE__*/function (_BaseValidationError) { + (0, _inherits2["default"])(RequiredValidationError, _BaseValidationError); + var _super = _createSuper(RequiredValidationError); + function RequiredValidationError() { + var _this; + (0, _classCallCheck2["default"])(this, RequiredValidationError); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + _this = _super.call.apply(_super, [this].concat(args)); + _this.name = 'RequiredValidationError'; + return _this; + } + (0, _createClass2["default"])(RequiredValidationError, [{ + key: "getLocation", + value: function getLocation() { + var dataPath = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.instancePath; + var _get$call = (0, _get2["default"])((0, _getPrototypeOf2["default"])(RequiredValidationError.prototype), "getLocation", this).call(this, dataPath), + start = _get$call.start; + return { + start: start + }; + } + }, { + key: "print", + value: function print() { + var _this$options = this.options, + message = _this$options.message, + params = _this$options.params; + var chalk = this.getChalk(); + var output = [chalk(_templateObject || (_templateObject = (0, _taggedTemplateLiteral2["default"])(["{red {bold REQUIRED} ", "}\n"], ["{red {bold REQUIRED} ", "}\\n"])), message)]; + return output.concat(this.getCodeFrame(chalk(_templateObject2 || (_templateObject2 = (0, _taggedTemplateLiteral2["default"])(["\u2639\uFE0F {magentaBright ", "} is missing here!"])), params.missingProperty))); + } + }, { + key: "getError", + value: function getError() { + var message = this.options.message; + return _objectSpread(_objectSpread({}, this.getLocation()), {}, { + error: "".concat(this.getDecoratedPath(), " ").concat(message), + path: this.instancePath + }); + } + }]); + return RequiredValidationError; + }(_base["default"]); + exports["default"] = RequiredValidationError; + module.exports = exports.default; + } (required$3, required$3.exports)); + return required$3.exports; +} + +var unevaluatedProp = {exports: {}}; + +var hasRequiredUnevaluatedProp; + +function requireUnevaluatedProp () { + if (hasRequiredUnevaluatedProp) return unevaluatedProp.exports; + hasRequiredUnevaluatedProp = 1; + (function (module, exports) { + + var _interopRequireDefault = interopRequireDefaultExports; + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports["default"] = void 0; + var _defineProperty2 = _interopRequireDefault(requireDefineProperty()); + var _taggedTemplateLiteral2 = _interopRequireDefault(requireTaggedTemplateLiteral()); + var _classCallCheck2 = _interopRequireDefault(requireClassCallCheck()); + var _createClass2 = _interopRequireDefault(requireCreateClass()); + var _inherits2 = _interopRequireDefault(requireInherits()); + var _possibleConstructorReturn2 = _interopRequireDefault(requirePossibleConstructorReturn()); + var _getPrototypeOf2 = _interopRequireDefault(requireGetPrototypeOf()); + var _base = _interopRequireDefault(requireBase()); + var _templateObject, _templateObject2; + 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) { (0, _defineProperty2["default"])(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 _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2["default"])(this, result); }; } + function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } + var UnevaluatedPropValidationError = /*#__PURE__*/function (_BaseValidationError) { + (0, _inherits2["default"])(UnevaluatedPropValidationError, _BaseValidationError); + var _super = _createSuper(UnevaluatedPropValidationError); + function UnevaluatedPropValidationError() { + var _this; + (0, _classCallCheck2["default"])(this, UnevaluatedPropValidationError); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + _this = _super.call.apply(_super, [this].concat(args)); + _this.name = 'UnevaluatedPropValidationError'; + _this.options.isIdentifierLocation = true; + return _this; + } + (0, _createClass2["default"])(UnevaluatedPropValidationError, [{ + key: "print", + value: function print() { + var _this$options = this.options, + message = _this$options.message, + params = _this$options.params; + var chalk = this.getChalk(); + var output = [chalk(_templateObject || (_templateObject = (0, _taggedTemplateLiteral2["default"])(["{red {bold UNEVALUATED PROPERTY} ", "}\n"], ["{red {bold UNEVALUATED PROPERTY} ", "}\\n"])), message)]; + return output.concat(this.getCodeFrame(chalk(_templateObject2 || (_templateObject2 = (0, _taggedTemplateLiteral2["default"])(["\uD83D\uDE32 {magentaBright ", "} is not expected to be here!"])), params.unevaluatedProperty), "".concat(this.instancePath, "/").concat(params.unevaluatedProperty))); + } + }, { + key: "getError", + value: function getError() { + var params = this.options.params; + return _objectSpread(_objectSpread({}, this.getLocation("".concat(this.instancePath, "/").concat(params.unevaluatedProperty))), {}, { + error: "".concat(this.getDecoratedPath(), " Property ").concat(params.unevaluatedProperty, " is not expected to be here"), + path: this.instancePath + }); + } + }]); + return UnevaluatedPropValidationError; + }(_base["default"]); + exports["default"] = UnevaluatedPropValidationError; + module.exports = exports.default; + } (unevaluatedProp, unevaluatedProp.exports)); + return unevaluatedProp.exports; +} + +var hasRequiredValidationErrors; + +function requireValidationErrors () { + if (hasRequiredValidationErrors) return validationErrors; + hasRequiredValidationErrors = 1; + (function (exports) { + + var _interopRequireDefault = interopRequireDefaultExports; + Object.defineProperty(exports, "__esModule", { + value: true + }); + Object.defineProperty(exports, "AdditionalPropValidationError", { + enumerable: true, + get: function get() { + return _additionalProp["default"]; + } + }); + Object.defineProperty(exports, "DefaultValidationError", { + enumerable: true, + get: function get() { + return _default["default"]; + } + }); + Object.defineProperty(exports, "EnumValidationError", { + enumerable: true, + get: function get() { + return _enum["default"]; + } + }); + Object.defineProperty(exports, "PatternValidationError", { + enumerable: true, + get: function get() { + return _pattern["default"]; + } + }); + Object.defineProperty(exports, "RequiredValidationError", { + enumerable: true, + get: function get() { + return _required["default"]; + } + }); + Object.defineProperty(exports, "UnevaluatedPropValidationError", { + enumerable: true, + get: function get() { + return _unevaluatedProp["default"]; + } + }); + var _additionalProp = _interopRequireDefault(requireAdditionalProp()); + var _default = _interopRequireDefault(require_default()); + var _enum = _interopRequireDefault(require_enum()); + var _pattern = _interopRequireDefault(requirePattern()); + var _required = _interopRequireDefault(requireRequired()); + var _unevaluatedProp = _interopRequireDefault(requireUnevaluatedProp()); + } (validationErrors)); + return validationErrors; +} + +var hasRequiredHelpers; + +function requireHelpers () { + if (hasRequiredHelpers) return helpers; + hasRequiredHelpers = 1; + (function (exports) { + + var _interopRequireDefault = interopRequireDefaultExports; + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.createErrorInstances = createErrorInstances; + exports["default"] = prettify; + exports.filterRedundantErrors = filterRedundantErrors; + exports.makeTree = makeTree; + var _defineProperty2 = _interopRequireDefault(requireDefineProperty()); + var _toConsumableArray2 = _interopRequireDefault(requireToConsumableArray()); + var _slicedToArray2 = _interopRequireDefault(requireSlicedToArray()); + var _utils = requireUtils$1(); + var _validationErrors = requireValidationErrors(); + 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) { (0, _defineProperty2["default"])(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; } + // eslint-disable-next-line unicorn/no-unsafe-regex + var JSON_POINTERS_REGEX = /\/[\w_-]+(\/\d+)?/g; + + // Make a tree of errors from ajv errors array + function makeTree() { + var ajvErrors = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; + var root = { + children: {} + }; + ajvErrors.forEach(function (ajvError) { + var instancePath = typeof ajvError.instancePath !== 'undefined' ? ajvError.instancePath : ajvError.dataPath; + + // `dataPath === ''` is root + var paths = instancePath === '' ? [''] : instancePath.match(JSON_POINTERS_REGEX); + if (paths) { + paths.reduce(function (obj, path, i) { + obj.children[path] = obj.children[path] || { + children: {}, + errors: [] + }; + if (i === paths.length - 1) { + obj.children[path].errors.push(ajvError); + } + return obj.children[path]; + }, root); + } + }); + return root; + } + function filterRedundantErrors(root, parent, key) { + /** + * If there is a `required` error then we can just skip everythig else. + * And, also `required` should have more priority than `anyOf`. @see #8 + */ + (0, _utils.getErrors)(root).forEach(function (error) { + if ((0, _utils.isRequiredError)(error)) { + root.errors = [error]; + root.children = {}; + } + }); + + /** + * If there is an `anyOf` error that means we have more meaningful errors + * inside children. So we will just remove all errors from this level. + * + * If there are no children, then we don't delete the errors since we should + * have at least one error to report. + */ + if ((0, _utils.getErrors)(root).some(_utils.isAnyOfError)) { + if (Object.keys(root.children).length > 0) { + delete root.errors; + } + } + + /** + * If all errors are `enum` and siblings have any error then we can safely + * ignore the node. + * + * **CAUTION** + * Need explicit `root.errors` check because `[].every(fn) === true` + * https://en.wikipedia.org/wiki/Vacuous_truth#Vacuous_truths_in_mathematics + */ + if (root.errors && root.errors.length && (0, _utils.getErrors)(root).every(_utils.isEnumError)) { + if ((0, _utils.getSiblings)(parent)(root) + // Remove any reference which becomes `undefined` later + .filter(_utils.notUndefined).some(_utils.getErrors)) { + delete parent.children[key]; + } + } + Object.entries(root.children).forEach(function (_ref) { + var _ref2 = (0, _slicedToArray2["default"])(_ref, 2), + k = _ref2[0], + child = _ref2[1]; + return filterRedundantErrors(child, root, k); + }); + } + function createErrorInstances(root, options) { + var errors = (0, _utils.getErrors)(root); + if (errors.length && errors.every(_utils.isEnumError)) { + var uniqueValues = new Set((0, _utils.concatAll)([])(errors.map(function (e) { + return e.params.allowedValues; + }))); + var allowedValues = (0, _toConsumableArray2["default"])(uniqueValues); + var error = errors[0]; + return [new _validationErrors.EnumValidationError(_objectSpread(_objectSpread({}, error), {}, { + params: { + allowedValues: allowedValues + } + }), options)]; + } + return (0, _utils.concatAll)(errors.reduce(function (ret, error) { + switch (error.keyword) { + case 'additionalProperties': + return ret.concat(new _validationErrors.AdditionalPropValidationError(error, options)); + case 'pattern': + return ret.concat(new _validationErrors.PatternValidationError(error, options)); + case 'required': + return ret.concat(new _validationErrors.RequiredValidationError(error, options)); + case 'unevaluatedProperties': + return ret.concat(new _validationErrors.UnevaluatedPropValidationError(error, options)); + default: + return ret.concat(new _validationErrors.DefaultValidationError(error, options)); + } + }, []))((0, _utils.getChildren)(root).map(function (child) { + return createErrorInstances(child, options); + })); + } + function prettify(ajvErrors, options) { + var tree = makeTree(ajvErrors || []); + filterRedundantErrors(tree); + return createErrorInstances(tree, options); + } + } (helpers)); + return helpers; +} + +(function (module, exports) { + + var _interopRequireDefault = interopRequireDefaultExports; + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports["default"] = betterAjvErrors; + var _momoa = api$1; + var _helpers = _interopRequireDefault(requireHelpers()); + function betterAjvErrors(schema, data, errors) { + var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; + var _options$colorize = options.colorize, + colorize = _options$colorize === void 0 ? true : _options$colorize, + _options$format = options.format, + format = _options$format === void 0 ? 'cli' : _options$format, + _options$indent = options.indent, + indent = _options$indent === void 0 ? null : _options$indent, + _options$json = options.json, + json = _options$json === void 0 ? null : _options$json; + var jsonRaw = json || JSON.stringify(data, null, indent); + var jsonAst = (0, _momoa.parse)(jsonRaw); + var customErrorToText = function customErrorToText(error) { + return error.print().join('\n'); + }; + var customErrorToStructure = function customErrorToStructure(error) { + return error.getError(); + }; + var customErrors = (0, _helpers["default"])(errors, { + colorize: colorize, + data: data, + schema: schema, + jsonAst: jsonAst, + jsonRaw: jsonRaw + }); + if (format === 'cli') { + return customErrors.map(customErrorToText).join('\n\n'); + } + return customErrors.map(customErrorToStructure); + } + module.exports = exports.default; +} (lib$f, lib$f.exports)); + +var libExports = lib$f.exports; + +var _2020 = {exports: {}}; + +var core$6 = {}; + +var validate = {}; + +var boolSchema = {}; + +var errors$1 = {}; + +var codegen = {}; + +var code$1 = {}; + +var hasRequiredCode$1; + +function requireCode$1 () { + if (hasRequiredCode$1) return code$1; + hasRequiredCode$1 = 1; + (function (exports) { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.regexpCode = exports.getEsmExportName = exports.getProperty = exports.safeStringify = exports.stringify = exports.strConcat = exports.addCodeArg = exports.str = exports._ = exports.nil = exports._Code = exports.Name = exports.IDENTIFIER = exports._CodeOrName = void 0; + class _CodeOrName { + } + exports._CodeOrName = _CodeOrName; + exports.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i; + class Name extends _CodeOrName { + constructor(s) { + super(); + if (!exports.IDENTIFIER.test(s)) + throw new Error("CodeGen: name must be a valid identifier"); + this.str = s; + } + toString() { + return this.str; + } + emptyStr() { + return false; + } + get names() { + return { [this.str]: 1 }; + } + } + exports.Name = Name; + class _Code extends _CodeOrName { + constructor(code) { + super(); + this._items = typeof code === "string" ? [code] : code; + } + toString() { + return this.str; + } + emptyStr() { + if (this._items.length > 1) + return false; + const item = this._items[0]; + return item === "" || item === '""'; + } + get str() { + var _a; + return ((_a = this._str) !== null && _a !== void 0 ? _a : (this._str = this._items.reduce((s, c) => `${s}${c}`, ""))); + } + get names() { + var _a; + return ((_a = this._names) !== null && _a !== void 0 ? _a : (this._names = this._items.reduce((names, c) => { + if (c instanceof Name) + names[c.str] = (names[c.str] || 0) + 1; + return names; + }, {}))); + } + } + exports._Code = _Code; + exports.nil = new _Code(""); + function _(strs, ...args) { + const code = [strs[0]]; + let i = 0; + while (i < args.length) { + addCodeArg(code, args[i]); + code.push(strs[++i]); + } + return new _Code(code); + } + exports._ = _; + const plus = new _Code("+"); + function str(strs, ...args) { + const expr = [safeStringify(strs[0])]; + let i = 0; + while (i < args.length) { + expr.push(plus); + addCodeArg(expr, args[i]); + expr.push(plus, safeStringify(strs[++i])); + } + optimize(expr); + return new _Code(expr); + } + exports.str = str; + function addCodeArg(code, arg) { + if (arg instanceof _Code) + code.push(...arg._items); + else if (arg instanceof Name) + code.push(arg); + else + code.push(interpolate(arg)); + } + exports.addCodeArg = addCodeArg; + function optimize(expr) { + let i = 1; + while (i < expr.length - 1) { + if (expr[i] === plus) { + const res = mergeExprItems(expr[i - 1], expr[i + 1]); + if (res !== undefined) { + expr.splice(i - 1, 3, res); + continue; + } + expr[i++] = "+"; + } + i++; + } + } + function mergeExprItems(a, b) { + if (b === '""') + return a; + if (a === '""') + return b; + if (typeof a == "string") { + if (b instanceof Name || a[a.length - 1] !== '"') + return; + if (typeof b != "string") + return `${a.slice(0, -1)}${b}"`; + if (b[0] === '"') + return a.slice(0, -1) + b.slice(1); + return; + } + if (typeof b == "string" && b[0] === '"' && !(a instanceof Name)) + return `"${a}${b.slice(1)}`; + return; + } + function strConcat(c1, c2) { + return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str `${c1}${c2}`; + } + exports.strConcat = strConcat; + // TODO do not allow arrays here + function interpolate(x) { + return typeof x == "number" || typeof x == "boolean" || x === null + ? x + : safeStringify(Array.isArray(x) ? x.join(",") : x); + } + function stringify(x) { + return new _Code(safeStringify(x)); + } + exports.stringify = stringify; + function safeStringify(x) { + return JSON.stringify(x) + .replace(/\u2028/g, "\\u2028") + .replace(/\u2029/g, "\\u2029"); + } + exports.safeStringify = safeStringify; + function getProperty(key) { + return typeof key == "string" && exports.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _ `[${key}]`; + } + exports.getProperty = getProperty; + //Does best effort to format the name properly + function getEsmExportName(key) { + if (typeof key == "string" && exports.IDENTIFIER.test(key)) { + return new _Code(`${key}`); + } + throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`); + } + exports.getEsmExportName = getEsmExportName; + function regexpCode(rx) { + return new _Code(rx.toString()); + } + exports.regexpCode = regexpCode; + + } (code$1)); + return code$1; +} + +var scope = {}; + +var hasRequiredScope; + +function requireScope () { + if (hasRequiredScope) return scope; + hasRequiredScope = 1; + (function (exports) { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ValueScope = exports.ValueScopeName = exports.Scope = exports.varKinds = exports.UsedValueState = void 0; + const code_1 = requireCode$1(); + class ValueError extends Error { + constructor(name) { + super(`CodeGen: "code" for ${name} not defined`); + this.value = name.value; + } + } + var UsedValueState; + (function (UsedValueState) { + UsedValueState[UsedValueState["Started"] = 0] = "Started"; + UsedValueState[UsedValueState["Completed"] = 1] = "Completed"; + })(UsedValueState = exports.UsedValueState || (exports.UsedValueState = {})); + exports.varKinds = { + const: new code_1.Name("const"), + let: new code_1.Name("let"), + var: new code_1.Name("var"), + }; + class Scope { + constructor({ prefixes, parent } = {}) { + this._names = {}; + this._prefixes = prefixes; + this._parent = parent; + } + toName(nameOrPrefix) { + return nameOrPrefix instanceof code_1.Name ? nameOrPrefix : this.name(nameOrPrefix); + } + name(prefix) { + return new code_1.Name(this._newName(prefix)); + } + _newName(prefix) { + const ng = this._names[prefix] || this._nameGroup(prefix); + return `${prefix}${ng.index++}`; + } + _nameGroup(prefix) { + var _a, _b; + if (((_b = (_a = this._parent) === null || _a === void 0 ? void 0 : _a._prefixes) === null || _b === void 0 ? void 0 : _b.has(prefix)) || (this._prefixes && !this._prefixes.has(prefix))) { + throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`); + } + return (this._names[prefix] = { prefix, index: 0 }); + } + } + exports.Scope = Scope; + class ValueScopeName extends code_1.Name { + constructor(prefix, nameStr) { + super(nameStr); + this.prefix = prefix; + } + setValue(value, { property, itemIndex }) { + this.value = value; + this.scopePath = (0, code_1._) `.${new code_1.Name(property)}[${itemIndex}]`; + } + } + exports.ValueScopeName = ValueScopeName; + const line = (0, code_1._) `\n`; + class ValueScope extends Scope { + constructor(opts) { + super(opts); + this._values = {}; + this._scope = opts.scope; + this.opts = { ...opts, _n: opts.lines ? line : code_1.nil }; + } + get() { + return this._scope; + } + name(prefix) { + return new ValueScopeName(prefix, this._newName(prefix)); + } + value(nameOrPrefix, value) { + var _a; + if (value.ref === undefined) + throw new Error("CodeGen: ref must be passed in value"); + const name = this.toName(nameOrPrefix); + const { prefix } = name; + const valueKey = (_a = value.key) !== null && _a !== void 0 ? _a : value.ref; + let vs = this._values[prefix]; + if (vs) { + const _name = vs.get(valueKey); + if (_name) + return _name; + } + else { + vs = this._values[prefix] = new Map(); + } + vs.set(valueKey, name); + const s = this._scope[prefix] || (this._scope[prefix] = []); + const itemIndex = s.length; + s[itemIndex] = value.ref; + name.setValue(value, { property: prefix, itemIndex }); + return name; + } + getValue(prefix, keyOrRef) { + const vs = this._values[prefix]; + if (!vs) + return; + return vs.get(keyOrRef); + } + scopeRefs(scopeName, values = this._values) { + return this._reduceValues(values, (name) => { + if (name.scopePath === undefined) + throw new Error(`CodeGen: name "${name}" has no value`); + return (0, code_1._) `${scopeName}${name.scopePath}`; + }); + } + scopeCode(values = this._values, usedValues, getCode) { + return this._reduceValues(values, (name) => { + if (name.value === undefined) + throw new Error(`CodeGen: name "${name}" has no value`); + return name.value.code; + }, usedValues, getCode); + } + _reduceValues(values, valueCode, usedValues = {}, getCode) { + let code = code_1.nil; + for (const prefix in values) { + const vs = values[prefix]; + if (!vs) + continue; + const nameSet = (usedValues[prefix] = usedValues[prefix] || new Map()); + vs.forEach((name) => { + if (nameSet.has(name)) + return; + nameSet.set(name, UsedValueState.Started); + let c = valueCode(name); + if (c) { + const def = this.opts.es5 ? exports.varKinds.var : exports.varKinds.const; + code = (0, code_1._) `${code}${def} ${name} = ${c};${this.opts._n}`; + } + else if ((c = getCode === null || getCode === void 0 ? void 0 : getCode(name))) { + code = (0, code_1._) `${code}${c}${this.opts._n}`; + } + else { + throw new ValueError(name); + } + nameSet.set(name, UsedValueState.Completed); + }); + } + return code; + } + } + exports.ValueScope = ValueScope; + + } (scope)); + return scope; +} + +var hasRequiredCodegen; + +function requireCodegen () { + if (hasRequiredCodegen) return codegen; + hasRequiredCodegen = 1; + (function (exports) { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.or = exports.and = exports.not = exports.CodeGen = exports.operators = exports.varKinds = exports.ValueScopeName = exports.ValueScope = exports.Scope = exports.Name = exports.regexpCode = exports.stringify = exports.getProperty = exports.nil = exports.strConcat = exports.str = exports._ = void 0; + const code_1 = requireCode$1(); + const scope_1 = requireScope(); + var code_2 = requireCode$1(); + Object.defineProperty(exports, "_", { enumerable: true, get: function () { return code_2._; } }); + Object.defineProperty(exports, "str", { enumerable: true, get: function () { return code_2.str; } }); + Object.defineProperty(exports, "strConcat", { enumerable: true, get: function () { return code_2.strConcat; } }); + Object.defineProperty(exports, "nil", { enumerable: true, get: function () { return code_2.nil; } }); + Object.defineProperty(exports, "getProperty", { enumerable: true, get: function () { return code_2.getProperty; } }); + Object.defineProperty(exports, "stringify", { enumerable: true, get: function () { return code_2.stringify; } }); + Object.defineProperty(exports, "regexpCode", { enumerable: true, get: function () { return code_2.regexpCode; } }); + Object.defineProperty(exports, "Name", { enumerable: true, get: function () { return code_2.Name; } }); + var scope_2 = requireScope(); + Object.defineProperty(exports, "Scope", { enumerable: true, get: function () { return scope_2.Scope; } }); + Object.defineProperty(exports, "ValueScope", { enumerable: true, get: function () { return scope_2.ValueScope; } }); + Object.defineProperty(exports, "ValueScopeName", { enumerable: true, get: function () { return scope_2.ValueScopeName; } }); + Object.defineProperty(exports, "varKinds", { enumerable: true, get: function () { return scope_2.varKinds; } }); + exports.operators = { + GT: new code_1._Code(">"), + GTE: new code_1._Code(">="), + LT: new code_1._Code("<"), + LTE: new code_1._Code("<="), + EQ: new code_1._Code("==="), + NEQ: new code_1._Code("!=="), + NOT: new code_1._Code("!"), + OR: new code_1._Code("||"), + AND: new code_1._Code("&&"), + ADD: new code_1._Code("+"), + }; + class Node { + optimizeNodes() { + return this; + } + optimizeNames(_names, _constants) { + return this; + } + } + class Def extends Node { + constructor(varKind, name, rhs) { + super(); + this.varKind = varKind; + this.name = name; + this.rhs = rhs; + } + render({ es5, _n }) { + const varKind = es5 ? scope_1.varKinds.var : this.varKind; + const rhs = this.rhs === undefined ? "" : ` = ${this.rhs}`; + return `${varKind} ${this.name}${rhs};` + _n; + } + optimizeNames(names, constants) { + if (!names[this.name.str]) + return; + if (this.rhs) + this.rhs = optimizeExpr(this.rhs, names, constants); + return this; + } + get names() { + return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {}; + } + } + class Assign extends Node { + constructor(lhs, rhs, sideEffects) { + super(); + this.lhs = lhs; + this.rhs = rhs; + this.sideEffects = sideEffects; + } + render({ _n }) { + return `${this.lhs} = ${this.rhs};` + _n; + } + optimizeNames(names, constants) { + if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects) + return; + this.rhs = optimizeExpr(this.rhs, names, constants); + return this; + } + get names() { + const names = this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names }; + return addExprNames(names, this.rhs); + } + } + class AssignOp extends Assign { + constructor(lhs, op, rhs, sideEffects) { + super(lhs, rhs, sideEffects); + this.op = op; + } + render({ _n }) { + return `${this.lhs} ${this.op}= ${this.rhs};` + _n; + } + } + class Label extends Node { + constructor(label) { + super(); + this.label = label; + this.names = {}; + } + render({ _n }) { + return `${this.label}:` + _n; + } + } + class Break extends Node { + constructor(label) { + super(); + this.label = label; + this.names = {}; + } + render({ _n }) { + const label = this.label ? ` ${this.label}` : ""; + return `break${label};` + _n; + } + } + class Throw extends Node { + constructor(error) { + super(); + this.error = error; + } + render({ _n }) { + return `throw ${this.error};` + _n; + } + get names() { + return this.error.names; + } + } + class AnyCode extends Node { + constructor(code) { + super(); + this.code = code; + } + render({ _n }) { + return `${this.code};` + _n; + } + optimizeNodes() { + return `${this.code}` ? this : undefined; + } + optimizeNames(names, constants) { + this.code = optimizeExpr(this.code, names, constants); + return this; + } + get names() { + return this.code instanceof code_1._CodeOrName ? this.code.names : {}; + } + } + class ParentNode extends Node { + constructor(nodes = []) { + super(); + this.nodes = nodes; + } + render(opts) { + return this.nodes.reduce((code, n) => code + n.render(opts), ""); + } + optimizeNodes() { + const { nodes } = this; + let i = nodes.length; + while (i--) { + const n = nodes[i].optimizeNodes(); + if (Array.isArray(n)) + nodes.splice(i, 1, ...n); + else if (n) + nodes[i] = n; + else + nodes.splice(i, 1); + } + return nodes.length > 0 ? this : undefined; + } + optimizeNames(names, constants) { + const { nodes } = this; + let i = nodes.length; + while (i--) { + // iterating backwards improves 1-pass optimization + const n = nodes[i]; + if (n.optimizeNames(names, constants)) + continue; + subtractNames(names, n.names); + nodes.splice(i, 1); + } + return nodes.length > 0 ? this : undefined; + } + get names() { + return this.nodes.reduce((names, n) => addNames(names, n.names), {}); + } + } + class BlockNode extends ParentNode { + render(opts) { + return "{" + opts._n + super.render(opts) + "}" + opts._n; + } + } + class Root extends ParentNode { + } + class Else extends BlockNode { + } + Else.kind = "else"; + class If extends BlockNode { + constructor(condition, nodes) { + super(nodes); + this.condition = condition; + } + render(opts) { + let code = `if(${this.condition})` + super.render(opts); + if (this.else) + code += "else " + this.else.render(opts); + return code; + } + optimizeNodes() { + super.optimizeNodes(); + const cond = this.condition; + if (cond === true) + return this.nodes; // else is ignored here + let e = this.else; + if (e) { + const ns = e.optimizeNodes(); + e = this.else = Array.isArray(ns) ? new Else(ns) : ns; + } + if (e) { + if (cond === false) + return e instanceof If ? e : e.nodes; + if (this.nodes.length) + return this; + return new If(not(cond), e instanceof If ? [e] : e.nodes); + } + if (cond === false || !this.nodes.length) + return undefined; + return this; + } + optimizeNames(names, constants) { + var _a; + this.else = (_a = this.else) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants); + if (!(super.optimizeNames(names, constants) || this.else)) + return; + this.condition = optimizeExpr(this.condition, names, constants); + return this; + } + get names() { + const names = super.names; + addExprNames(names, this.condition); + if (this.else) + addNames(names, this.else.names); + return names; + } + } + If.kind = "if"; + class For extends BlockNode { + } + For.kind = "for"; + class ForLoop extends For { + constructor(iteration) { + super(); + this.iteration = iteration; + } + render(opts) { + return `for(${this.iteration})` + super.render(opts); + } + optimizeNames(names, constants) { + if (!super.optimizeNames(names, constants)) + return; + this.iteration = optimizeExpr(this.iteration, names, constants); + return this; + } + get names() { + return addNames(super.names, this.iteration.names); + } + } + class ForRange extends For { + constructor(varKind, name, from, to) { + super(); + this.varKind = varKind; + this.name = name; + this.from = from; + this.to = to; + } + render(opts) { + const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind; + const { name, from, to } = this; + return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts); + } + get names() { + const names = addExprNames(super.names, this.from); + return addExprNames(names, this.to); + } + } + class ForIter extends For { + constructor(loop, varKind, name, iterable) { + super(); + this.loop = loop; + this.varKind = varKind; + this.name = name; + this.iterable = iterable; + } + render(opts) { + return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts); + } + optimizeNames(names, constants) { + if (!super.optimizeNames(names, constants)) + return; + this.iterable = optimizeExpr(this.iterable, names, constants); + return this; + } + get names() { + return addNames(super.names, this.iterable.names); + } + } + class Func extends BlockNode { + constructor(name, args, async) { + super(); + this.name = name; + this.args = args; + this.async = async; + } + render(opts) { + const _async = this.async ? "async " : ""; + return `${_async}function ${this.name}(${this.args})` + super.render(opts); + } + } + Func.kind = "func"; + class Return extends ParentNode { + render(opts) { + return "return " + super.render(opts); + } + } + Return.kind = "return"; + class Try extends BlockNode { + render(opts) { + let code = "try" + super.render(opts); + if (this.catch) + code += this.catch.render(opts); + if (this.finally) + code += this.finally.render(opts); + return code; + } + optimizeNodes() { + var _a, _b; + super.optimizeNodes(); + (_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNodes(); + (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNodes(); + return this; + } + optimizeNames(names, constants) { + var _a, _b; + super.optimizeNames(names, constants); + (_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants); + (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNames(names, constants); + return this; + } + get names() { + const names = super.names; + if (this.catch) + addNames(names, this.catch.names); + if (this.finally) + addNames(names, this.finally.names); + return names; + } + } + class Catch extends BlockNode { + constructor(error) { + super(); + this.error = error; + } + render(opts) { + return `catch(${this.error})` + super.render(opts); + } + } + Catch.kind = "catch"; + class Finally extends BlockNode { + render(opts) { + return "finally" + super.render(opts); + } + } + Finally.kind = "finally"; + class CodeGen { + constructor(extScope, opts = {}) { + this._values = {}; + this._blockStarts = []; + this._constants = {}; + this.opts = { ...opts, _n: opts.lines ? "\n" : "" }; + this._extScope = extScope; + this._scope = new scope_1.Scope({ parent: extScope }); + this._nodes = [new Root()]; + } + toString() { + return this._root.render(this.opts); + } + // returns unique name in the internal scope + name(prefix) { + return this._scope.name(prefix); + } + // reserves unique name in the external scope + scopeName(prefix) { + return this._extScope.name(prefix); + } + // reserves unique name in the external scope and assigns value to it + scopeValue(prefixOrName, value) { + const name = this._extScope.value(prefixOrName, value); + const vs = this._values[name.prefix] || (this._values[name.prefix] = new Set()); + vs.add(name); + return name; + } + getScopeValue(prefix, keyOrRef) { + return this._extScope.getValue(prefix, keyOrRef); + } + // return code that assigns values in the external scope to the names that are used internally + // (same names that were returned by gen.scopeName or gen.scopeValue) + scopeRefs(scopeName) { + return this._extScope.scopeRefs(scopeName, this._values); + } + scopeCode() { + return this._extScope.scopeCode(this._values); + } + _def(varKind, nameOrPrefix, rhs, constant) { + const name = this._scope.toName(nameOrPrefix); + if (rhs !== undefined && constant) + this._constants[name.str] = rhs; + this._leafNode(new Def(varKind, name, rhs)); + return name; + } + // `const` declaration (`var` in es5 mode) + const(nameOrPrefix, rhs, _constant) { + return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant); + } + // `let` declaration with optional assignment (`var` in es5 mode) + let(nameOrPrefix, rhs, _constant) { + return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant); + } + // `var` declaration with optional assignment + var(nameOrPrefix, rhs, _constant) { + return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant); + } + // assignment code + assign(lhs, rhs, sideEffects) { + return this._leafNode(new Assign(lhs, rhs, sideEffects)); + } + // `+=` code + add(lhs, rhs) { + return this._leafNode(new AssignOp(lhs, exports.operators.ADD, rhs)); + } + // appends passed SafeExpr to code or executes Block + code(c) { + if (typeof c == "function") + c(); + else if (c !== code_1.nil) + this._leafNode(new AnyCode(c)); + return this; + } + // returns code for object literal for the passed argument list of key-value pairs + object(...keyValues) { + const code = ["{"]; + for (const [key, value] of keyValues) { + if (code.length > 1) + code.push(","); + code.push(key); + if (key !== value || this.opts.es5) { + code.push(":"); + (0, code_1.addCodeArg)(code, value); + } + } + code.push("}"); + return new code_1._Code(code); + } + // `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed) + if(condition, thenBody, elseBody) { + this._blockNode(new If(condition)); + if (thenBody && elseBody) { + this.code(thenBody).else().code(elseBody).endIf(); + } + else if (thenBody) { + this.code(thenBody).endIf(); + } + else if (elseBody) { + throw new Error('CodeGen: "else" body without "then" body'); + } + return this; + } + // `else if` clause - invalid without `if` or after `else` clauses + elseIf(condition) { + return this._elseNode(new If(condition)); + } + // `else` clause - only valid after `if` or `else if` clauses + else() { + return this._elseNode(new Else()); + } + // end `if` statement (needed if gen.if was used only with condition) + endIf() { + return this._endBlockNode(If, Else); + } + _for(node, forBody) { + this._blockNode(node); + if (forBody) + this.code(forBody).endFor(); + return this; + } + // a generic `for` clause (or statement if `forBody` is passed) + for(iteration, forBody) { + return this._for(new ForLoop(iteration), forBody); + } + // `for` statement for a range of values + forRange(nameOrPrefix, from, to, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) { + const name = this._scope.toName(nameOrPrefix); + return this._for(new ForRange(varKind, name, from, to), () => forBody(name)); + } + // `for-of` statement (in es5 mode replace with a normal for loop) + forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) { + const name = this._scope.toName(nameOrPrefix); + if (this.opts.es5) { + const arr = iterable instanceof code_1.Name ? iterable : this.var("_arr", iterable); + return this.forRange("_i", 0, (0, code_1._) `${arr}.length`, (i) => { + this.var(name, (0, code_1._) `${arr}[${i}]`); + forBody(name); + }); + } + return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name)); + } + // `for-in` statement. + // With option `ownProperties` replaced with a `for-of` loop for object keys + forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) { + if (this.opts.ownProperties) { + return this.forOf(nameOrPrefix, (0, code_1._) `Object.keys(${obj})`, forBody); + } + const name = this._scope.toName(nameOrPrefix); + return this._for(new ForIter("in", varKind, name, obj), () => forBody(name)); + } + // end `for` loop + endFor() { + return this._endBlockNode(For); + } + // `label` statement + label(label) { + return this._leafNode(new Label(label)); + } + // `break` statement + break(label) { + return this._leafNode(new Break(label)); + } + // `return` statement + return(value) { + const node = new Return(); + this._blockNode(node); + this.code(value); + if (node.nodes.length !== 1) + throw new Error('CodeGen: "return" should have one node'); + return this._endBlockNode(Return); + } + // `try` statement + try(tryBody, catchCode, finallyCode) { + if (!catchCode && !finallyCode) + throw new Error('CodeGen: "try" without "catch" and "finally"'); + const node = new Try(); + this._blockNode(node); + this.code(tryBody); + if (catchCode) { + const error = this.name("e"); + this._currNode = node.catch = new Catch(error); + catchCode(error); + } + if (finallyCode) { + this._currNode = node.finally = new Finally(); + this.code(finallyCode); + } + return this._endBlockNode(Catch, Finally); + } + // `throw` statement + throw(error) { + return this._leafNode(new Throw(error)); + } + // start self-balancing block + block(body, nodeCount) { + this._blockStarts.push(this._nodes.length); + if (body) + this.code(body).endBlock(nodeCount); + return this; + } + // end the current self-balancing block + endBlock(nodeCount) { + const len = this._blockStarts.pop(); + if (len === undefined) + throw new Error("CodeGen: not in self-balancing block"); + const toClose = this._nodes.length - len; + if (toClose < 0 || (nodeCount !== undefined && toClose !== nodeCount)) { + throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`); + } + this._nodes.length = len; + return this; + } + // `function` heading (or definition if funcBody is passed) + func(name, args = code_1.nil, async, funcBody) { + this._blockNode(new Func(name, args, async)); + if (funcBody) + this.code(funcBody).endFunc(); + return this; + } + // end function definition + endFunc() { + return this._endBlockNode(Func); + } + optimize(n = 1) { + while (n-- > 0) { + this._root.optimizeNodes(); + this._root.optimizeNames(this._root.names, this._constants); + } + } + _leafNode(node) { + this._currNode.nodes.push(node); + return this; + } + _blockNode(node) { + this._currNode.nodes.push(node); + this._nodes.push(node); + } + _endBlockNode(N1, N2) { + const n = this._currNode; + if (n instanceof N1 || (N2 && n instanceof N2)) { + this._nodes.pop(); + return this; + } + throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`); + } + _elseNode(node) { + const n = this._currNode; + if (!(n instanceof If)) { + throw new Error('CodeGen: "else" without "if"'); + } + this._currNode = n.else = node; + return this; + } + get _root() { + return this._nodes[0]; + } + get _currNode() { + const ns = this._nodes; + return ns[ns.length - 1]; + } + set _currNode(node) { + const ns = this._nodes; + ns[ns.length - 1] = node; + } + } + exports.CodeGen = CodeGen; + function addNames(names, from) { + for (const n in from) + names[n] = (names[n] || 0) + (from[n] || 0); + return names; + } + function addExprNames(names, from) { + return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names; + } + function optimizeExpr(expr, names, constants) { + if (expr instanceof code_1.Name) + return replaceName(expr); + if (!canOptimize(expr)) + return expr; + return new code_1._Code(expr._items.reduce((items, c) => { + if (c instanceof code_1.Name) + c = replaceName(c); + if (c instanceof code_1._Code) + items.push(...c._items); + else + items.push(c); + return items; + }, [])); + function replaceName(n) { + const c = constants[n.str]; + if (c === undefined || names[n.str] !== 1) + return n; + delete names[n.str]; + return c; + } + function canOptimize(e) { + return (e instanceof code_1._Code && + e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants[c.str] !== undefined)); + } + } + function subtractNames(names, from) { + for (const n in from) + names[n] = (names[n] || 0) - (from[n] || 0); + } + function not(x) { + return typeof x == "boolean" || typeof x == "number" || x === null ? !x : (0, code_1._) `!${par(x)}`; + } + exports.not = not; + const andCode = mappend(exports.operators.AND); + // boolean AND (&&) expression with the passed arguments + function and(...args) { + return args.reduce(andCode); + } + exports.and = and; + const orCode = mappend(exports.operators.OR); + // boolean OR (||) expression with the passed arguments + function or(...args) { + return args.reduce(orCode); + } + exports.or = or; + function mappend(op) { + return (x, y) => (x === code_1.nil ? y : y === code_1.nil ? x : (0, code_1._) `${par(x)} ${op} ${par(y)}`); + } + function par(x) { + return x instanceof code_1.Name ? x : (0, code_1._) `(${x})`; + } + + } (codegen)); + return codegen; +} + +var util$6 = {}; + +(function (exports) { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.checkStrictMode = exports.getErrorPath = exports.Type = exports.useFunc = exports.setEvaluated = exports.evaluatedPropsToName = exports.mergeEvaluated = exports.eachItem = exports.unescapeJsonPointer = exports.escapeJsonPointer = exports.escapeFragment = exports.unescapeFragment = exports.schemaRefOrVal = exports.schemaHasRulesButRef = exports.schemaHasRules = exports.checkUnknownRules = exports.alwaysValidSchema = exports.toHash = void 0; + const codegen_1 = requireCodegen(); + const code_1 = requireCode$1(); + // TODO refactor to use Set + function toHash(arr) { + const hash = {}; + for (const item of arr) + hash[item] = true; + return hash; + } + exports.toHash = toHash; + function alwaysValidSchema(it, schema) { + if (typeof schema == "boolean") + return schema; + if (Object.keys(schema).length === 0) + return true; + checkUnknownRules(it, schema); + return !schemaHasRules(schema, it.self.RULES.all); + } + exports.alwaysValidSchema = alwaysValidSchema; + function checkUnknownRules(it, schema = it.schema) { + const { opts, self } = it; + if (!opts.strictSchema) + return; + if (typeof schema === "boolean") + return; + const rules = self.RULES.keywords; + for (const key in schema) { + if (!rules[key]) + checkStrictMode(it, `unknown keyword: "${key}"`); + } + } + exports.checkUnknownRules = checkUnknownRules; + function schemaHasRules(schema, rules) { + if (typeof schema == "boolean") + return !schema; + for (const key in schema) + if (rules[key]) + return true; + return false; + } + exports.schemaHasRules = schemaHasRules; + function schemaHasRulesButRef(schema, RULES) { + if (typeof schema == "boolean") + return !schema; + for (const key in schema) + if (key !== "$ref" && RULES.all[key]) + return true; + return false; + } + exports.schemaHasRulesButRef = schemaHasRulesButRef; + function schemaRefOrVal({ topSchemaRef, schemaPath }, schema, keyword, $data) { + if (!$data) { + if (typeof schema == "number" || typeof schema == "boolean") + return schema; + if (typeof schema == "string") + return (0, codegen_1._) `${schema}`; + } + return (0, codegen_1._) `${topSchemaRef}${schemaPath}${(0, codegen_1.getProperty)(keyword)}`; + } + exports.schemaRefOrVal = schemaRefOrVal; + function unescapeFragment(str) { + return unescapeJsonPointer(decodeURIComponent(str)); + } + exports.unescapeFragment = unescapeFragment; + function escapeFragment(str) { + return encodeURIComponent(escapeJsonPointer(str)); + } + exports.escapeFragment = escapeFragment; + function escapeJsonPointer(str) { + if (typeof str == "number") + return `${str}`; + return str.replace(/~/g, "~0").replace(/\//g, "~1"); + } + exports.escapeJsonPointer = escapeJsonPointer; + function unescapeJsonPointer(str) { + return str.replace(/~1/g, "/").replace(/~0/g, "~"); + } + exports.unescapeJsonPointer = unescapeJsonPointer; + function eachItem(xs, f) { + if (Array.isArray(xs)) { + for (const x of xs) + f(x); + } + else { + f(xs); + } + } + exports.eachItem = eachItem; + function makeMergeEvaluated({ mergeNames, mergeToName, mergeValues, resultToName, }) { + return (gen, from, to, toName) => { + const res = to === undefined + ? from + : to instanceof codegen_1.Name + ? (from instanceof codegen_1.Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to) + : from instanceof codegen_1.Name + ? (mergeToName(gen, to, from), from) + : mergeValues(from, to); + return toName === codegen_1.Name && !(res instanceof codegen_1.Name) ? resultToName(gen, res) : res; + }; + } + exports.mergeEvaluated = { + props: makeMergeEvaluated({ + mergeNames: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true && ${from} !== undefined`, () => { + gen.if((0, codegen_1._) `${from} === true`, () => gen.assign(to, true), () => gen.assign(to, (0, codegen_1._) `${to} || {}`).code((0, codegen_1._) `Object.assign(${to}, ${from})`)); + }), + mergeToName: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true`, () => { + if (from === true) { + gen.assign(to, true); + } + else { + gen.assign(to, (0, codegen_1._) `${to} || {}`); + setEvaluated(gen, to, from); + } + }), + mergeValues: (from, to) => (from === true ? true : { ...from, ...to }), + resultToName: evaluatedPropsToName, + }), + items: makeMergeEvaluated({ + mergeNames: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true && ${from} !== undefined`, () => gen.assign(to, (0, codegen_1._) `${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)), + mergeToName: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true`, () => gen.assign(to, from === true ? true : (0, codegen_1._) `${to} > ${from} ? ${to} : ${from}`)), + mergeValues: (from, to) => (from === true ? true : Math.max(from, to)), + resultToName: (gen, items) => gen.var("items", items), + }), + }; + function evaluatedPropsToName(gen, ps) { + if (ps === true) + return gen.var("props", true); + const props = gen.var("props", (0, codegen_1._) `{}`); + if (ps !== undefined) + setEvaluated(gen, props, ps); + return props; + } + exports.evaluatedPropsToName = evaluatedPropsToName; + function setEvaluated(gen, props, ps) { + Object.keys(ps).forEach((p) => gen.assign((0, codegen_1._) `${props}${(0, codegen_1.getProperty)(p)}`, true)); + } + exports.setEvaluated = setEvaluated; + const snippets = {}; + function useFunc(gen, f) { + return gen.scopeValue("func", { + ref: f, + code: snippets[f.code] || (snippets[f.code] = new code_1._Code(f.code)), + }); + } + exports.useFunc = useFunc; + var Type; + (function (Type) { + Type[Type["Num"] = 0] = "Num"; + Type[Type["Str"] = 1] = "Str"; + })(Type = exports.Type || (exports.Type = {})); + function getErrorPath(dataProp, dataPropType, jsPropertySyntax) { + // let path + if (dataProp instanceof codegen_1.Name) { + const isNumber = dataPropType === Type.Num; + return jsPropertySyntax + ? isNumber + ? (0, codegen_1._) `"[" + ${dataProp} + "]"` + : (0, codegen_1._) `"['" + ${dataProp} + "']"` + : isNumber + ? (0, codegen_1._) `"/" + ${dataProp}` + : (0, codegen_1._) `"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")`; // TODO maybe use global escapePointer + } + return jsPropertySyntax ? (0, codegen_1.getProperty)(dataProp).toString() : "/" + escapeJsonPointer(dataProp); + } + exports.getErrorPath = getErrorPath; + function checkStrictMode(it, msg, mode = it.opts.strictSchema) { + if (!mode) + return; + msg = `strict mode: ${msg}`; + if (mode === true) + throw new Error(msg); + it.self.logger.warn(msg); + } + exports.checkStrictMode = checkStrictMode; + +} (util$6)); + +var names = {}; + +var hasRequiredNames; + +function requireNames () { + if (hasRequiredNames) return names; + hasRequiredNames = 1; + Object.defineProperty(names, "__esModule", { value: true }); + const codegen_1 = requireCodegen(); + const names$1 = { + // validation function arguments + data: new codegen_1.Name("data"), + // args passed from referencing schema + valCxt: new codegen_1.Name("valCxt"), + instancePath: new codegen_1.Name("instancePath"), + parentData: new codegen_1.Name("parentData"), + parentDataProperty: new codegen_1.Name("parentDataProperty"), + rootData: new codegen_1.Name("rootData"), + dynamicAnchors: new codegen_1.Name("dynamicAnchors"), + // function scoped variables + vErrors: new codegen_1.Name("vErrors"), + errors: new codegen_1.Name("errors"), + this: new codegen_1.Name("this"), + // "globals" + self: new codegen_1.Name("self"), + scope: new codegen_1.Name("scope"), + // JTD serialize/parse name for JSON string and position + json: new codegen_1.Name("json"), + jsonPos: new codegen_1.Name("jsonPos"), + jsonLen: new codegen_1.Name("jsonLen"), + jsonPart: new codegen_1.Name("jsonPart"), + }; + names.default = names$1; + + return names; +} + +var hasRequiredErrors$1; + +function requireErrors$1 () { + if (hasRequiredErrors$1) return errors$1; + hasRequiredErrors$1 = 1; + (function (exports) { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.extendErrors = exports.resetErrorsCount = exports.reportExtraError = exports.reportError = exports.keyword$DataError = exports.keywordError = void 0; + const codegen_1 = requireCodegen(); + const util_1 = util$6; + const names_1 = requireNames(); + exports.keywordError = { + message: ({ keyword }) => (0, codegen_1.str) `must pass "${keyword}" keyword validation`, + }; + exports.keyword$DataError = { + message: ({ keyword, schemaType }) => schemaType + ? (0, codegen_1.str) `"${keyword}" keyword must be ${schemaType} ($data)` + : (0, codegen_1.str) `"${keyword}" keyword is invalid ($data)`, + }; + function reportError(cxt, error = exports.keywordError, errorPaths, overrideAllErrors) { + const { it } = cxt; + const { gen, compositeRule, allErrors } = it; + const errObj = errorObjectCode(cxt, error, errorPaths); + if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : (compositeRule || allErrors)) { + addError(gen, errObj); + } + else { + returnErrors(it, (0, codegen_1._) `[${errObj}]`); + } + } + exports.reportError = reportError; + function reportExtraError(cxt, error = exports.keywordError, errorPaths) { + const { it } = cxt; + const { gen, compositeRule, allErrors } = it; + const errObj = errorObjectCode(cxt, error, errorPaths); + addError(gen, errObj); + if (!(compositeRule || allErrors)) { + returnErrors(it, names_1.default.vErrors); + } + } + exports.reportExtraError = reportExtraError; + function resetErrorsCount(gen, errsCount) { + gen.assign(names_1.default.errors, errsCount); + gen.if((0, codegen_1._) `${names_1.default.vErrors} !== null`, () => gen.if(errsCount, () => gen.assign((0, codegen_1._) `${names_1.default.vErrors}.length`, errsCount), () => gen.assign(names_1.default.vErrors, null))); + } + exports.resetErrorsCount = resetErrorsCount; + function extendErrors({ gen, keyword, schemaValue, data, errsCount, it, }) { + /* istanbul ignore if */ + if (errsCount === undefined) + throw new Error("ajv implementation error"); + const err = gen.name("err"); + gen.forRange("i", errsCount, names_1.default.errors, (i) => { + gen.const(err, (0, codegen_1._) `${names_1.default.vErrors}[${i}]`); + gen.if((0, codegen_1._) `${err}.instancePath === undefined`, () => gen.assign((0, codegen_1._) `${err}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it.errorPath))); + gen.assign((0, codegen_1._) `${err}.schemaPath`, (0, codegen_1.str) `${it.errSchemaPath}/${keyword}`); + if (it.opts.verbose) { + gen.assign((0, codegen_1._) `${err}.schema`, schemaValue); + gen.assign((0, codegen_1._) `${err}.data`, data); + } + }); + } + exports.extendErrors = extendErrors; + function addError(gen, errObj) { + const err = gen.const("err", errObj); + gen.if((0, codegen_1._) `${names_1.default.vErrors} === null`, () => gen.assign(names_1.default.vErrors, (0, codegen_1._) `[${err}]`), (0, codegen_1._) `${names_1.default.vErrors}.push(${err})`); + gen.code((0, codegen_1._) `${names_1.default.errors}++`); + } + function returnErrors(it, errs) { + const { gen, validateName, schemaEnv } = it; + if (schemaEnv.$async) { + gen.throw((0, codegen_1._) `new ${it.ValidationError}(${errs})`); + } + else { + gen.assign((0, codegen_1._) `${validateName}.errors`, errs); + gen.return(false); + } + } + const E = { + keyword: new codegen_1.Name("keyword"), + schemaPath: new codegen_1.Name("schemaPath"), + params: new codegen_1.Name("params"), + propertyName: new codegen_1.Name("propertyName"), + message: new codegen_1.Name("message"), + schema: new codegen_1.Name("schema"), + parentSchema: new codegen_1.Name("parentSchema"), + }; + function errorObjectCode(cxt, error, errorPaths) { + const { createErrors } = cxt.it; + if (createErrors === false) + return (0, codegen_1._) `{}`; + return errorObject(cxt, error, errorPaths); + } + function errorObject(cxt, error, errorPaths = {}) { + const { gen, it } = cxt; + const keyValues = [ + errorInstancePath(it, errorPaths), + errorSchemaPath(cxt, errorPaths), + ]; + extraErrorProps(cxt, error, keyValues); + return gen.object(...keyValues); + } + function errorInstancePath({ errorPath }, { instancePath }) { + const instPath = instancePath + ? (0, codegen_1.str) `${errorPath}${(0, util_1.getErrorPath)(instancePath, util_1.Type.Str)}` + : errorPath; + return [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, instPath)]; + } + function errorSchemaPath({ keyword, it: { errSchemaPath } }, { schemaPath, parentSchema }) { + let schPath = parentSchema ? errSchemaPath : (0, codegen_1.str) `${errSchemaPath}/${keyword}`; + if (schemaPath) { + schPath = (0, codegen_1.str) `${schPath}${(0, util_1.getErrorPath)(schemaPath, util_1.Type.Str)}`; + } + return [E.schemaPath, schPath]; + } + function extraErrorProps(cxt, { params, message }, keyValues) { + const { keyword, data, schemaValue, it } = cxt; + const { opts, propertyName, topSchemaRef, schemaPath } = it; + keyValues.push([E.keyword, keyword], [E.params, typeof params == "function" ? params(cxt) : params || (0, codegen_1._) `{}`]); + if (opts.messages) { + keyValues.push([E.message, typeof message == "function" ? message(cxt) : message]); + } + if (opts.verbose) { + keyValues.push([E.schema, schemaValue], [E.parentSchema, (0, codegen_1._) `${topSchemaRef}${schemaPath}`], [names_1.default.data, data]); + } + if (propertyName) + keyValues.push([E.propertyName, propertyName]); + } + + } (errors$1)); + return errors$1; +} + +var hasRequiredBoolSchema; + +function requireBoolSchema () { + if (hasRequiredBoolSchema) return boolSchema; + hasRequiredBoolSchema = 1; + Object.defineProperty(boolSchema, "__esModule", { value: true }); + boolSchema.boolOrEmptySchema = boolSchema.topBoolOrEmptySchema = void 0; + const errors_1 = requireErrors$1(); + const codegen_1 = requireCodegen(); + const names_1 = requireNames(); + const boolError = { + message: "boolean schema is false", + }; + function topBoolOrEmptySchema(it) { + const { gen, schema, validateName } = it; + if (schema === false) { + falseSchemaError(it, false); + } + else if (typeof schema == "object" && schema.$async === true) { + gen.return(names_1.default.data); + } + else { + gen.assign((0, codegen_1._) `${validateName}.errors`, null); + gen.return(true); + } + } + boolSchema.topBoolOrEmptySchema = topBoolOrEmptySchema; + function boolOrEmptySchema(it, valid) { + const { gen, schema } = it; + if (schema === false) { + gen.var(valid, false); // TODO var + falseSchemaError(it); + } + else { + gen.var(valid, true); // TODO var + } + } + boolSchema.boolOrEmptySchema = boolOrEmptySchema; + function falseSchemaError(it, overrideAllErrors) { + const { gen, data } = it; + // TODO maybe some other interface should be used for non-keyword validation errors... + const cxt = { + gen, + keyword: "false schema", + data, + schema: false, + schemaCode: false, + schemaValue: false, + params: {}, + it, + }; + (0, errors_1.reportError)(cxt, boolError, undefined, overrideAllErrors); + } + + return boolSchema; +} + +var dataType = {}; + +var rules = {}; + +Object.defineProperty(rules, "__esModule", { value: true }); +rules.getRules = rules.isJSONType = void 0; +const _jsonTypes = ["string", "number", "integer", "boolean", "null", "object", "array"]; +const jsonTypes = new Set(_jsonTypes); +function isJSONType(x) { + return typeof x == "string" && jsonTypes.has(x); +} +rules.isJSONType = isJSONType; +function getRules() { + const groups = { + number: { type: "number", rules: [] }, + string: { type: "string", rules: [] }, + array: { type: "array", rules: [] }, + object: { type: "object", rules: [] }, + }; + return { + types: { ...groups, integer: true, boolean: true, null: true }, + rules: [{ rules: [] }, groups.number, groups.string, groups.array, groups.object], + post: { rules: [] }, + all: {}, + keywords: {}, + }; +} +rules.getRules = getRules; + +var applicability = {}; + +var hasRequiredApplicability; + +function requireApplicability () { + if (hasRequiredApplicability) return applicability; + hasRequiredApplicability = 1; + Object.defineProperty(applicability, "__esModule", { value: true }); + applicability.shouldUseRule = applicability.shouldUseGroup = applicability.schemaHasRulesForType = void 0; + function schemaHasRulesForType({ schema, self }, type) { + const group = self.RULES.types[type]; + return group && group !== true && shouldUseGroup(schema, group); + } + applicability.schemaHasRulesForType = schemaHasRulesForType; + function shouldUseGroup(schema, group) { + return group.rules.some((rule) => shouldUseRule(schema, rule)); + } + applicability.shouldUseGroup = shouldUseGroup; + function shouldUseRule(schema, rule) { + var _a; + return (schema[rule.keyword] !== undefined || + ((_a = rule.definition.implements) === null || _a === void 0 ? void 0 : _a.some((kwd) => schema[kwd] !== undefined))); + } + applicability.shouldUseRule = shouldUseRule; + + return applicability; +} + +(function (exports) { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.reportTypeError = exports.checkDataTypes = exports.checkDataType = exports.coerceAndCheckDataType = exports.getJSONTypes = exports.getSchemaTypes = exports.DataType = void 0; + const rules_1 = rules; + const applicability_1 = requireApplicability(); + const errors_1 = requireErrors$1(); + const codegen_1 = requireCodegen(); + const util_1 = util$6; + var DataType; + (function (DataType) { + DataType[DataType["Correct"] = 0] = "Correct"; + DataType[DataType["Wrong"] = 1] = "Wrong"; + })(DataType = exports.DataType || (exports.DataType = {})); + function getSchemaTypes(schema) { + const types = getJSONTypes(schema.type); + const hasNull = types.includes("null"); + if (hasNull) { + if (schema.nullable === false) + throw new Error("type: null contradicts nullable: false"); + } + else { + if (!types.length && schema.nullable !== undefined) { + throw new Error('"nullable" cannot be used without "type"'); + } + if (schema.nullable === true) + types.push("null"); + } + return types; + } + exports.getSchemaTypes = getSchemaTypes; + function getJSONTypes(ts) { + const types = Array.isArray(ts) ? ts : ts ? [ts] : []; + if (types.every(rules_1.isJSONType)) + return types; + throw new Error("type must be JSONType or JSONType[]: " + types.join(",")); + } + exports.getJSONTypes = getJSONTypes; + function coerceAndCheckDataType(it, types) { + const { gen, data, opts } = it; + const coerceTo = coerceToTypes(types, opts.coerceTypes); + const checkTypes = types.length > 0 && + !(coerceTo.length === 0 && types.length === 1 && (0, applicability_1.schemaHasRulesForType)(it, types[0])); + if (checkTypes) { + const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong); + gen.if(wrongType, () => { + if (coerceTo.length) + coerceData(it, types, coerceTo); + else + reportTypeError(it); + }); + } + return checkTypes; + } + exports.coerceAndCheckDataType = coerceAndCheckDataType; + const COERCIBLE = new Set(["string", "number", "integer", "boolean", "null"]); + function coerceToTypes(types, coerceTypes) { + return coerceTypes + ? types.filter((t) => COERCIBLE.has(t) || (coerceTypes === "array" && t === "array")) + : []; + } + function coerceData(it, types, coerceTo) { + const { gen, data, opts } = it; + const dataType = gen.let("dataType", (0, codegen_1._) `typeof ${data}`); + const coerced = gen.let("coerced", (0, codegen_1._) `undefined`); + if (opts.coerceTypes === "array") { + gen.if((0, codegen_1._) `${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => gen + .assign(data, (0, codegen_1._) `${data}[0]`) + .assign(dataType, (0, codegen_1._) `typeof ${data}`) + .if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data))); + } + gen.if((0, codegen_1._) `${coerced} !== undefined`); + for (const t of coerceTo) { + if (COERCIBLE.has(t) || (t === "array" && opts.coerceTypes === "array")) { + coerceSpecificType(t); + } + } + gen.else(); + reportTypeError(it); + gen.endIf(); + gen.if((0, codegen_1._) `${coerced} !== undefined`, () => { + gen.assign(data, coerced); + assignParentData(it, coerced); + }); + function coerceSpecificType(t) { + switch (t) { + case "string": + gen + .elseIf((0, codegen_1._) `${dataType} == "number" || ${dataType} == "boolean"`) + .assign(coerced, (0, codegen_1._) `"" + ${data}`) + .elseIf((0, codegen_1._) `${data} === null`) + .assign(coerced, (0, codegen_1._) `""`); + return; + case "number": + gen + .elseIf((0, codegen_1._) `${dataType} == "boolean" || ${data} === null + || (${dataType} == "string" && ${data} && ${data} == +${data})`) + .assign(coerced, (0, codegen_1._) `+${data}`); + return; + case "integer": + gen + .elseIf((0, codegen_1._) `${dataType} === "boolean" || ${data} === null + || (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))`) + .assign(coerced, (0, codegen_1._) `+${data}`); + return; + case "boolean": + gen + .elseIf((0, codegen_1._) `${data} === "false" || ${data} === 0 || ${data} === null`) + .assign(coerced, false) + .elseIf((0, codegen_1._) `${data} === "true" || ${data} === 1`) + .assign(coerced, true); + return; + case "null": + gen.elseIf((0, codegen_1._) `${data} === "" || ${data} === 0 || ${data} === false`); + gen.assign(coerced, null); + return; + case "array": + gen + .elseIf((0, codegen_1._) `${dataType} === "string" || ${dataType} === "number" + || ${dataType} === "boolean" || ${data} === null`) + .assign(coerced, (0, codegen_1._) `[${data}]`); + } + } + } + function assignParentData({ gen, parentData, parentDataProperty }, expr) { + // TODO use gen.property + gen.if((0, codegen_1._) `${parentData} !== undefined`, () => gen.assign((0, codegen_1._) `${parentData}[${parentDataProperty}]`, expr)); + } + function checkDataType(dataType, data, strictNums, correct = DataType.Correct) { + const EQ = correct === DataType.Correct ? codegen_1.operators.EQ : codegen_1.operators.NEQ; + let cond; + switch (dataType) { + case "null": + return (0, codegen_1._) `${data} ${EQ} null`; + case "array": + cond = (0, codegen_1._) `Array.isArray(${data})`; + break; + case "object": + cond = (0, codegen_1._) `${data} && typeof ${data} == "object" && !Array.isArray(${data})`; + break; + case "integer": + cond = numCond((0, codegen_1._) `!(${data} % 1) && !isNaN(${data})`); + break; + case "number": + cond = numCond(); + break; + default: + return (0, codegen_1._) `typeof ${data} ${EQ} ${dataType}`; + } + return correct === DataType.Correct ? cond : (0, codegen_1.not)(cond); + function numCond(_cond = codegen_1.nil) { + return (0, codegen_1.and)((0, codegen_1._) `typeof ${data} == "number"`, _cond, strictNums ? (0, codegen_1._) `isFinite(${data})` : codegen_1.nil); + } + } + exports.checkDataType = checkDataType; + function checkDataTypes(dataTypes, data, strictNums, correct) { + if (dataTypes.length === 1) { + return checkDataType(dataTypes[0], data, strictNums, correct); + } + let cond; + const types = (0, util_1.toHash)(dataTypes); + if (types.array && types.object) { + const notObj = (0, codegen_1._) `typeof ${data} != "object"`; + cond = types.null ? notObj : (0, codegen_1._) `!${data} || ${notObj}`; + delete types.null; + delete types.array; + delete types.object; + } + else { + cond = codegen_1.nil; + } + if (types.number) + delete types.integer; + for (const t in types) + cond = (0, codegen_1.and)(cond, checkDataType(t, data, strictNums, correct)); + return cond; + } + exports.checkDataTypes = checkDataTypes; + const typeError = { + message: ({ schema }) => `must be ${schema}`, + params: ({ schema, schemaValue }) => typeof schema == "string" ? (0, codegen_1._) `{type: ${schema}}` : (0, codegen_1._) `{type: ${schemaValue}}`, + }; + function reportTypeError(it) { + const cxt = getTypeErrorContext(it); + (0, errors_1.reportError)(cxt, typeError); + } + exports.reportTypeError = reportTypeError; + function getTypeErrorContext(it) { + const { gen, data, schema } = it; + const schemaCode = (0, util_1.schemaRefOrVal)(it, schema, "type"); + return { + gen, + keyword: "type", + data, + schema: schema.type, + schemaCode, + schemaValue: schemaCode, + parentSchema: schema, + params: {}, + it, + }; + } + +} (dataType)); + +var defaults$5 = {}; + +var hasRequiredDefaults; + +function requireDefaults () { + if (hasRequiredDefaults) return defaults$5; + hasRequiredDefaults = 1; + Object.defineProperty(defaults$5, "__esModule", { value: true }); + defaults$5.assignDefaults = void 0; + const codegen_1 = requireCodegen(); + const util_1 = util$6; + function assignDefaults(it, ty) { + const { properties, items } = it.schema; + if (ty === "object" && properties) { + for (const key in properties) { + assignDefault(it, key, properties[key].default); + } + } + else if (ty === "array" && Array.isArray(items)) { + items.forEach((sch, i) => assignDefault(it, i, sch.default)); + } + } + defaults$5.assignDefaults = assignDefaults; + function assignDefault(it, prop, defaultValue) { + const { gen, compositeRule, data, opts } = it; + if (defaultValue === undefined) + return; + const childData = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(prop)}`; + if (compositeRule) { + (0, util_1.checkStrictMode)(it, `default is ignored for: ${childData}`); + return; + } + let condition = (0, codegen_1._) `${childData} === undefined`; + if (opts.useDefaults === "empty") { + condition = (0, codegen_1._) `${condition} || ${childData} === null || ${childData} === ""`; + } + // `${childData} === undefined` + + // (opts.useDefaults === "empty" ? ` || ${childData} === null || ${childData} === ""` : "") + gen.if(condition, (0, codegen_1._) `${childData} = ${(0, codegen_1.stringify)(defaultValue)}`); + } + + return defaults$5; +} + +var keyword = {}; + +var code = {}; + +var hasRequiredCode; + +function requireCode () { + if (hasRequiredCode) return code; + hasRequiredCode = 1; + Object.defineProperty(code, "__esModule", { value: true }); + code.validateUnion = code.validateArray = code.usePattern = code.callValidateCode = code.schemaProperties = code.allSchemaProperties = code.noPropertyInData = code.propertyInData = code.isOwnProperty = code.hasPropFunc = code.reportMissingProp = code.checkMissingProp = code.checkReportMissingProp = void 0; + const codegen_1 = requireCodegen(); + const util_1 = util$6; + const names_1 = requireNames(); + const util_2 = util$6; + function checkReportMissingProp(cxt, prop) { + const { gen, data, it } = cxt; + gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => { + cxt.setParams({ missingProperty: (0, codegen_1._) `${prop}` }, true); + cxt.error(); + }); + } + code.checkReportMissingProp = checkReportMissingProp; + function checkMissingProp({ gen, data, it: { opts } }, properties, missing) { + return (0, codegen_1.or)(...properties.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data, prop, opts.ownProperties), (0, codegen_1._) `${missing} = ${prop}`))); + } + code.checkMissingProp = checkMissingProp; + function reportMissingProp(cxt, missing) { + cxt.setParams({ missingProperty: missing }, true); + cxt.error(); + } + code.reportMissingProp = reportMissingProp; + function hasPropFunc(gen) { + return gen.scopeValue("func", { + // eslint-disable-next-line @typescript-eslint/unbound-method + ref: Object.prototype.hasOwnProperty, + code: (0, codegen_1._) `Object.prototype.hasOwnProperty`, + }); + } + code.hasPropFunc = hasPropFunc; + function isOwnProperty(gen, data, property) { + return (0, codegen_1._) `${hasPropFunc(gen)}.call(${data}, ${property})`; + } + code.isOwnProperty = isOwnProperty; + function propertyInData(gen, data, property, ownProperties) { + const cond = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(property)} !== undefined`; + return ownProperties ? (0, codegen_1._) `${cond} && ${isOwnProperty(gen, data, property)}` : cond; + } + code.propertyInData = propertyInData; + function noPropertyInData(gen, data, property, ownProperties) { + const cond = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(property)} === undefined`; + return ownProperties ? (0, codegen_1.or)(cond, (0, codegen_1.not)(isOwnProperty(gen, data, property))) : cond; + } + code.noPropertyInData = noPropertyInData; + function allSchemaProperties(schemaMap) { + return schemaMap ? Object.keys(schemaMap).filter((p) => p !== "__proto__") : []; + } + code.allSchemaProperties = allSchemaProperties; + function schemaProperties(it, schemaMap) { + return allSchemaProperties(schemaMap).filter((p) => !(0, util_1.alwaysValidSchema)(it, schemaMap[p])); + } + code.schemaProperties = schemaProperties; + function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it }, func, context, passSchema) { + const dataAndSchema = passSchema ? (0, codegen_1._) `${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data; + const valCxt = [ + [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, errorPath)], + [names_1.default.parentData, it.parentData], + [names_1.default.parentDataProperty, it.parentDataProperty], + [names_1.default.rootData, names_1.default.rootData], + ]; + if (it.opts.dynamicRef) + valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]); + const args = (0, codegen_1._) `${dataAndSchema}, ${gen.object(...valCxt)}`; + return context !== codegen_1.nil ? (0, codegen_1._) `${func}.call(${context}, ${args})` : (0, codegen_1._) `${func}(${args})`; + } + code.callValidateCode = callValidateCode; + const newRegExp = (0, codegen_1._) `new RegExp`; + function usePattern({ gen, it: { opts } }, pattern) { + const u = opts.unicodeRegExp ? "u" : ""; + const { regExp } = opts.code; + const rx = regExp(pattern, u); + return gen.scopeValue("pattern", { + key: rx.toString(), + ref: rx, + code: (0, codegen_1._) `${regExp.code === "new RegExp" ? newRegExp : (0, util_2.useFunc)(gen, regExp)}(${pattern}, ${u})`, + }); + } + code.usePattern = usePattern; + function validateArray(cxt) { + const { gen, data, keyword, it } = cxt; + const valid = gen.name("valid"); + if (it.allErrors) { + const validArr = gen.let("valid", true); + validateItems(() => gen.assign(validArr, false)); + return validArr; + } + gen.var(valid, true); + validateItems(() => gen.break()); + return valid; + function validateItems(notValid) { + const len = gen.const("len", (0, codegen_1._) `${data}.length`); + gen.forRange("i", 0, len, (i) => { + cxt.subschema({ + keyword, + dataProp: i, + dataPropType: util_1.Type.Num, + }, valid); + gen.if((0, codegen_1.not)(valid), notValid); + }); + } + } + code.validateArray = validateArray; + function validateUnion(cxt) { + const { gen, schema, keyword, it } = cxt; + /* istanbul ignore if */ + if (!Array.isArray(schema)) + throw new Error("ajv implementation error"); + const alwaysValid = schema.some((sch) => (0, util_1.alwaysValidSchema)(it, sch)); + if (alwaysValid && !it.opts.unevaluated) + return; + const valid = gen.let("valid", false); + const schValid = gen.name("_valid"); + gen.block(() => schema.forEach((_sch, i) => { + const schCxt = cxt.subschema({ + keyword, + schemaProp: i, + compositeRule: true, + }, schValid); + gen.assign(valid, (0, codegen_1._) `${valid} || ${schValid}`); + const merged = cxt.mergeValidEvaluated(schCxt, schValid); + // can short-circuit if `unevaluatedProperties/Items` not supported (opts.unevaluated !== true) + // or if all properties and items were evaluated (it.props === true && it.items === true) + if (!merged) + gen.if((0, codegen_1.not)(valid)); + })); + cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); + } + code.validateUnion = validateUnion; + + return code; +} + +var hasRequiredKeyword; + +function requireKeyword () { + if (hasRequiredKeyword) return keyword; + hasRequiredKeyword = 1; + Object.defineProperty(keyword, "__esModule", { value: true }); + keyword.validateKeywordUsage = keyword.validSchemaType = keyword.funcKeywordCode = keyword.macroKeywordCode = void 0; + const codegen_1 = requireCodegen(); + const names_1 = requireNames(); + const code_1 = requireCode(); + const errors_1 = requireErrors$1(); + function macroKeywordCode(cxt, def) { + const { gen, keyword, schema, parentSchema, it } = cxt; + const macroSchema = def.macro.call(it.self, schema, parentSchema, it); + const schemaRef = useKeyword(gen, keyword, macroSchema); + if (it.opts.validateSchema !== false) + it.self.validateSchema(macroSchema, true); + const valid = gen.name("valid"); + cxt.subschema({ + schema: macroSchema, + schemaPath: codegen_1.nil, + errSchemaPath: `${it.errSchemaPath}/${keyword}`, + topSchemaRef: schemaRef, + compositeRule: true, + }, valid); + cxt.pass(valid, () => cxt.error(true)); + } + keyword.macroKeywordCode = macroKeywordCode; + function funcKeywordCode(cxt, def) { + var _a; + const { gen, keyword, schema, parentSchema, $data, it } = cxt; + checkAsyncKeyword(it, def); + const validate = !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate; + const validateRef = useKeyword(gen, keyword, validate); + const valid = gen.let("valid"); + cxt.block$data(valid, validateKeyword); + cxt.ok((_a = def.valid) !== null && _a !== void 0 ? _a : valid); + function validateKeyword() { + if (def.errors === false) { + assignValid(); + if (def.modifying) + modifyData(cxt); + reportErrs(() => cxt.error()); + } + else { + const ruleErrs = def.async ? validateAsync() : validateSync(); + if (def.modifying) + modifyData(cxt); + reportErrs(() => addErrs(cxt, ruleErrs)); + } + } + function validateAsync() { + const ruleErrs = gen.let("ruleErrs", null); + gen.try(() => assignValid((0, codegen_1._) `await `), (e) => gen.assign(valid, false).if((0, codegen_1._) `${e} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._) `${e}.errors`), () => gen.throw(e))); + return ruleErrs; + } + function validateSync() { + const validateErrs = (0, codegen_1._) `${validateRef}.errors`; + gen.assign(validateErrs, null); + assignValid(codegen_1.nil); + return validateErrs; + } + function assignValid(_await = def.async ? (0, codegen_1._) `await ` : codegen_1.nil) { + const passCxt = it.opts.passContext ? names_1.default.this : names_1.default.self; + const passSchema = !(("compile" in def && !$data) || def.schema === false); + gen.assign(valid, (0, codegen_1._) `${_await}${(0, code_1.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def.modifying); + } + function reportErrs(errors) { + var _a; + gen.if((0, codegen_1.not)((_a = def.valid) !== null && _a !== void 0 ? _a : valid), errors); + } + } + keyword.funcKeywordCode = funcKeywordCode; + function modifyData(cxt) { + const { gen, data, it } = cxt; + gen.if(it.parentData, () => gen.assign(data, (0, codegen_1._) `${it.parentData}[${it.parentDataProperty}]`)); + } + function addErrs(cxt, errs) { + const { gen } = cxt; + gen.if((0, codegen_1._) `Array.isArray(${errs})`, () => { + gen + .assign(names_1.default.vErrors, (0, codegen_1._) `${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`) + .assign(names_1.default.errors, (0, codegen_1._) `${names_1.default.vErrors}.length`); + (0, errors_1.extendErrors)(cxt); + }, () => cxt.error()); + } + function checkAsyncKeyword({ schemaEnv }, def) { + if (def.async && !schemaEnv.$async) + throw new Error("async keyword in sync schema"); + } + function useKeyword(gen, keyword, result) { + if (result === undefined) + throw new Error(`keyword "${keyword}" failed to compile`); + return gen.scopeValue("keyword", typeof result == "function" ? { ref: result } : { ref: result, code: (0, codegen_1.stringify)(result) }); + } + function validSchemaType(schema, schemaType, allowUndefined = false) { + // TODO add tests + return (!schemaType.length || + schemaType.some((st) => st === "array" + ? Array.isArray(schema) + : st === "object" + ? schema && typeof schema == "object" && !Array.isArray(schema) + : typeof schema == st || (allowUndefined && typeof schema == "undefined"))); + } + keyword.validSchemaType = validSchemaType; + function validateKeywordUsage({ schema, opts, self, errSchemaPath }, def, keyword) { + /* istanbul ignore if */ + if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) { + throw new Error("ajv implementation error"); + } + const deps = def.dependencies; + if (deps === null || deps === void 0 ? void 0 : deps.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) { + throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`); + } + if (def.validateSchema) { + const valid = def.validateSchema(schema[keyword]); + if (!valid) { + const msg = `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` + + self.errorsText(def.validateSchema.errors); + if (opts.validateSchema === "log") + self.logger.error(msg); + else + throw new Error(msg); + } + } + } + keyword.validateKeywordUsage = validateKeywordUsage; + + return keyword; +} + +var subschema = {}; + +var hasRequiredSubschema; + +function requireSubschema () { + if (hasRequiredSubschema) return subschema; + hasRequiredSubschema = 1; + Object.defineProperty(subschema, "__esModule", { value: true }); + subschema.extendSubschemaMode = subschema.extendSubschemaData = subschema.getSubschema = void 0; + const codegen_1 = requireCodegen(); + const util_1 = util$6; + function getSubschema(it, { keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef }) { + if (keyword !== undefined && schema !== undefined) { + throw new Error('both "keyword" and "schema" passed, only one allowed'); + } + if (keyword !== undefined) { + const sch = it.schema[keyword]; + return schemaProp === undefined + ? { + schema: sch, + schemaPath: (0, codegen_1._) `${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}`, + errSchemaPath: `${it.errSchemaPath}/${keyword}`, + } + : { + schema: sch[schemaProp], + schemaPath: (0, codegen_1._) `${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`, + errSchemaPath: `${it.errSchemaPath}/${keyword}/${(0, util_1.escapeFragment)(schemaProp)}`, + }; + } + if (schema !== undefined) { + if (schemaPath === undefined || errSchemaPath === undefined || topSchemaRef === undefined) { + throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"'); + } + return { + schema, + schemaPath, + topSchemaRef, + errSchemaPath, + }; + } + throw new Error('either "keyword" or "schema" must be passed'); + } + subschema.getSubschema = getSubschema; + function extendSubschemaData(subschema, it, { dataProp, dataPropType: dpType, data, dataTypes, propertyName }) { + if (data !== undefined && dataProp !== undefined) { + throw new Error('both "data" and "dataProp" passed, only one allowed'); + } + const { gen } = it; + if (dataProp !== undefined) { + const { errorPath, dataPathArr, opts } = it; + const nextData = gen.let("data", (0, codegen_1._) `${it.data}${(0, codegen_1.getProperty)(dataProp)}`, true); + dataContextProps(nextData); + subschema.errorPath = (0, codegen_1.str) `${errorPath}${(0, util_1.getErrorPath)(dataProp, dpType, opts.jsPropertySyntax)}`; + subschema.parentDataProperty = (0, codegen_1._) `${dataProp}`; + subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty]; + } + if (data !== undefined) { + const nextData = data instanceof codegen_1.Name ? data : gen.let("data", data, true); // replaceable if used once? + dataContextProps(nextData); + if (propertyName !== undefined) + subschema.propertyName = propertyName; + // TODO something is possibly wrong here with not changing parentDataProperty and not appending dataPathArr + } + if (dataTypes) + subschema.dataTypes = dataTypes; + function dataContextProps(_nextData) { + subschema.data = _nextData; + subschema.dataLevel = it.dataLevel + 1; + subschema.dataTypes = []; + it.definedProperties = new Set(); + subschema.parentData = it.data; + subschema.dataNames = [...it.dataNames, _nextData]; + } + } + subschema.extendSubschemaData = extendSubschemaData; + function extendSubschemaMode(subschema, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) { + if (compositeRule !== undefined) + subschema.compositeRule = compositeRule; + if (createErrors !== undefined) + subschema.createErrors = createErrors; + if (allErrors !== undefined) + subschema.allErrors = allErrors; + subschema.jtdDiscriminator = jtdDiscriminator; // not inherited + subschema.jtdMetadata = jtdMetadata; // not inherited + } + subschema.extendSubschemaMode = extendSubschemaMode; + + return subschema; +} + +var resolve$2 = {}; + +// do not edit .js files directly - edit src/index.jst + + + +var fastDeepEqual = function equal(a, b) { + if (a === b) return true; + + if (a && b && typeof a == 'object' && typeof b == 'object') { + if (a.constructor !== b.constructor) return false; + + var length, i, keys; + if (Array.isArray(a)) { + length = a.length; + if (length != b.length) return false; + for (i = length; i-- !== 0;) + if (!equal(a[i], b[i])) return false; + return true; + } + + + + if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; + if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); + if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); + + keys = Object.keys(a); + length = keys.length; + if (length !== Object.keys(b).length) return false; + + for (i = length; i-- !== 0;) + if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; + + for (i = length; i-- !== 0;) { + var key = keys[i]; + + if (!equal(a[key], b[key])) return false; + } + + return true; + } + + // true if both NaN, false otherwise + return a!==a && b!==b; +}; + +var jsonSchemaTraverse = {exports: {}}; + +var traverse$1 = jsonSchemaTraverse.exports = function (schema, opts, cb) { + // Legacy support for v0.3.1 and earlier. + if (typeof opts == 'function') { + cb = opts; + opts = {}; + } + + cb = opts.cb || cb; + var pre = (typeof cb == 'function') ? cb : cb.pre || function() {}; + var post = cb.post || function() {}; + + _traverse(opts, pre, post, schema, '', schema); +}; + + +traverse$1.keywords = { + additionalItems: true, + items: true, + contains: true, + additionalProperties: true, + propertyNames: true, + not: true, + if: true, + then: true, + else: true +}; + +traverse$1.arrayKeywords = { + items: true, + allOf: true, + anyOf: true, + oneOf: true +}; + +traverse$1.propsKeywords = { + $defs: true, + definitions: true, + properties: true, + patternProperties: true, + dependencies: true +}; + +traverse$1.skipKeywords = { + default: true, + enum: true, + const: true, + required: true, + maximum: true, + minimum: true, + exclusiveMaximum: true, + exclusiveMinimum: true, + multipleOf: true, + maxLength: true, + minLength: true, + pattern: true, + format: true, + maxItems: true, + minItems: true, + uniqueItems: true, + maxProperties: true, + minProperties: true +}; + + +function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) { + if (schema && typeof schema == 'object' && !Array.isArray(schema)) { + pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); + for (var key in schema) { + var sch = schema[key]; + if (Array.isArray(sch)) { + if (key in traverse$1.arrayKeywords) { + for (var i=0; i<sch.length; i++) + _traverse(opts, pre, post, sch[i], jsonPtr + '/' + key + '/' + i, rootSchema, jsonPtr, key, schema, i); + } + } else if (key in traverse$1.propsKeywords) { + if (sch && typeof sch == 'object') { + for (var prop in sch) + _traverse(opts, pre, post, sch[prop], jsonPtr + '/' + key + '/' + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop); + } + } else if (key in traverse$1.keywords || (opts.allKeys && !(key in traverse$1.skipKeywords))) { + _traverse(opts, pre, post, sch, jsonPtr + '/' + key, rootSchema, jsonPtr, key, schema); + } + } + post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); + } +} + + +function escapeJsonPtr(str) { + return str.replace(/~/g, '~0').replace(/\//g, '~1'); +} + +var jsonSchemaTraverseExports = jsonSchemaTraverse.exports; + +Object.defineProperty(resolve$2, "__esModule", { value: true }); +resolve$2.getSchemaRefs = resolve$2.resolveUrl = resolve$2.normalizeId = resolve$2._getFullPath = resolve$2.getFullPath = resolve$2.inlineRef = void 0; +const util_1$p = util$6; +const equal$2 = fastDeepEqual; +const traverse = jsonSchemaTraverseExports; +// TODO refactor to use keyword definitions +const SIMPLE_INLINED = new Set([ + "type", + "format", + "pattern", + "maxLength", + "minLength", + "maxProperties", + "minProperties", + "maxItems", + "minItems", + "maximum", + "minimum", + "uniqueItems", + "multipleOf", + "required", + "enum", + "const", +]); +function inlineRef(schema, limit = true) { + if (typeof schema == "boolean") + return true; + if (limit === true) + return !hasRef(schema); + if (!limit) + return false; + return countKeys(schema) <= limit; +} +resolve$2.inlineRef = inlineRef; +const REF_KEYWORDS = new Set([ + "$ref", + "$recursiveRef", + "$recursiveAnchor", + "$dynamicRef", + "$dynamicAnchor", +]); +function hasRef(schema) { + for (const key in schema) { + if (REF_KEYWORDS.has(key)) + return true; + const sch = schema[key]; + if (Array.isArray(sch) && sch.some(hasRef)) + return true; + if (typeof sch == "object" && hasRef(sch)) + return true; + } + return false; +} +function countKeys(schema) { + let count = 0; + for (const key in schema) { + if (key === "$ref") + return Infinity; + count++; + if (SIMPLE_INLINED.has(key)) + continue; + if (typeof schema[key] == "object") { + (0, util_1$p.eachItem)(schema[key], (sch) => (count += countKeys(sch))); + } + if (count === Infinity) + return Infinity; + } + return count; +} +function getFullPath(resolver, id = "", normalize) { + if (normalize !== false) + id = normalizeId(id); + const p = resolver.parse(id); + return _getFullPath(resolver, p); +} +resolve$2.getFullPath = getFullPath; +function _getFullPath(resolver, p) { + const serialized = resolver.serialize(p); + return serialized.split("#")[0] + "#"; +} +resolve$2._getFullPath = _getFullPath; +const TRAILING_SLASH_HASH = /#\/?$/; +function normalizeId(id) { + return id ? id.replace(TRAILING_SLASH_HASH, "") : ""; +} +resolve$2.normalizeId = normalizeId; +function resolveUrl(resolver, baseId, id) { + id = normalizeId(id); + return resolver.resolve(baseId, id); +} +resolve$2.resolveUrl = resolveUrl; +const ANCHOR = /^[a-z_][-a-z0-9._]*$/i; +function getSchemaRefs(schema, baseId) { + if (typeof schema == "boolean") + return {}; + const { schemaId, uriResolver } = this.opts; + const schId = normalizeId(schema[schemaId] || baseId); + const baseIds = { "": schId }; + const pathPrefix = getFullPath(uriResolver, schId, false); + const localRefs = {}; + const schemaRefs = new Set(); + traverse(schema, { allKeys: true }, (sch, jsonPtr, _, parentJsonPtr) => { + if (parentJsonPtr === undefined) + return; + const fullPath = pathPrefix + jsonPtr; + let baseId = baseIds[parentJsonPtr]; + if (typeof sch[schemaId] == "string") + baseId = addRef.call(this, sch[schemaId]); + addAnchor.call(this, sch.$anchor); + addAnchor.call(this, sch.$dynamicAnchor); + baseIds[jsonPtr] = baseId; + function addRef(ref) { + // eslint-disable-next-line @typescript-eslint/unbound-method + const _resolve = this.opts.uriResolver.resolve; + ref = normalizeId(baseId ? _resolve(baseId, ref) : ref); + if (schemaRefs.has(ref)) + throw ambiguos(ref); + schemaRefs.add(ref); + let schOrRef = this.refs[ref]; + if (typeof schOrRef == "string") + schOrRef = this.refs[schOrRef]; + if (typeof schOrRef == "object") { + checkAmbiguosRef(sch, schOrRef.schema, ref); + } + else if (ref !== normalizeId(fullPath)) { + if (ref[0] === "#") { + checkAmbiguosRef(sch, localRefs[ref], ref); + localRefs[ref] = sch; + } + else { + this.refs[ref] = fullPath; + } + } + return ref; + } + function addAnchor(anchor) { + if (typeof anchor == "string") { + if (!ANCHOR.test(anchor)) + throw new Error(`invalid anchor "${anchor}"`); + addRef.call(this, `#${anchor}`); + } + } + }); + return localRefs; + function checkAmbiguosRef(sch1, sch2, ref) { + if (sch2 !== undefined && !equal$2(sch1, sch2)) + throw ambiguos(ref); + } + function ambiguos(ref) { + return new Error(`reference "${ref}" resolves to more than one schema`); + } +} +resolve$2.getSchemaRefs = getSchemaRefs; + +var hasRequiredValidate; + +function requireValidate () { + if (hasRequiredValidate) return validate; + hasRequiredValidate = 1; + Object.defineProperty(validate, "__esModule", { value: true }); + validate.getData = validate.KeywordCxt = validate.validateFunctionCode = void 0; + const boolSchema_1 = requireBoolSchema(); + const dataType_1 = dataType; + const applicability_1 = requireApplicability(); + const dataType_2 = dataType; + const defaults_1 = requireDefaults(); + const keyword_1 = requireKeyword(); + const subschema_1 = requireSubschema(); + const codegen_1 = requireCodegen(); + const names_1 = requireNames(); + const resolve_1 = resolve$2; + const util_1 = util$6; + const errors_1 = requireErrors$1(); + // schema compilation - generates validation function, subschemaCode (below) is used for subschemas + function validateFunctionCode(it) { + if (isSchemaObj(it)) { + checkKeywords(it); + if (schemaCxtHasRules(it)) { + topSchemaObjCode(it); + return; + } + } + validateFunction(it, () => (0, boolSchema_1.topBoolOrEmptySchema)(it)); + } + validate.validateFunctionCode = validateFunctionCode; + function validateFunction({ gen, validateName, schema, schemaEnv, opts }, body) { + if (opts.code.es5) { + gen.func(validateName, (0, codegen_1._) `${names_1.default.data}, ${names_1.default.valCxt}`, schemaEnv.$async, () => { + gen.code((0, codegen_1._) `"use strict"; ${funcSourceUrl(schema, opts)}`); + destructureValCxtES5(gen, opts); + gen.code(body); + }); + } + else { + gen.func(validateName, (0, codegen_1._) `${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body)); + } + } + function destructureValCxt(opts) { + return (0, codegen_1._) `{${names_1.default.instancePath}="", ${names_1.default.parentData}, ${names_1.default.parentDataProperty}, ${names_1.default.rootData}=${names_1.default.data}${opts.dynamicRef ? (0, codegen_1._) `, ${names_1.default.dynamicAnchors}={}` : codegen_1.nil}}={}`; + } + function destructureValCxtES5(gen, opts) { + gen.if(names_1.default.valCxt, () => { + gen.var(names_1.default.instancePath, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.instancePath}`); + gen.var(names_1.default.parentData, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.parentData}`); + gen.var(names_1.default.parentDataProperty, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.parentDataProperty}`); + gen.var(names_1.default.rootData, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.rootData}`); + if (opts.dynamicRef) + gen.var(names_1.default.dynamicAnchors, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`); + }, () => { + gen.var(names_1.default.instancePath, (0, codegen_1._) `""`); + gen.var(names_1.default.parentData, (0, codegen_1._) `undefined`); + gen.var(names_1.default.parentDataProperty, (0, codegen_1._) `undefined`); + gen.var(names_1.default.rootData, names_1.default.data); + if (opts.dynamicRef) + gen.var(names_1.default.dynamicAnchors, (0, codegen_1._) `{}`); + }); + } + function topSchemaObjCode(it) { + const { schema, opts, gen } = it; + validateFunction(it, () => { + if (opts.$comment && schema.$comment) + commentKeyword(it); + checkNoDefault(it); + gen.let(names_1.default.vErrors, null); + gen.let(names_1.default.errors, 0); + if (opts.unevaluated) + resetEvaluated(it); + typeAndKeywords(it); + returnResults(it); + }); + return; + } + function resetEvaluated(it) { + // TODO maybe some hook to execute it in the end to check whether props/items are Name, as in assignEvaluated + const { gen, validateName } = it; + it.evaluated = gen.const("evaluated", (0, codegen_1._) `${validateName}.evaluated`); + gen.if((0, codegen_1._) `${it.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._) `${it.evaluated}.props`, (0, codegen_1._) `undefined`)); + gen.if((0, codegen_1._) `${it.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._) `${it.evaluated}.items`, (0, codegen_1._) `undefined`)); + } + function funcSourceUrl(schema, opts) { + const schId = typeof schema == "object" && schema[opts.schemaId]; + return schId && (opts.code.source || opts.code.process) ? (0, codegen_1._) `/*# sourceURL=${schId} */` : codegen_1.nil; + } + // schema compilation - this function is used recursively to generate code for sub-schemas + function subschemaCode(it, valid) { + if (isSchemaObj(it)) { + checkKeywords(it); + if (schemaCxtHasRules(it)) { + subSchemaObjCode(it, valid); + return; + } + } + (0, boolSchema_1.boolOrEmptySchema)(it, valid); + } + function schemaCxtHasRules({ schema, self }) { + if (typeof schema == "boolean") + return !schema; + for (const key in schema) + if (self.RULES.all[key]) + return true; + return false; + } + function isSchemaObj(it) { + return typeof it.schema != "boolean"; + } + function subSchemaObjCode(it, valid) { + const { schema, gen, opts } = it; + if (opts.$comment && schema.$comment) + commentKeyword(it); + updateContext(it); + checkAsyncSchema(it); + const errsCount = gen.const("_errs", names_1.default.errors); + typeAndKeywords(it, errsCount); + // TODO var + gen.var(valid, (0, codegen_1._) `${errsCount} === ${names_1.default.errors}`); + } + function checkKeywords(it) { + (0, util_1.checkUnknownRules)(it); + checkRefsAndKeywords(it); + } + function typeAndKeywords(it, errsCount) { + if (it.opts.jtd) + return schemaKeywords(it, [], false, errsCount); + const types = (0, dataType_1.getSchemaTypes)(it.schema); + const checkedTypes = (0, dataType_1.coerceAndCheckDataType)(it, types); + schemaKeywords(it, types, !checkedTypes, errsCount); + } + function checkRefsAndKeywords(it) { + const { schema, errSchemaPath, opts, self } = it; + if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema, self.RULES)) { + self.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`); + } + } + function checkNoDefault(it) { + const { schema, opts } = it; + if (schema.default !== undefined && opts.useDefaults && opts.strictSchema) { + (0, util_1.checkStrictMode)(it, "default is ignored in the schema root"); + } + } + function updateContext(it) { + const schId = it.schema[it.opts.schemaId]; + if (schId) + it.baseId = (0, resolve_1.resolveUrl)(it.opts.uriResolver, it.baseId, schId); + } + function checkAsyncSchema(it) { + if (it.schema.$async && !it.schemaEnv.$async) + throw new Error("async schema in sync schema"); + } + function commentKeyword({ gen, schemaEnv, schema, errSchemaPath, opts }) { + const msg = schema.$comment; + if (opts.$comment === true) { + gen.code((0, codegen_1._) `${names_1.default.self}.logger.log(${msg})`); + } + else if (typeof opts.$comment == "function") { + const schemaPath = (0, codegen_1.str) `${errSchemaPath}/$comment`; + const rootName = gen.scopeValue("root", { ref: schemaEnv.root }); + gen.code((0, codegen_1._) `${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`); + } + } + function returnResults(it) { + const { gen, schemaEnv, validateName, ValidationError, opts } = it; + if (schemaEnv.$async) { + // TODO assign unevaluated + gen.if((0, codegen_1._) `${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._) `new ${ValidationError}(${names_1.default.vErrors})`)); + } + else { + gen.assign((0, codegen_1._) `${validateName}.errors`, names_1.default.vErrors); + if (opts.unevaluated) + assignEvaluated(it); + gen.return((0, codegen_1._) `${names_1.default.errors} === 0`); + } + } + function assignEvaluated({ gen, evaluated, props, items }) { + if (props instanceof codegen_1.Name) + gen.assign((0, codegen_1._) `${evaluated}.props`, props); + if (items instanceof codegen_1.Name) + gen.assign((0, codegen_1._) `${evaluated}.items`, items); + } + function schemaKeywords(it, types, typeErrors, errsCount) { + const { gen, schema, data, allErrors, opts, self } = it; + const { RULES } = self; + if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) { + gen.block(() => keywordCode(it, "$ref", RULES.all.$ref.definition)); // TODO typecast + return; + } + if (!opts.jtd) + checkStrictTypes(it, types); + gen.block(() => { + for (const group of RULES.rules) + groupKeywords(group); + groupKeywords(RULES.post); + }); + function groupKeywords(group) { + if (!(0, applicability_1.shouldUseGroup)(schema, group)) + return; + if (group.type) { + gen.if((0, dataType_2.checkDataType)(group.type, data, opts.strictNumbers)); + iterateKeywords(it, group); + if (types.length === 1 && types[0] === group.type && typeErrors) { + gen.else(); + (0, dataType_2.reportTypeError)(it); + } + gen.endIf(); + } + else { + iterateKeywords(it, group); + } + // TODO make it "ok" call? + if (!allErrors) + gen.if((0, codegen_1._) `${names_1.default.errors} === ${errsCount || 0}`); + } + } + function iterateKeywords(it, group) { + const { gen, schema, opts: { useDefaults }, } = it; + if (useDefaults) + (0, defaults_1.assignDefaults)(it, group.type); + gen.block(() => { + for (const rule of group.rules) { + if ((0, applicability_1.shouldUseRule)(schema, rule)) { + keywordCode(it, rule.keyword, rule.definition, group.type); + } + } + }); + } + function checkStrictTypes(it, types) { + if (it.schemaEnv.meta || !it.opts.strictTypes) + return; + checkContextTypes(it, types); + if (!it.opts.allowUnionTypes) + checkMultipleTypes(it, types); + checkKeywordTypes(it, it.dataTypes); + } + function checkContextTypes(it, types) { + if (!types.length) + return; + if (!it.dataTypes.length) { + it.dataTypes = types; + return; + } + types.forEach((t) => { + if (!includesType(it.dataTypes, t)) { + strictTypesError(it, `type "${t}" not allowed by context "${it.dataTypes.join(",")}"`); + } + }); + narrowSchemaTypes(it, types); + } + function checkMultipleTypes(it, ts) { + if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) { + strictTypesError(it, "use allowUnionTypes to allow union type keyword"); + } + } + function checkKeywordTypes(it, ts) { + const rules = it.self.RULES.all; + for (const keyword in rules) { + const rule = rules[keyword]; + if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it.schema, rule)) { + const { type } = rule.definition; + if (type.length && !type.some((t) => hasApplicableType(ts, t))) { + strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`); + } + } + } + } + function hasApplicableType(schTs, kwdT) { + return schTs.includes(kwdT) || (kwdT === "number" && schTs.includes("integer")); + } + function includesType(ts, t) { + return ts.includes(t) || (t === "integer" && ts.includes("number")); + } + function narrowSchemaTypes(it, withTypes) { + const ts = []; + for (const t of it.dataTypes) { + if (includesType(withTypes, t)) + ts.push(t); + else if (withTypes.includes("integer") && t === "number") + ts.push("integer"); + } + it.dataTypes = ts; + } + function strictTypesError(it, msg) { + const schemaPath = it.schemaEnv.baseId + it.errSchemaPath; + msg += ` at "${schemaPath}" (strictTypes)`; + (0, util_1.checkStrictMode)(it, msg, it.opts.strictTypes); + } + class KeywordCxt { + constructor(it, def, keyword) { + (0, keyword_1.validateKeywordUsage)(it, def, keyword); + this.gen = it.gen; + this.allErrors = it.allErrors; + this.keyword = keyword; + this.data = it.data; + this.schema = it.schema[keyword]; + this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data; + this.schemaValue = (0, util_1.schemaRefOrVal)(it, this.schema, keyword, this.$data); + this.schemaType = def.schemaType; + this.parentSchema = it.schema; + this.params = {}; + this.it = it; + this.def = def; + if (this.$data) { + this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)); + } + else { + this.schemaCode = this.schemaValue; + if (!(0, keyword_1.validSchemaType)(this.schema, def.schemaType, def.allowUndefined)) { + throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`); + } + } + if ("code" in def ? def.trackErrors : def.errors !== false) { + this.errsCount = it.gen.const("_errs", names_1.default.errors); + } + } + result(condition, successAction, failAction) { + this.failResult((0, codegen_1.not)(condition), successAction, failAction); + } + failResult(condition, successAction, failAction) { + this.gen.if(condition); + if (failAction) + failAction(); + else + this.error(); + if (successAction) { + this.gen.else(); + successAction(); + if (this.allErrors) + this.gen.endIf(); + } + else { + if (this.allErrors) + this.gen.endIf(); + else + this.gen.else(); + } + } + pass(condition, failAction) { + this.failResult((0, codegen_1.not)(condition), undefined, failAction); + } + fail(condition) { + if (condition === undefined) { + this.error(); + if (!this.allErrors) + this.gen.if(false); // this branch will be removed by gen.optimize + return; + } + this.gen.if(condition); + this.error(); + if (this.allErrors) + this.gen.endIf(); + else + this.gen.else(); + } + fail$data(condition) { + if (!this.$data) + return this.fail(condition); + const { schemaCode } = this; + this.fail((0, codegen_1._) `${schemaCode} !== undefined && (${(0, codegen_1.or)(this.invalid$data(), condition)})`); + } + error(append, errorParams, errorPaths) { + if (errorParams) { + this.setParams(errorParams); + this._error(append, errorPaths); + this.setParams({}); + return; + } + this._error(append, errorPaths); + } + _error(append, errorPaths) { + (append ? errors_1.reportExtraError : errors_1.reportError)(this, this.def.error, errorPaths); + } + $dataError() { + (0, errors_1.reportError)(this, this.def.$dataError || errors_1.keyword$DataError); + } + reset() { + if (this.errsCount === undefined) + throw new Error('add "trackErrors" to keyword definition'); + (0, errors_1.resetErrorsCount)(this.gen, this.errsCount); + } + ok(cond) { + if (!this.allErrors) + this.gen.if(cond); + } + setParams(obj, assign) { + if (assign) + Object.assign(this.params, obj); + else + this.params = obj; + } + block$data(valid, codeBlock, $dataValid = codegen_1.nil) { + this.gen.block(() => { + this.check$data(valid, $dataValid); + codeBlock(); + }); + } + check$data(valid = codegen_1.nil, $dataValid = codegen_1.nil) { + if (!this.$data) + return; + const { gen, schemaCode, schemaType, def } = this; + gen.if((0, codegen_1.or)((0, codegen_1._) `${schemaCode} === undefined`, $dataValid)); + if (valid !== codegen_1.nil) + gen.assign(valid, true); + if (schemaType.length || def.validateSchema) { + gen.elseIf(this.invalid$data()); + this.$dataError(); + if (valid !== codegen_1.nil) + gen.assign(valid, false); + } + gen.else(); + } + invalid$data() { + const { gen, schemaCode, schemaType, def, it } = this; + return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema()); + function wrong$DataType() { + if (schemaType.length) { + /* istanbul ignore if */ + if (!(schemaCode instanceof codegen_1.Name)) + throw new Error("ajv implementation error"); + const st = Array.isArray(schemaType) ? schemaType : [schemaType]; + return (0, codegen_1._) `${(0, dataType_2.checkDataTypes)(st, schemaCode, it.opts.strictNumbers, dataType_2.DataType.Wrong)}`; + } + return codegen_1.nil; + } + function invalid$DataSchema() { + if (def.validateSchema) { + const validateSchemaRef = gen.scopeValue("validate$data", { ref: def.validateSchema }); // TODO value.code for standalone + return (0, codegen_1._) `!${validateSchemaRef}(${schemaCode})`; + } + return codegen_1.nil; + } + } + subschema(appl, valid) { + const subschema = (0, subschema_1.getSubschema)(this.it, appl); + (0, subschema_1.extendSubschemaData)(subschema, this.it, appl); + (0, subschema_1.extendSubschemaMode)(subschema, appl); + const nextContext = { ...this.it, ...subschema, items: undefined, props: undefined }; + subschemaCode(nextContext, valid); + return nextContext; + } + mergeEvaluated(schemaCxt, toName) { + const { it, gen } = this; + if (!it.opts.unevaluated) + return; + if (it.props !== true && schemaCxt.props !== undefined) { + it.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it.props, toName); + } + if (it.items !== true && schemaCxt.items !== undefined) { + it.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it.items, toName); + } + } + mergeValidEvaluated(schemaCxt, valid) { + const { it, gen } = this; + if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { + gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name)); + return true; + } + } + } + validate.KeywordCxt = KeywordCxt; + function keywordCode(it, keyword, def, ruleType) { + const cxt = new KeywordCxt(it, def, keyword); + if ("code" in def) { + def.code(cxt, ruleType); + } + else if (cxt.$data && def.validate) { + (0, keyword_1.funcKeywordCode)(cxt, def); + } + else if ("macro" in def) { + (0, keyword_1.macroKeywordCode)(cxt, def); + } + else if (def.compile || def.validate) { + (0, keyword_1.funcKeywordCode)(cxt, def); + } + } + const JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/; + const RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/; + function getData($data, { dataLevel, dataNames, dataPathArr }) { + let jsonPointer; + let data; + if ($data === "") + return names_1.default.rootData; + if ($data[0] === "/") { + if (!JSON_POINTER.test($data)) + throw new Error(`Invalid JSON-pointer: ${$data}`); + jsonPointer = $data; + data = names_1.default.rootData; + } + else { + const matches = RELATIVE_JSON_POINTER.exec($data); + if (!matches) + throw new Error(`Invalid JSON-pointer: ${$data}`); + const up = +matches[1]; + jsonPointer = matches[2]; + if (jsonPointer === "#") { + if (up >= dataLevel) + throw new Error(errorMsg("property/index", up)); + return dataPathArr[dataLevel - up]; + } + if (up > dataLevel) + throw new Error(errorMsg("data", up)); + data = dataNames[dataLevel - up]; + if (!jsonPointer) + return data; + } + let expr = data; + const segments = jsonPointer.split("/"); + for (const segment of segments) { + if (segment) { + data = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)((0, util_1.unescapeJsonPointer)(segment))}`; + expr = (0, codegen_1._) `${expr} && ${data}`; + } + } + return expr; + function errorMsg(pointerType, up) { + return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`; + } + } + validate.getData = getData; + + return validate; +} + +var validation_error = {}; + +var hasRequiredValidation_error; + +function requireValidation_error () { + if (hasRequiredValidation_error) return validation_error; + hasRequiredValidation_error = 1; + Object.defineProperty(validation_error, "__esModule", { value: true }); + class ValidationError extends Error { + constructor(errors) { + super("validation failed"); + this.errors = errors; + this.ajv = this.validation = true; + } + } + validation_error.default = ValidationError; + + return validation_error; +} + +var ref_error = {}; + +var hasRequiredRef_error; + +function requireRef_error () { + if (hasRequiredRef_error) return ref_error; + hasRequiredRef_error = 1; + Object.defineProperty(ref_error, "__esModule", { value: true }); + const resolve_1 = resolve$2; + class MissingRefError extends Error { + constructor(resolver, baseId, ref, msg) { + super(msg || `can't resolve reference ${ref} from id ${baseId}`); + this.missingRef = (0, resolve_1.resolveUrl)(resolver, baseId, ref); + this.missingSchema = (0, resolve_1.normalizeId)((0, resolve_1.getFullPath)(resolver, this.missingRef)); + } + } + ref_error.default = MissingRefError; + + return ref_error; +} + +var compile = {}; + +Object.defineProperty(compile, "__esModule", { value: true }); +compile.resolveSchema = compile.getCompilingSchema = compile.resolveRef = compile.compileSchema = compile.SchemaEnv = void 0; +const codegen_1$r = requireCodegen(); +const validation_error_1 = requireValidation_error(); +const names_1$5 = requireNames(); +const resolve_1 = resolve$2; +const util_1$o = util$6; +const validate_1$1 = requireValidate(); +class SchemaEnv { + constructor(env) { + var _a; + this.refs = {}; + this.dynamicAnchors = {}; + let schema; + if (typeof env.schema == "object") + schema = env.schema; + this.schema = env.schema; + this.schemaId = env.schemaId; + this.root = env.root || this; + this.baseId = (_a = env.baseId) !== null && _a !== void 0 ? _a : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env.schemaId || "$id"]); + this.schemaPath = env.schemaPath; + this.localRefs = env.localRefs; + this.meta = env.meta; + this.$async = schema === null || schema === void 0 ? void 0 : schema.$async; + this.refs = {}; + } +} +compile.SchemaEnv = SchemaEnv; +// let codeSize = 0 +// let nodeCount = 0 +// Compiles schema in SchemaEnv +function compileSchema(sch) { + // TODO refactor - remove compilations + const _sch = getCompilingSchema.call(this, sch); + if (_sch) + return _sch; + const rootId = (0, resolve_1.getFullPath)(this.opts.uriResolver, sch.root.baseId); // TODO if getFullPath removed 1 tests fails + const { es5, lines } = this.opts.code; + const { ownProperties } = this.opts; + const gen = new codegen_1$r.CodeGen(this.scope, { es5, lines, ownProperties }); + let _ValidationError; + if (sch.$async) { + _ValidationError = gen.scopeValue("Error", { + ref: validation_error_1.default, + code: (0, codegen_1$r._) `require("ajv/dist/runtime/validation_error").default`, + }); + } + const validateName = gen.scopeName("validate"); + sch.validateName = validateName; + const schemaCxt = { + gen, + allErrors: this.opts.allErrors, + data: names_1$5.default.data, + parentData: names_1$5.default.parentData, + parentDataProperty: names_1$5.default.parentDataProperty, + dataNames: [names_1$5.default.data], + dataPathArr: [codegen_1$r.nil], + dataLevel: 0, + dataTypes: [], + definedProperties: new Set(), + topSchemaRef: gen.scopeValue("schema", this.opts.code.source === true + ? { ref: sch.schema, code: (0, codegen_1$r.stringify)(sch.schema) } + : { ref: sch.schema }), + validateName, + ValidationError: _ValidationError, + schema: sch.schema, + schemaEnv: sch, + rootId, + baseId: sch.baseId || rootId, + schemaPath: codegen_1$r.nil, + errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"), + errorPath: (0, codegen_1$r._) `""`, + opts: this.opts, + self: this, + }; + let sourceCode; + try { + this._compilations.add(sch); + (0, validate_1$1.validateFunctionCode)(schemaCxt); + gen.optimize(this.opts.code.optimize); + // gen.optimize(1) + const validateCode = gen.toString(); + sourceCode = `${gen.scopeRefs(names_1$5.default.scope)}return ${validateCode}`; + // console.log((codeSize += sourceCode.length), (nodeCount += gen.nodeCount)) + if (this.opts.code.process) + sourceCode = this.opts.code.process(sourceCode, sch); + // console.log("\n\n\n *** \n", sourceCode) + const makeValidate = new Function(`${names_1$5.default.self}`, `${names_1$5.default.scope}`, sourceCode); + const validate = makeValidate(this, this.scope.get()); + this.scope.value(validateName, { ref: validate }); + validate.errors = null; + validate.schema = sch.schema; + validate.schemaEnv = sch; + if (sch.$async) + validate.$async = true; + if (this.opts.code.source === true) { + validate.source = { validateName, validateCode, scopeValues: gen._values }; + } + if (this.opts.unevaluated) { + const { props, items } = schemaCxt; + validate.evaluated = { + props: props instanceof codegen_1$r.Name ? undefined : props, + items: items instanceof codegen_1$r.Name ? undefined : items, + dynamicProps: props instanceof codegen_1$r.Name, + dynamicItems: items instanceof codegen_1$r.Name, + }; + if (validate.source) + validate.source.evaluated = (0, codegen_1$r.stringify)(validate.evaluated); + } + sch.validate = validate; + return sch; + } + catch (e) { + delete sch.validate; + delete sch.validateName; + if (sourceCode) + this.logger.error("Error compiling schema, function code:", sourceCode); + // console.log("\n\n\n *** \n", sourceCode, this.opts) + throw e; + } + finally { + this._compilations.delete(sch); + } +} +compile.compileSchema = compileSchema; +function resolveRef(root, baseId, ref) { + var _a; + ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref); + const schOrFunc = root.refs[ref]; + if (schOrFunc) + return schOrFunc; + let _sch = resolve$1.call(this, root, ref); + if (_sch === undefined) { + const schema = (_a = root.localRefs) === null || _a === void 0 ? void 0 : _a[ref]; // TODO maybe localRefs should hold SchemaEnv + const { schemaId } = this.opts; + if (schema) + _sch = new SchemaEnv({ schema, schemaId, root, baseId }); + } + if (_sch === undefined) + return; + return (root.refs[ref] = inlineOrCompile.call(this, _sch)); +} +compile.resolveRef = resolveRef; +function inlineOrCompile(sch) { + if ((0, resolve_1.inlineRef)(sch.schema, this.opts.inlineRefs)) + return sch.schema; + return sch.validate ? sch : compileSchema.call(this, sch); +} +// Index of schema compilation in the currently compiled list +function getCompilingSchema(schEnv) { + for (const sch of this._compilations) { + if (sameSchemaEnv(sch, schEnv)) + return sch; + } +} +compile.getCompilingSchema = getCompilingSchema; +function sameSchemaEnv(s1, s2) { + return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId; +} +// resolve and compile the references ($ref) +// TODO returns AnySchemaObject (if the schema can be inlined) or validation function +function resolve$1(root, // information about the root schema for the current schema +ref // reference to resolve +) { + let sch; + while (typeof (sch = this.refs[ref]) == "string") + ref = sch; + return sch || this.schemas[ref] || resolveSchema.call(this, root, ref); +} +// Resolve schema, its root and baseId +function resolveSchema(root, // root object with properties schema, refs TODO below SchemaEnv is assigned to it +ref // reference to resolve +) { + const p = this.opts.uriResolver.parse(ref); + const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p); + let baseId = (0, resolve_1.getFullPath)(this.opts.uriResolver, root.baseId, undefined); + // TODO `Object.keys(root.schema).length > 0` should not be needed - but removing breaks 2 tests + if (Object.keys(root.schema).length > 0 && refPath === baseId) { + return getJsonPointer.call(this, p, root); + } + const id = (0, resolve_1.normalizeId)(refPath); + const schOrRef = this.refs[id] || this.schemas[id]; + if (typeof schOrRef == "string") { + const sch = resolveSchema.call(this, root, schOrRef); + if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== "object") + return; + return getJsonPointer.call(this, p, sch); + } + if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== "object") + return; + if (!schOrRef.validate) + compileSchema.call(this, schOrRef); + if (id === (0, resolve_1.normalizeId)(ref)) { + const { schema } = schOrRef; + const { schemaId } = this.opts; + const schId = schema[schemaId]; + if (schId) + baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); + return new SchemaEnv({ schema, schemaId, root, baseId }); + } + return getJsonPointer.call(this, p, schOrRef); +} +compile.resolveSchema = resolveSchema; +const PREVENT_SCOPE_CHANGE = new Set([ + "properties", + "patternProperties", + "enum", + "dependencies", + "definitions", +]); +function getJsonPointer(parsedRef, { baseId, schema, root }) { + var _a; + if (((_a = parsedRef.fragment) === null || _a === void 0 ? void 0 : _a[0]) !== "/") + return; + for (const part of parsedRef.fragment.slice(1).split("/")) { + if (typeof schema === "boolean") + return; + const partSchema = schema[(0, util_1$o.unescapeFragment)(part)]; + if (partSchema === undefined) + return; + schema = partSchema; + // TODO PREVENT_SCOPE_CHANGE could be defined in keyword def? + const schId = typeof schema === "object" && schema[this.opts.schemaId]; + if (!PREVENT_SCOPE_CHANGE.has(part) && schId) { + baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); + } + } + let env; + if (typeof schema != "boolean" && schema.$ref && !(0, util_1$o.schemaHasRulesButRef)(schema, this.RULES)) { + const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref); + env = resolveSchema.call(this, root, $ref); + } + // even though resolution failed we need to return SchemaEnv to throw exception + // so that compileAsync loads missing schema. + const { schemaId } = this.opts; + env = env || new SchemaEnv({ schema, schemaId, root, baseId }); + if (env.schema !== env.root.schema) + return env; + return undefined; +} + +var $id$8 = "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"; +var description$2 = "Meta-schema for $data reference (JSON AnySchema extension proposal)"; +var type$9 = "object"; +var required$2 = [ + "$data" +]; +var properties$b = { + $data: { + type: "string", + anyOf: [ + { + format: "relative-json-pointer" + }, + { + format: "json-pointer" + } + ] + } +}; +var additionalProperties$2 = false; +var require$$9 = { + $id: $id$8, + description: description$2, + type: type$9, + required: required$2, + properties: properties$b, + additionalProperties: additionalProperties$2 +}; + +var uri$1 = {}; + +var uri_all = {exports: {}}; + +/** @license URI.js v4.4.1 (c) 2011 Gary Court. License: http://github.com/garycourt/uri-js */ + +(function (module, exports) { + (function (global, factory) { + factory(exports) ; + }(commonjsGlobal, (function (exports) { + function merge() { + for (var _len = arguments.length, sets = Array(_len), _key = 0; _key < _len; _key++) { + sets[_key] = arguments[_key]; + } + + if (sets.length > 1) { + sets[0] = sets[0].slice(0, -1); + var xl = sets.length - 1; + for (var x = 1; x < xl; ++x) { + sets[x] = sets[x].slice(1, -1); + } + sets[xl] = sets[xl].slice(1); + return sets.join(''); + } else { + return sets[0]; + } + } + function subexp(str) { + return "(?:" + str + ")"; + } + function typeOf(o) { + return o === undefined ? "undefined" : o === null ? "null" : Object.prototype.toString.call(o).split(" ").pop().split("]").shift().toLowerCase(); + } + function toUpperCase(str) { + return str.toUpperCase(); + } + function toArray(obj) { + return obj !== undefined && obj !== null ? obj instanceof Array ? obj : typeof obj.length !== "number" || obj.split || obj.setInterval || obj.call ? [obj] : Array.prototype.slice.call(obj) : []; + } + function assign(target, source) { + var obj = target; + if (source) { + for (var key in source) { + obj[key] = source[key]; + } + } + return obj; + } + + function buildExps(isIRI) { + var ALPHA$$ = "[A-Za-z]", + DIGIT$$ = "[0-9]", + HEXDIG$$ = merge(DIGIT$$, "[A-Fa-f]"), + PCT_ENCODED$ = subexp(subexp("%[EFef]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%[89A-Fa-f]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%" + HEXDIG$$ + HEXDIG$$)), + //expanded + GEN_DELIMS$$ = "[\\:\\/\\?\\#\\[\\]\\@]", + SUB_DELIMS$$ = "[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]", + RESERVED$$ = merge(GEN_DELIMS$$, SUB_DELIMS$$), + UCSCHAR$$ = isIRI ? "[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]" : "[]", + //subset, excludes bidi control characters + IPRIVATE$$ = isIRI ? "[\\uE000-\\uF8FF]" : "[]", + //subset + UNRESERVED$$ = merge(ALPHA$$, DIGIT$$, "[\\-\\.\\_\\~]", UCSCHAR$$); + subexp(ALPHA$$ + merge(ALPHA$$, DIGIT$$, "[\\+\\-\\.]") + "*"); + subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:]")) + "*"); + var DEC_OCTET_RELAXED$ = subexp(subexp("25[0-5]") + "|" + subexp("2[0-4]" + DIGIT$$) + "|" + subexp("1" + DIGIT$$ + DIGIT$$) + "|" + subexp("0?[1-9]" + DIGIT$$) + "|0?0?" + DIGIT$$), + //relaxed parsing rules + IPV4ADDRESS$ = subexp(DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$), + H16$ = subexp(HEXDIG$$ + "{1,4}"), + LS32$ = subexp(subexp(H16$ + "\\:" + H16$) + "|" + IPV4ADDRESS$), + IPV6ADDRESS1$ = subexp(subexp(H16$ + "\\:") + "{6}" + LS32$), + // 6( h16 ":" ) ls32 + IPV6ADDRESS2$ = subexp("\\:\\:" + subexp(H16$ + "\\:") + "{5}" + LS32$), + // "::" 5( h16 ":" ) ls32 + IPV6ADDRESS3$ = subexp(subexp(H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{4}" + LS32$), + //[ h16 ] "::" 4( h16 ":" ) ls32 + IPV6ADDRESS4$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,1}" + H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{3}" + LS32$), + //[ *1( h16 ":" ) h16 ] "::" 3( h16 ":" ) ls32 + IPV6ADDRESS5$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,2}" + H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{2}" + LS32$), + //[ *2( h16 ":" ) h16 ] "::" 2( h16 ":" ) ls32 + IPV6ADDRESS6$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,3}" + H16$) + "?\\:\\:" + H16$ + "\\:" + LS32$), + //[ *3( h16 ":" ) h16 ] "::" h16 ":" ls32 + IPV6ADDRESS7$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,4}" + H16$) + "?\\:\\:" + LS32$), + //[ *4( h16 ":" ) h16 ] "::" ls32 + IPV6ADDRESS8$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,5}" + H16$) + "?\\:\\:" + H16$), + //[ *5( h16 ":" ) h16 ] "::" h16 + IPV6ADDRESS9$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,6}" + H16$) + "?\\:\\:"), + //[ *6( h16 ":" ) h16 ] "::" + IPV6ADDRESS$ = subexp([IPV6ADDRESS1$, IPV6ADDRESS2$, IPV6ADDRESS3$, IPV6ADDRESS4$, IPV6ADDRESS5$, IPV6ADDRESS6$, IPV6ADDRESS7$, IPV6ADDRESS8$, IPV6ADDRESS9$].join("|")), + ZONEID$ = subexp(subexp(UNRESERVED$$ + "|" + PCT_ENCODED$) + "+"); + //RFC 6874, with relaxed parsing rules + subexp("[vV]" + HEXDIG$$ + "+\\." + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:]") + "+"); + //RFC 6874 + subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$)) + "*"); + var PCHAR$ = subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@]")); + subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\@]")) + "+"); + subexp(subexp(PCHAR$ + "|" + merge("[\\/\\?]", IPRIVATE$$)) + "*"); + return { + NOT_SCHEME: new RegExp(merge("[^]", ALPHA$$, DIGIT$$, "[\\+\\-\\.]"), "g"), + NOT_USERINFO: new RegExp(merge("[^\\%\\:]", UNRESERVED$$, SUB_DELIMS$$), "g"), + NOT_HOST: new RegExp(merge("[^\\%\\[\\]\\:]", UNRESERVED$$, SUB_DELIMS$$), "g"), + NOT_PATH: new RegExp(merge("[^\\%\\/\\:\\@]", UNRESERVED$$, SUB_DELIMS$$), "g"), + NOT_PATH_NOSCHEME: new RegExp(merge("[^\\%\\/\\@]", UNRESERVED$$, SUB_DELIMS$$), "g"), + NOT_QUERY: new RegExp(merge("[^\\%]", UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@\\/\\?]", IPRIVATE$$), "g"), + NOT_FRAGMENT: new RegExp(merge("[^\\%]", UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@\\/\\?]"), "g"), + ESCAPE: new RegExp(merge("[^]", UNRESERVED$$, SUB_DELIMS$$), "g"), + UNRESERVED: new RegExp(UNRESERVED$$, "g"), + OTHER_CHARS: new RegExp(merge("[^\\%]", UNRESERVED$$, RESERVED$$), "g"), + PCT_ENCODED: new RegExp(PCT_ENCODED$, "g"), + IPV4ADDRESS: new RegExp("^(" + IPV4ADDRESS$ + ")$"), + IPV6ADDRESS: new RegExp("^\\[?(" + IPV6ADDRESS$ + ")" + subexp(subexp("\\%25|\\%(?!" + HEXDIG$$ + "{2})") + "(" + ZONEID$ + ")") + "?\\]?$") //RFC 6874, with relaxed parsing rules + }; + } + var URI_PROTOCOL = buildExps(false); + + var IRI_PROTOCOL = buildExps(true); + + var slicedToArray = function () { + function sliceIterator(arr, i) { + 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"]) _i["return"](); + } finally { + if (_d) throw _e; + } + } + + return _arr; + } + + return function (arr, i) { + if (Array.isArray(arr)) { + return arr; + } else if (Symbol.iterator in Object(arr)) { + return sliceIterator(arr, i); + } else { + throw new TypeError("Invalid attempt to destructure non-iterable instance"); + } + }; + }(); + + + + + + + + + + + + + + var toConsumableArray = function (arr) { + if (Array.isArray(arr)) { + for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; + + return arr2; + } else { + return Array.from(arr); + } + }; + + /** Highest positive signed 32-bit float value */ + + var maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1 + + /** Bootstring parameters */ + var base = 36; + var tMin = 1; + var tMax = 26; + var skew = 38; + var damp = 700; + var initialBias = 72; + var initialN = 128; // 0x80 + var delimiter = '-'; // '\x2D' + + /** Regular expressions */ + var regexPunycode = /^xn--/; + var regexNonASCII = /[^\0-\x7E]/; // non-ASCII chars + var regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators + + /** Error messages */ + var errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' + }; + + /** Convenience shortcuts */ + var baseMinusTMin = base - tMin; + var floor = Math.floor; + var stringFromCharCode = String.fromCharCode; + + /*--------------------------------------------------------------------------*/ + + /** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ + function error$1(type) { + throw new RangeError(errors[type]); + } + + /** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ + function map(array, fn) { + var result = []; + var length = array.length; + while (length--) { + result[length] = fn(array[length]); + } + return result; + } + + /** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ + function mapDomain(string, fn) { + var parts = string.split('@'); + var result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + var labels = string.split('.'); + var encoded = map(labels, fn).join('.'); + return result + encoded; + } + + /** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see <https://mathiasbynens.be/notes/javascript-encoding> + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ + function ucs2decode(string) { + var output = []; + var counter = 0; + var length = string.length; + while (counter < length) { + var value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // It's a high surrogate, and there is a next character. + var extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { + // Low surrogate. + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // It's an unmatched surrogate; only append this code unit, in case the + // next code unit is the high surrogate of a surrogate pair. + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; + } + + /** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ + var ucs2encode = function ucs2encode(array) { + return String.fromCodePoint.apply(String, toConsumableArray(array)); + }; + + /** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ + var basicToDigit = function basicToDigit(codePoint) { + if (codePoint - 0x30 < 0x0A) { + return codePoint - 0x16; + } + if (codePoint - 0x41 < 0x1A) { + return codePoint - 0x41; + } + if (codePoint - 0x61 < 0x1A) { + return codePoint - 0x61; + } + return base; + }; + + /** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ + var digitToBasic = function digitToBasic(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); + }; + + /** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ + var adapt = function adapt(delta, numPoints, firstTime) { + var k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (; /* no initialization */delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); + }; + + /** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ + var decode = function decode(input) { + // Don't use UCS-2. + var output = []; + var inputLength = input.length; + var i = 0; + var n = initialN; + var bias = initialBias; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + var basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (var j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error$1('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (var index = basic > 0 ? basic + 1 : 0; index < inputLength;) /* no final expression */{ + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + var oldi = i; + for (var w = 1, k = base;; /* no condition */k += base) { + + if (index >= inputLength) { + error$1('invalid-input'); + } + + var digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base || digit > floor((maxInt - i) / w)) { + error$1('overflow'); + } + + i += digit * w; + var t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias; + + if (digit < t) { + break; + } + + var baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error$1('overflow'); + } + + w *= baseMinusT; + } + + var out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error$1('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output. + output.splice(i++, 0, n); + } + + return String.fromCodePoint.apply(String, output); + }; + + /** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ + var encode = function encode(input) { + var output = []; + + // Convert the input in UCS-2 to an array of Unicode code points. + input = ucs2decode(input); + + // Cache the length. + var inputLength = input.length; + + // Initialize the state. + var n = initialN; + var delta = 0; + var bias = initialBias; + + // Handle the basic code points. + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = input[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var _currentValue2 = _step.value; + + if (_currentValue2 < 0x80) { + output.push(stringFromCharCode(_currentValue2)); + } + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + var basicLength = output.length; + var handledCPCount = basicLength; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string with a delimiter unless it's empty. + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + var m = maxInt; + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + + try { + for (var _iterator2 = input[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var currentValue = _step2.value; + + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>, + // but guard against overflow. + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + + var handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error$1('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; + + try { + for (var _iterator3 = input[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var _currentValue = _step3.value; + + if (_currentValue < n && ++delta > maxInt) { + error$1('overflow'); + } + if (_currentValue == n) { + // Represent delta as a generalized variable-length integer. + var q = delta; + for (var k = base;; /* no condition */k += base) { + var t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias; + if (q < t) { + break; + } + var qMinusT = q - t; + var baseMinusT = base - t; + output.push(stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + } catch (err) { + _didIteratorError3 = true; + _iteratorError3 = err; + } finally { + try { + if (!_iteratorNormalCompletion3 && _iterator3.return) { + _iterator3.return(); + } + } finally { + if (_didIteratorError3) { + throw _iteratorError3; + } + } + } + + ++delta; + ++n; + } + return output.join(''); + }; + + /** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ + var toUnicode = function toUnicode(input) { + return mapDomain(input, function (string) { + return regexPunycode.test(string) ? decode(string.slice(4).toLowerCase()) : string; + }); + }; + + /** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ + var toASCII = function toASCII(input) { + return mapDomain(input, function (string) { + return regexNonASCII.test(string) ? 'xn--' + encode(string) : string; + }); + }; + + /*--------------------------------------------------------------------------*/ + + /** Define the public API */ + var punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '2.1.0', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see <https://mathiasbynens.be/notes/javascript-encoding> + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode + }; + + /** + * URI.js + * + * @fileoverview An RFC 3986 compliant, scheme extendable URI parsing/validating/resolving library for JavaScript. + * @author <a href="mailto:gary.court@gmail.com">Gary Court</a> + * @see http://github.com/garycourt/uri-js + */ + /** + * Copyright 2011 Gary Court. 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. + * + * THIS SOFTWARE IS PROVIDED BY GARY COURT ``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 GARY COURT 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of Gary Court. + */ + var SCHEMES = {}; + function pctEncChar(chr) { + var c = chr.charCodeAt(0); + var e = void 0; + if (c < 16) e = "%0" + c.toString(16).toUpperCase();else if (c < 128) e = "%" + c.toString(16).toUpperCase();else if (c < 2048) e = "%" + (c >> 6 | 192).toString(16).toUpperCase() + "%" + (c & 63 | 128).toString(16).toUpperCase();else e = "%" + (c >> 12 | 224).toString(16).toUpperCase() + "%" + (c >> 6 & 63 | 128).toString(16).toUpperCase() + "%" + (c & 63 | 128).toString(16).toUpperCase(); + return e; + } + function pctDecChars(str) { + var newStr = ""; + var i = 0; + var il = str.length; + while (i < il) { + var c = parseInt(str.substr(i + 1, 2), 16); + if (c < 128) { + newStr += String.fromCharCode(c); + i += 3; + } else if (c >= 194 && c < 224) { + if (il - i >= 6) { + var c2 = parseInt(str.substr(i + 4, 2), 16); + newStr += String.fromCharCode((c & 31) << 6 | c2 & 63); + } else { + newStr += str.substr(i, 6); + } + i += 6; + } else if (c >= 224) { + if (il - i >= 9) { + var _c = parseInt(str.substr(i + 4, 2), 16); + var c3 = parseInt(str.substr(i + 7, 2), 16); + newStr += String.fromCharCode((c & 15) << 12 | (_c & 63) << 6 | c3 & 63); + } else { + newStr += str.substr(i, 9); + } + i += 9; + } else { + newStr += str.substr(i, 3); + i += 3; + } + } + return newStr; + } + function _normalizeComponentEncoding(components, protocol) { + function decodeUnreserved(str) { + var decStr = pctDecChars(str); + return !decStr.match(protocol.UNRESERVED) ? str : decStr; + } + if (components.scheme) components.scheme = String(components.scheme).replace(protocol.PCT_ENCODED, decodeUnreserved).toLowerCase().replace(protocol.NOT_SCHEME, ""); + if (components.userinfo !== undefined) components.userinfo = String(components.userinfo).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_USERINFO, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); + if (components.host !== undefined) components.host = String(components.host).replace(protocol.PCT_ENCODED, decodeUnreserved).toLowerCase().replace(protocol.NOT_HOST, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); + if (components.path !== undefined) components.path = String(components.path).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(components.scheme ? protocol.NOT_PATH : protocol.NOT_PATH_NOSCHEME, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); + if (components.query !== undefined) components.query = String(components.query).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_QUERY, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); + if (components.fragment !== undefined) components.fragment = String(components.fragment).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_FRAGMENT, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); + return components; + } + + function _stripLeadingZeros(str) { + return str.replace(/^0*(.*)/, "$1") || "0"; + } + function _normalizeIPv4(host, protocol) { + var matches = host.match(protocol.IPV4ADDRESS) || []; + + var _matches = slicedToArray(matches, 2), + address = _matches[1]; + + if (address) { + return address.split(".").map(_stripLeadingZeros).join("."); + } else { + return host; + } + } + function _normalizeIPv6(host, protocol) { + var matches = host.match(protocol.IPV6ADDRESS) || []; + + var _matches2 = slicedToArray(matches, 3), + address = _matches2[1], + zone = _matches2[2]; + + if (address) { + var _address$toLowerCase$ = address.toLowerCase().split('::').reverse(), + _address$toLowerCase$2 = slicedToArray(_address$toLowerCase$, 2), + last = _address$toLowerCase$2[0], + first = _address$toLowerCase$2[1]; + + var firstFields = first ? first.split(":").map(_stripLeadingZeros) : []; + var lastFields = last.split(":").map(_stripLeadingZeros); + var isLastFieldIPv4Address = protocol.IPV4ADDRESS.test(lastFields[lastFields.length - 1]); + var fieldCount = isLastFieldIPv4Address ? 7 : 8; + var lastFieldsStart = lastFields.length - fieldCount; + var fields = Array(fieldCount); + for (var x = 0; x < fieldCount; ++x) { + fields[x] = firstFields[x] || lastFields[lastFieldsStart + x] || ''; + } + if (isLastFieldIPv4Address) { + fields[fieldCount - 1] = _normalizeIPv4(fields[fieldCount - 1], protocol); + } + var allZeroFields = fields.reduce(function (acc, field, index) { + if (!field || field === "0") { + var lastLongest = acc[acc.length - 1]; + if (lastLongest && lastLongest.index + lastLongest.length === index) { + lastLongest.length++; + } else { + acc.push({ index: index, length: 1 }); + } + } + return acc; + }, []); + var longestZeroFields = allZeroFields.sort(function (a, b) { + return b.length - a.length; + })[0]; + var newHost = void 0; + if (longestZeroFields && longestZeroFields.length > 1) { + var newFirst = fields.slice(0, longestZeroFields.index); + var newLast = fields.slice(longestZeroFields.index + longestZeroFields.length); + newHost = newFirst.join(":") + "::" + newLast.join(":"); + } else { + newHost = fields.join(":"); + } + if (zone) { + newHost += "%" + zone; + } + return newHost; + } else { + return host; + } + } + var URI_PARSE = /^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i; + var NO_MATCH_IS_UNDEFINED = "".match(/(){0}/)[1] === undefined; + function parse(uriString) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + var components = {}; + var protocol = options.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL; + if (options.reference === "suffix") uriString = (options.scheme ? options.scheme + ":" : "") + "//" + uriString; + var matches = uriString.match(URI_PARSE); + if (matches) { + if (NO_MATCH_IS_UNDEFINED) { + //store each component + components.scheme = matches[1]; + components.userinfo = matches[3]; + components.host = matches[4]; + components.port = parseInt(matches[5], 10); + components.path = matches[6] || ""; + components.query = matches[7]; + components.fragment = matches[8]; + //fix port number + if (isNaN(components.port)) { + components.port = matches[5]; + } + } else { + //IE FIX for improper RegExp matching + //store each component + components.scheme = matches[1] || undefined; + components.userinfo = uriString.indexOf("@") !== -1 ? matches[3] : undefined; + components.host = uriString.indexOf("//") !== -1 ? matches[4] : undefined; + components.port = parseInt(matches[5], 10); + components.path = matches[6] || ""; + components.query = uriString.indexOf("?") !== -1 ? matches[7] : undefined; + components.fragment = uriString.indexOf("#") !== -1 ? matches[8] : undefined; + //fix port number + if (isNaN(components.port)) { + components.port = uriString.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/) ? matches[4] : undefined; + } + } + if (components.host) { + //normalize IP hosts + components.host = _normalizeIPv6(_normalizeIPv4(components.host, protocol), protocol); + } + //determine reference type + if (components.scheme === undefined && components.userinfo === undefined && components.host === undefined && components.port === undefined && !components.path && components.query === undefined) { + components.reference = "same-document"; + } else if (components.scheme === undefined) { + components.reference = "relative"; + } else if (components.fragment === undefined) { + components.reference = "absolute"; + } else { + components.reference = "uri"; + } + //check for reference errors + if (options.reference && options.reference !== "suffix" && options.reference !== components.reference) { + components.error = components.error || "URI is not a " + options.reference + " reference."; + } + //find scheme handler + var schemeHandler = SCHEMES[(options.scheme || components.scheme || "").toLowerCase()]; + //check if scheme can't handle IRIs + if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) { + //if host component is a domain name + if (components.host && (options.domainHost || schemeHandler && schemeHandler.domainHost)) { + //convert Unicode IDN -> ASCII IDN + try { + components.host = punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase()); + } catch (e) { + components.error = components.error || "Host's domain name can not be converted to ASCII via punycode: " + e; + } + } + //convert IRI -> URI + _normalizeComponentEncoding(components, URI_PROTOCOL); + } else { + //normalize encodings + _normalizeComponentEncoding(components, protocol); + } + //perform scheme specific parsing + if (schemeHandler && schemeHandler.parse) { + schemeHandler.parse(components, options); + } + } else { + components.error = components.error || "URI can not be parsed."; + } + return components; + } + + function _recomposeAuthority(components, options) { + var protocol = options.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL; + var uriTokens = []; + if (components.userinfo !== undefined) { + uriTokens.push(components.userinfo); + uriTokens.push("@"); + } + if (components.host !== undefined) { + //normalize IP hosts, add brackets and escape zone separator for IPv6 + uriTokens.push(_normalizeIPv6(_normalizeIPv4(String(components.host), protocol), protocol).replace(protocol.IPV6ADDRESS, function (_, $1, $2) { + return "[" + $1 + ($2 ? "%25" + $2 : "") + "]"; + })); + } + if (typeof components.port === "number" || typeof components.port === "string") { + uriTokens.push(":"); + uriTokens.push(String(components.port)); + } + return uriTokens.length ? uriTokens.join("") : undefined; + } + + var RDS1 = /^\.\.?\//; + var RDS2 = /^\/\.(\/|$)/; + var RDS3 = /^\/\.\.(\/|$)/; + var RDS5 = /^\/?(?:.|\n)*?(?=\/|$)/; + function removeDotSegments(input) { + var output = []; + while (input.length) { + if (input.match(RDS1)) { + input = input.replace(RDS1, ""); + } else if (input.match(RDS2)) { + input = input.replace(RDS2, "/"); + } else if (input.match(RDS3)) { + input = input.replace(RDS3, "/"); + output.pop(); + } else if (input === "." || input === "..") { + input = ""; + } else { + var im = input.match(RDS5); + if (im) { + var s = im[0]; + input = input.slice(s.length); + output.push(s); + } else { + throw new Error("Unexpected dot segment condition"); + } + } + } + return output.join(""); + } + + function serialize(components) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + var protocol = options.iri ? IRI_PROTOCOL : URI_PROTOCOL; + var uriTokens = []; + //find scheme handler + var schemeHandler = SCHEMES[(options.scheme || components.scheme || "").toLowerCase()]; + //perform scheme specific serialization + if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(components, options); + if (components.host) { + //if host component is an IPv6 address + if (protocol.IPV6ADDRESS.test(components.host)) ; + //TODO: normalize IPv6 address as per RFC 5952 + + //if host component is a domain name + else if (options.domainHost || schemeHandler && schemeHandler.domainHost) { + //convert IDN via punycode + try { + components.host = !options.iri ? punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase()) : punycode.toUnicode(components.host); + } catch (e) { + components.error = components.error || "Host's domain name can not be converted to " + (!options.iri ? "ASCII" : "Unicode") + " via punycode: " + e; + } + } + } + //normalize encoding + _normalizeComponentEncoding(components, protocol); + if (options.reference !== "suffix" && components.scheme) { + uriTokens.push(components.scheme); + uriTokens.push(":"); + } + var authority = _recomposeAuthority(components, options); + if (authority !== undefined) { + if (options.reference !== "suffix") { + uriTokens.push("//"); + } + uriTokens.push(authority); + if (components.path && components.path.charAt(0) !== "/") { + uriTokens.push("/"); + } + } + if (components.path !== undefined) { + var s = components.path; + if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) { + s = removeDotSegments(s); + } + if (authority === undefined) { + s = s.replace(/^\/\//, "/%2F"); //don't allow the path to start with "//" + } + uriTokens.push(s); + } + if (components.query !== undefined) { + uriTokens.push("?"); + uriTokens.push(components.query); + } + if (components.fragment !== undefined) { + uriTokens.push("#"); + uriTokens.push(components.fragment); + } + return uriTokens.join(""); //merge tokens into a string + } + + function resolveComponents(base, relative) { + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + var skipNormalization = arguments[3]; + + var target = {}; + if (!skipNormalization) { + base = parse(serialize(base, options), options); //normalize base components + relative = parse(serialize(relative, options), options); //normalize relative components + } + options = options || {}; + if (!options.tolerant && relative.scheme) { + target.scheme = relative.scheme; + //target.authority = relative.authority; + target.userinfo = relative.userinfo; + target.host = relative.host; + target.port = relative.port; + target.path = removeDotSegments(relative.path || ""); + target.query = relative.query; + } else { + if (relative.userinfo !== undefined || relative.host !== undefined || relative.port !== undefined) { + //target.authority = relative.authority; + target.userinfo = relative.userinfo; + target.host = relative.host; + target.port = relative.port; + target.path = removeDotSegments(relative.path || ""); + target.query = relative.query; + } else { + if (!relative.path) { + target.path = base.path; + if (relative.query !== undefined) { + target.query = relative.query; + } else { + target.query = base.query; + } + } else { + if (relative.path.charAt(0) === "/") { + target.path = removeDotSegments(relative.path); + } else { + if ((base.userinfo !== undefined || base.host !== undefined || base.port !== undefined) && !base.path) { + target.path = "/" + relative.path; + } else if (!base.path) { + target.path = relative.path; + } else { + target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative.path; + } + target.path = removeDotSegments(target.path); + } + target.query = relative.query; + } + //target.authority = base.authority; + target.userinfo = base.userinfo; + target.host = base.host; + target.port = base.port; + } + target.scheme = base.scheme; + } + target.fragment = relative.fragment; + return target; + } + + function resolve(baseURI, relativeURI, options) { + var schemelessOptions = assign({ scheme: 'null' }, options); + return serialize(resolveComponents(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true), schemelessOptions); + } + + function normalize(uri, options) { + if (typeof uri === "string") { + uri = serialize(parse(uri, options), options); + } else if (typeOf(uri) === "object") { + uri = parse(serialize(uri, options), options); + } + return uri; + } + + function equal(uriA, uriB, options) { + if (typeof uriA === "string") { + uriA = serialize(parse(uriA, options), options); + } else if (typeOf(uriA) === "object") { + uriA = serialize(uriA, options); + } + if (typeof uriB === "string") { + uriB = serialize(parse(uriB, options), options); + } else if (typeOf(uriB) === "object") { + uriB = serialize(uriB, options); + } + return uriA === uriB; + } + + function escapeComponent(str, options) { + return str && str.toString().replace(!options || !options.iri ? URI_PROTOCOL.ESCAPE : IRI_PROTOCOL.ESCAPE, pctEncChar); + } + + function unescapeComponent(str, options) { + return str && str.toString().replace(!options || !options.iri ? URI_PROTOCOL.PCT_ENCODED : IRI_PROTOCOL.PCT_ENCODED, pctDecChars); + } + + var handler = { + scheme: "http", + domainHost: true, + parse: function parse(components, options) { + //report missing host + if (!components.host) { + components.error = components.error || "HTTP URIs must have a host."; + } + return components; + }, + serialize: function serialize(components, options) { + var secure = String(components.scheme).toLowerCase() === "https"; + //normalize the default port + if (components.port === (secure ? 443 : 80) || components.port === "") { + components.port = undefined; + } + //normalize the empty path + if (!components.path) { + components.path = "/"; + } + //NOTE: We do not parse query strings for HTTP URIs + //as WWW Form Url Encoded query strings are part of the HTML4+ spec, + //and not the HTTP spec. + return components; + } + }; + + var handler$1 = { + scheme: "https", + domainHost: handler.domainHost, + parse: handler.parse, + serialize: handler.serialize + }; + + function isSecure(wsComponents) { + return typeof wsComponents.secure === 'boolean' ? wsComponents.secure : String(wsComponents.scheme).toLowerCase() === "wss"; + } + //RFC 6455 + var handler$2 = { + scheme: "ws", + domainHost: true, + parse: function parse(components, options) { + var wsComponents = components; + //indicate if the secure flag is set + wsComponents.secure = isSecure(wsComponents); + //construct resouce name + wsComponents.resourceName = (wsComponents.path || '/') + (wsComponents.query ? '?' + wsComponents.query : ''); + wsComponents.path = undefined; + wsComponents.query = undefined; + return wsComponents; + }, + serialize: function serialize(wsComponents, options) { + //normalize the default port + if (wsComponents.port === (isSecure(wsComponents) ? 443 : 80) || wsComponents.port === "") { + wsComponents.port = undefined; + } + //ensure scheme matches secure flag + if (typeof wsComponents.secure === 'boolean') { + wsComponents.scheme = wsComponents.secure ? 'wss' : 'ws'; + wsComponents.secure = undefined; + } + //reconstruct path from resource name + if (wsComponents.resourceName) { + var _wsComponents$resourc = wsComponents.resourceName.split('?'), + _wsComponents$resourc2 = slicedToArray(_wsComponents$resourc, 2), + path = _wsComponents$resourc2[0], + query = _wsComponents$resourc2[1]; + + wsComponents.path = path && path !== '/' ? path : undefined; + wsComponents.query = query; + wsComponents.resourceName = undefined; + } + //forbid fragment component + wsComponents.fragment = undefined; + return wsComponents; + } + }; + + var handler$3 = { + scheme: "wss", + domainHost: handler$2.domainHost, + parse: handler$2.parse, + serialize: handler$2.serialize + }; + + var O = {}; + //RFC 3986 + var UNRESERVED$$ = "[A-Za-z0-9\\-\\.\\_\\~" + ("\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF" ) + "]"; + var HEXDIG$$ = "[0-9A-Fa-f]"; //case-insensitive + var PCT_ENCODED$ = subexp(subexp("%[EFef]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%[89A-Fa-f]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%" + HEXDIG$$ + HEXDIG$$)); //expanded + //RFC 5322, except these symbols as per RFC 6068: @ : / ? # [ ] & ; = + //const ATEXT$$ = "[A-Za-z0-9\\!\\#\\$\\%\\&\\'\\*\\+\\-\\/\\=\\?\\^\\_\\`\\{\\|\\}\\~]"; + //const WSP$$ = "[\\x20\\x09]"; + //const OBS_QTEXT$$ = "[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x7F]"; //(%d1-8 / %d11-12 / %d14-31 / %d127) + //const QTEXT$$ = merge("[\\x21\\x23-\\x5B\\x5D-\\x7E]", OBS_QTEXT$$); //%d33 / %d35-91 / %d93-126 / obs-qtext + //const VCHAR$$ = "[\\x21-\\x7E]"; + //const WSP$$ = "[\\x20\\x09]"; + //const OBS_QP$ = subexp("\\\\" + merge("[\\x00\\x0D\\x0A]", OBS_QTEXT$$)); //%d0 / CR / LF / obs-qtext + //const FWS$ = subexp(subexp(WSP$$ + "*" + "\\x0D\\x0A") + "?" + WSP$$ + "+"); + //const QUOTED_PAIR$ = subexp(subexp("\\\\" + subexp(VCHAR$$ + "|" + WSP$$)) + "|" + OBS_QP$); + //const QUOTED_STRING$ = subexp('\\"' + subexp(FWS$ + "?" + QCONTENT$) + "*" + FWS$ + "?" + '\\"'); + var ATEXT$$ = "[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]"; + var QTEXT$$ = "[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]"; + var VCHAR$$ = merge(QTEXT$$, "[\\\"\\\\]"); + var SOME_DELIMS$$ = "[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]"; + var UNRESERVED = new RegExp(UNRESERVED$$, "g"); + var PCT_ENCODED = new RegExp(PCT_ENCODED$, "g"); + var NOT_LOCAL_PART = new RegExp(merge("[^]", ATEXT$$, "[\\.]", '[\\"]', VCHAR$$), "g"); + var NOT_HFNAME = new RegExp(merge("[^]", UNRESERVED$$, SOME_DELIMS$$), "g"); + var NOT_HFVALUE = NOT_HFNAME; + function decodeUnreserved(str) { + var decStr = pctDecChars(str); + return !decStr.match(UNRESERVED) ? str : decStr; + } + var handler$4 = { + scheme: "mailto", + parse: function parse$$1(components, options) { + var mailtoComponents = components; + var to = mailtoComponents.to = mailtoComponents.path ? mailtoComponents.path.split(",") : []; + mailtoComponents.path = undefined; + if (mailtoComponents.query) { + var unknownHeaders = false; + var headers = {}; + var hfields = mailtoComponents.query.split("&"); + for (var x = 0, xl = hfields.length; x < xl; ++x) { + var hfield = hfields[x].split("="); + switch (hfield[0]) { + case "to": + var toAddrs = hfield[1].split(","); + for (var _x = 0, _xl = toAddrs.length; _x < _xl; ++_x) { + to.push(toAddrs[_x]); + } + break; + case "subject": + mailtoComponents.subject = unescapeComponent(hfield[1], options); + break; + case "body": + mailtoComponents.body = unescapeComponent(hfield[1], options); + break; + default: + unknownHeaders = true; + headers[unescapeComponent(hfield[0], options)] = unescapeComponent(hfield[1], options); + break; + } + } + if (unknownHeaders) mailtoComponents.headers = headers; + } + mailtoComponents.query = undefined; + for (var _x2 = 0, _xl2 = to.length; _x2 < _xl2; ++_x2) { + var addr = to[_x2].split("@"); + addr[0] = unescapeComponent(addr[0]); + if (!options.unicodeSupport) { + //convert Unicode IDN -> ASCII IDN + try { + addr[1] = punycode.toASCII(unescapeComponent(addr[1], options).toLowerCase()); + } catch (e) { + mailtoComponents.error = mailtoComponents.error || "Email address's domain name can not be converted to ASCII via punycode: " + e; + } + } else { + addr[1] = unescapeComponent(addr[1], options).toLowerCase(); + } + to[_x2] = addr.join("@"); + } + return mailtoComponents; + }, + serialize: function serialize$$1(mailtoComponents, options) { + var components = mailtoComponents; + var to = toArray(mailtoComponents.to); + if (to) { + for (var x = 0, xl = to.length; x < xl; ++x) { + var toAddr = String(to[x]); + var atIdx = toAddr.lastIndexOf("@"); + var localPart = toAddr.slice(0, atIdx).replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_LOCAL_PART, pctEncChar); + var domain = toAddr.slice(atIdx + 1); + //convert IDN via punycode + try { + domain = !options.iri ? punycode.toASCII(unescapeComponent(domain, options).toLowerCase()) : punycode.toUnicode(domain); + } catch (e) { + components.error = components.error || "Email address's domain name can not be converted to " + (!options.iri ? "ASCII" : "Unicode") + " via punycode: " + e; + } + to[x] = localPart + "@" + domain; + } + components.path = to.join(","); + } + var headers = mailtoComponents.headers = mailtoComponents.headers || {}; + if (mailtoComponents.subject) headers["subject"] = mailtoComponents.subject; + if (mailtoComponents.body) headers["body"] = mailtoComponents.body; + var fields = []; + for (var name in headers) { + if (headers[name] !== O[name]) { + fields.push(name.replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFNAME, pctEncChar) + "=" + headers[name].replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFVALUE, pctEncChar)); + } + } + if (fields.length) { + components.query = fields.join("&"); + } + return components; + } + }; + + var URN_PARSE = /^([^\:]+)\:(.*)/; + //RFC 2141 + var handler$5 = { + scheme: "urn", + parse: function parse$$1(components, options) { + var matches = components.path && components.path.match(URN_PARSE); + var urnComponents = components; + if (matches) { + var scheme = options.scheme || urnComponents.scheme || "urn"; + var nid = matches[1].toLowerCase(); + var nss = matches[2]; + var urnScheme = scheme + ":" + (options.nid || nid); + var schemeHandler = SCHEMES[urnScheme]; + urnComponents.nid = nid; + urnComponents.nss = nss; + urnComponents.path = undefined; + if (schemeHandler) { + urnComponents = schemeHandler.parse(urnComponents, options); + } + } else { + urnComponents.error = urnComponents.error || "URN can not be parsed."; + } + return urnComponents; + }, + serialize: function serialize$$1(urnComponents, options) { + var scheme = options.scheme || urnComponents.scheme || "urn"; + var nid = urnComponents.nid; + var urnScheme = scheme + ":" + (options.nid || nid); + var schemeHandler = SCHEMES[urnScheme]; + if (schemeHandler) { + urnComponents = schemeHandler.serialize(urnComponents, options); + } + var uriComponents = urnComponents; + var nss = urnComponents.nss; + uriComponents.path = (nid || options.nid) + ":" + nss; + return uriComponents; + } + }; + + var UUID = /^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/; + //RFC 4122 + var handler$6 = { + scheme: "urn:uuid", + parse: function parse(urnComponents, options) { + var uuidComponents = urnComponents; + uuidComponents.uuid = uuidComponents.nss; + uuidComponents.nss = undefined; + if (!options.tolerant && (!uuidComponents.uuid || !uuidComponents.uuid.match(UUID))) { + uuidComponents.error = uuidComponents.error || "UUID is not valid."; + } + return uuidComponents; + }, + serialize: function serialize(uuidComponents, options) { + var urnComponents = uuidComponents; + //normalize UUID + urnComponents.nss = (uuidComponents.uuid || "").toLowerCase(); + return urnComponents; + } + }; + + SCHEMES[handler.scheme] = handler; + SCHEMES[handler$1.scheme] = handler$1; + SCHEMES[handler$2.scheme] = handler$2; + SCHEMES[handler$3.scheme] = handler$3; + SCHEMES[handler$4.scheme] = handler$4; + SCHEMES[handler$5.scheme] = handler$5; + SCHEMES[handler$6.scheme] = handler$6; + + exports.SCHEMES = SCHEMES; + exports.pctEncChar = pctEncChar; + exports.pctDecChars = pctDecChars; + exports.parse = parse; + exports.removeDotSegments = removeDotSegments; + exports.serialize = serialize; + exports.resolveComponents = resolveComponents; + exports.resolve = resolve; + exports.normalize = normalize; + exports.equal = equal; + exports.escapeComponent = escapeComponent; + exports.unescapeComponent = unescapeComponent; + + Object.defineProperty(exports, '__esModule', { value: true }); + + }))); + +} (uri_all, uri_all.exports)); + +var uri_allExports = uri_all.exports; + +Object.defineProperty(uri$1, "__esModule", { value: true }); +const uri = uri_allExports; +uri.code = 'require("ajv/dist/runtime/uri").default'; +uri$1.default = uri; + +(function (exports) { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0; + var validate_1 = requireValidate(); + Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function () { return validate_1.KeywordCxt; } }); + var codegen_1 = requireCodegen(); + Object.defineProperty(exports, "_", { enumerable: true, get: function () { return codegen_1._; } }); + Object.defineProperty(exports, "str", { enumerable: true, get: function () { return codegen_1.str; } }); + Object.defineProperty(exports, "stringify", { enumerable: true, get: function () { return codegen_1.stringify; } }); + Object.defineProperty(exports, "nil", { enumerable: true, get: function () { return codegen_1.nil; } }); + Object.defineProperty(exports, "Name", { enumerable: true, get: function () { return codegen_1.Name; } }); + Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function () { return codegen_1.CodeGen; } }); + const validation_error_1 = requireValidation_error(); + const ref_error_1 = requireRef_error(); + const rules_1 = rules; + const compile_1 = compile; + const codegen_2 = requireCodegen(); + const resolve_1 = resolve$2; + const dataType_1 = dataType; + const util_1 = util$6; + const $dataRefSchema = require$$9; + const uri_1 = uri$1; + const defaultRegExp = (str, flags) => new RegExp(str, flags); + defaultRegExp.code = "new RegExp"; + const META_IGNORE_OPTIONS = ["removeAdditional", "useDefaults", "coerceTypes"]; + const EXT_SCOPE_NAMES = new Set([ + "validate", + "serialize", + "parse", + "wrapper", + "root", + "schema", + "keyword", + "pattern", + "formats", + "validate$data", + "func", + "obj", + "Error", + ]); + const removedOptions = { + errorDataPath: "", + format: "`validateFormats: false` can be used instead.", + nullable: '"nullable" keyword is supported by default.', + jsonPointers: "Deprecated jsPropertySyntax can be used instead.", + extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.", + missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.", + processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`", + sourceCode: "Use option `code: {source: true}`", + strictDefaults: "It is default now, see option `strict`.", + strictKeywords: "It is default now, see option `strict`.", + uniqueItems: '"uniqueItems" keyword is always validated.', + unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).", + cache: "Map is used as cache, schema object as key.", + serialize: "Map is used as cache, schema object as key.", + ajvErrors: "It is default now.", + }; + const deprecatedOptions = { + ignoreKeywordsWithRef: "", + jsPropertySyntax: "", + unicode: '"minLength"/"maxLength" account for unicode characters by default.', + }; + const MAX_EXPRESSION = 200; + // eslint-disable-next-line complexity + function requiredOptions(o) { + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0; + const s = o.strict; + const _optz = (_a = o.code) === null || _a === void 0 ? void 0 : _a.optimize; + const optimize = _optz === true || _optz === undefined ? 1 : _optz || 0; + const regExp = (_c = (_b = o.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c !== void 0 ? _c : defaultRegExp; + const uriResolver = (_d = o.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default; + return { + strictSchema: (_f = (_e = o.strictSchema) !== null && _e !== void 0 ? _e : s) !== null && _f !== void 0 ? _f : true, + strictNumbers: (_h = (_g = o.strictNumbers) !== null && _g !== void 0 ? _g : s) !== null && _h !== void 0 ? _h : true, + strictTypes: (_k = (_j = o.strictTypes) !== null && _j !== void 0 ? _j : s) !== null && _k !== void 0 ? _k : "log", + strictTuples: (_m = (_l = o.strictTuples) !== null && _l !== void 0 ? _l : s) !== null && _m !== void 0 ? _m : "log", + strictRequired: (_p = (_o = o.strictRequired) !== null && _o !== void 0 ? _o : s) !== null && _p !== void 0 ? _p : false, + code: o.code ? { ...o.code, optimize, regExp } : { optimize, regExp }, + loopRequired: (_q = o.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION, + loopEnum: (_r = o.loopEnum) !== null && _r !== void 0 ? _r : MAX_EXPRESSION, + meta: (_s = o.meta) !== null && _s !== void 0 ? _s : true, + messages: (_t = o.messages) !== null && _t !== void 0 ? _t : true, + inlineRefs: (_u = o.inlineRefs) !== null && _u !== void 0 ? _u : true, + schemaId: (_v = o.schemaId) !== null && _v !== void 0 ? _v : "$id", + addUsedSchema: (_w = o.addUsedSchema) !== null && _w !== void 0 ? _w : true, + validateSchema: (_x = o.validateSchema) !== null && _x !== void 0 ? _x : true, + validateFormats: (_y = o.validateFormats) !== null && _y !== void 0 ? _y : true, + unicodeRegExp: (_z = o.unicodeRegExp) !== null && _z !== void 0 ? _z : true, + int32range: (_0 = o.int32range) !== null && _0 !== void 0 ? _0 : true, + uriResolver: uriResolver, + }; + } + class Ajv { + constructor(opts = {}) { + this.schemas = {}; + this.refs = {}; + this.formats = {}; + this._compilations = new Set(); + this._loading = {}; + this._cache = new Map(); + opts = this.opts = { ...opts, ...requiredOptions(opts) }; + const { es5, lines } = this.opts.code; + this.scope = new codegen_2.ValueScope({ scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines }); + this.logger = getLogger(opts.logger); + const formatOpt = opts.validateFormats; + opts.validateFormats = false; + this.RULES = (0, rules_1.getRules)(); + checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED"); + checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn"); + this._metaOpts = getMetaSchemaOptions.call(this); + if (opts.formats) + addInitialFormats.call(this); + this._addVocabularies(); + this._addDefaultMetaSchema(); + if (opts.keywords) + addInitialKeywords.call(this, opts.keywords); + if (typeof opts.meta == "object") + this.addMetaSchema(opts.meta); + addInitialSchemas.call(this); + opts.validateFormats = formatOpt; + } + _addVocabularies() { + this.addKeyword("$async"); + } + _addDefaultMetaSchema() { + const { $data, meta, schemaId } = this.opts; + let _dataRefSchema = $dataRefSchema; + if (schemaId === "id") { + _dataRefSchema = { ...$dataRefSchema }; + _dataRefSchema.id = _dataRefSchema.$id; + delete _dataRefSchema.$id; + } + if (meta && $data) + this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false); + } + defaultMeta() { + const { meta, schemaId } = this.opts; + return (this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : undefined); + } + validate(schemaKeyRef, // key, ref or schema object + data // to be validated + ) { + let v; + if (typeof schemaKeyRef == "string") { + v = this.getSchema(schemaKeyRef); + if (!v) + throw new Error(`no schema with key or ref "${schemaKeyRef}"`); + } + else { + v = this.compile(schemaKeyRef); + } + const valid = v(data); + if (!("$async" in v)) + this.errors = v.errors; + return valid; + } + compile(schema, _meta) { + const sch = this._addSchema(schema, _meta); + return (sch.validate || this._compileSchemaEnv(sch)); + } + compileAsync(schema, meta) { + if (typeof this.opts.loadSchema != "function") { + throw new Error("options.loadSchema should be a function"); + } + const { loadSchema } = this.opts; + return runCompileAsync.call(this, schema, meta); + async function runCompileAsync(_schema, _meta) { + await loadMetaSchema.call(this, _schema.$schema); + const sch = this._addSchema(_schema, _meta); + return sch.validate || _compileAsync.call(this, sch); + } + async function loadMetaSchema($ref) { + if ($ref && !this.getSchema($ref)) { + await runCompileAsync.call(this, { $ref }, true); + } + } + async function _compileAsync(sch) { + try { + return this._compileSchemaEnv(sch); + } + catch (e) { + if (!(e instanceof ref_error_1.default)) + throw e; + checkLoaded.call(this, e); + await loadMissingSchema.call(this, e.missingSchema); + return _compileAsync.call(this, sch); + } + } + function checkLoaded({ missingSchema: ref, missingRef }) { + if (this.refs[ref]) { + throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`); + } + } + async function loadMissingSchema(ref) { + const _schema = await _loadSchema.call(this, ref); + if (!this.refs[ref]) + await loadMetaSchema.call(this, _schema.$schema); + if (!this.refs[ref]) + this.addSchema(_schema, ref, meta); + } + async function _loadSchema(ref) { + const p = this._loading[ref]; + if (p) + return p; + try { + return await (this._loading[ref] = loadSchema(ref)); + } + finally { + delete this._loading[ref]; + } + } + } + // Adds schema to the instance + addSchema(schema, // If array is passed, `key` will be ignored + key, // Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`. + _meta, // true if schema is a meta-schema. Used internally, addMetaSchema should be used instead. + _validateSchema = this.opts.validateSchema // false to skip schema validation. Used internally, option validateSchema should be used instead. + ) { + if (Array.isArray(schema)) { + for (const sch of schema) + this.addSchema(sch, undefined, _meta, _validateSchema); + return this; + } + let id; + if (typeof schema === "object") { + const { schemaId } = this.opts; + id = schema[schemaId]; + if (id !== undefined && typeof id != "string") { + throw new Error(`schema ${schemaId} must be string`); + } + } + key = (0, resolve_1.normalizeId)(key || id); + this._checkUnique(key); + this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true); + return this; + } + // Add schema that will be used to validate other schemas + // options in META_IGNORE_OPTIONS are alway set to false + addMetaSchema(schema, key, // schema key + _validateSchema = this.opts.validateSchema // false to skip schema validation, can be used to override validateSchema option for meta-schema + ) { + this.addSchema(schema, key, true, _validateSchema); + return this; + } + // Validate schema against its meta-schema + validateSchema(schema, throwOrLogError) { + if (typeof schema == "boolean") + return true; + let $schema; + $schema = schema.$schema; + if ($schema !== undefined && typeof $schema != "string") { + throw new Error("$schema must be a string"); + } + $schema = $schema || this.opts.defaultMeta || this.defaultMeta(); + if (!$schema) { + this.logger.warn("meta-schema not available"); + this.errors = null; + return true; + } + const valid = this.validate($schema, schema); + if (!valid && throwOrLogError) { + const message = "schema is invalid: " + this.errorsText(); + if (this.opts.validateSchema === "log") + this.logger.error(message); + else + throw new Error(message); + } + return valid; + } + // Get compiled schema by `key` or `ref`. + // (`key` that was passed to `addSchema` or full schema reference - `schema.$id` or resolved id) + getSchema(keyRef) { + let sch; + while (typeof (sch = getSchEnv.call(this, keyRef)) == "string") + keyRef = sch; + if (sch === undefined) { + const { schemaId } = this.opts; + const root = new compile_1.SchemaEnv({ schema: {}, schemaId }); + sch = compile_1.resolveSchema.call(this, root, keyRef); + if (!sch) + return; + this.refs[keyRef] = sch; + } + return (sch.validate || this._compileSchemaEnv(sch)); + } + // Remove cached schema(s). + // If no parameter is passed all schemas but meta-schemas are removed. + // If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed. + // Even if schema is referenced by other schemas it still can be removed as other schemas have local references. + removeSchema(schemaKeyRef) { + if (schemaKeyRef instanceof RegExp) { + this._removeAllSchemas(this.schemas, schemaKeyRef); + this._removeAllSchemas(this.refs, schemaKeyRef); + return this; + } + switch (typeof schemaKeyRef) { + case "undefined": + this._removeAllSchemas(this.schemas); + this._removeAllSchemas(this.refs); + this._cache.clear(); + return this; + case "string": { + const sch = getSchEnv.call(this, schemaKeyRef); + if (typeof sch == "object") + this._cache.delete(sch.schema); + delete this.schemas[schemaKeyRef]; + delete this.refs[schemaKeyRef]; + return this; + } + case "object": { + const cacheKey = schemaKeyRef; + this._cache.delete(cacheKey); + let id = schemaKeyRef[this.opts.schemaId]; + if (id) { + id = (0, resolve_1.normalizeId)(id); + delete this.schemas[id]; + delete this.refs[id]; + } + return this; + } + default: + throw new Error("ajv.removeSchema: invalid parameter"); + } + } + // add "vocabulary" - a collection of keywords + addVocabulary(definitions) { + for (const def of definitions) + this.addKeyword(def); + return this; + } + addKeyword(kwdOrDef, def // deprecated + ) { + let keyword; + if (typeof kwdOrDef == "string") { + keyword = kwdOrDef; + if (typeof def == "object") { + this.logger.warn("these parameters are deprecated, see docs for addKeyword"); + def.keyword = keyword; + } + } + else if (typeof kwdOrDef == "object" && def === undefined) { + def = kwdOrDef; + keyword = def.keyword; + if (Array.isArray(keyword) && !keyword.length) { + throw new Error("addKeywords: keyword must be string or non-empty array"); + } + } + else { + throw new Error("invalid addKeywords parameters"); + } + checkKeyword.call(this, keyword, def); + if (!def) { + (0, util_1.eachItem)(keyword, (kwd) => addRule.call(this, kwd)); + return this; + } + keywordMetaschema.call(this, def); + const definition = { + ...def, + type: (0, dataType_1.getJSONTypes)(def.type), + schemaType: (0, dataType_1.getJSONTypes)(def.schemaType), + }; + (0, util_1.eachItem)(keyword, definition.type.length === 0 + ? (k) => addRule.call(this, k, definition) + : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t))); + return this; + } + getKeyword(keyword) { + const rule = this.RULES.all[keyword]; + return typeof rule == "object" ? rule.definition : !!rule; + } + // Remove keyword + removeKeyword(keyword) { + // TODO return type should be Ajv + const { RULES } = this; + delete RULES.keywords[keyword]; + delete RULES.all[keyword]; + for (const group of RULES.rules) { + const i = group.rules.findIndex((rule) => rule.keyword === keyword); + if (i >= 0) + group.rules.splice(i, 1); + } + return this; + } + // Add format + addFormat(name, format) { + if (typeof format == "string") + format = new RegExp(format); + this.formats[name] = format; + return this; + } + errorsText(errors = this.errors, // optional array of validation errors + { separator = ", ", dataVar = "data" } = {} // optional options with properties `separator` and `dataVar` + ) { + if (!errors || errors.length === 0) + return "No errors"; + return errors + .map((e) => `${dataVar}${e.instancePath} ${e.message}`) + .reduce((text, msg) => text + separator + msg); + } + $dataMetaSchema(metaSchema, keywordsJsonPointers) { + const rules = this.RULES.all; + metaSchema = JSON.parse(JSON.stringify(metaSchema)); + for (const jsonPointer of keywordsJsonPointers) { + const segments = jsonPointer.split("/").slice(1); // first segment is an empty string + let keywords = metaSchema; + for (const seg of segments) + keywords = keywords[seg]; + for (const key in rules) { + const rule = rules[key]; + if (typeof rule != "object") + continue; + const { $data } = rule.definition; + const schema = keywords[key]; + if ($data && schema) + keywords[key] = schemaOrData(schema); + } + } + return metaSchema; + } + _removeAllSchemas(schemas, regex) { + for (const keyRef in schemas) { + const sch = schemas[keyRef]; + if (!regex || regex.test(keyRef)) { + if (typeof sch == "string") { + delete schemas[keyRef]; + } + else if (sch && !sch.meta) { + this._cache.delete(sch.schema); + delete schemas[keyRef]; + } + } + } + } + _addSchema(schema, meta, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) { + let id; + const { schemaId } = this.opts; + if (typeof schema == "object") { + id = schema[schemaId]; + } + else { + if (this.opts.jtd) + throw new Error("schema must be object"); + else if (typeof schema != "boolean") + throw new Error("schema must be object or boolean"); + } + let sch = this._cache.get(schema); + if (sch !== undefined) + return sch; + baseId = (0, resolve_1.normalizeId)(id || baseId); + const localRefs = resolve_1.getSchemaRefs.call(this, schema, baseId); + sch = new compile_1.SchemaEnv({ schema, schemaId, meta, baseId, localRefs }); + this._cache.set(sch.schema, sch); + if (addSchema && !baseId.startsWith("#")) { + // TODO atm it is allowed to overwrite schemas without id (instead of not adding them) + if (baseId) + this._checkUnique(baseId); + this.refs[baseId] = sch; + } + if (validateSchema) + this.validateSchema(schema, true); + return sch; + } + _checkUnique(id) { + if (this.schemas[id] || this.refs[id]) { + throw new Error(`schema with key or id "${id}" already exists`); + } + } + _compileSchemaEnv(sch) { + if (sch.meta) + this._compileMetaSchema(sch); + else + compile_1.compileSchema.call(this, sch); + /* istanbul ignore if */ + if (!sch.validate) + throw new Error("ajv implementation error"); + return sch.validate; + } + _compileMetaSchema(sch) { + const currentOpts = this.opts; + this.opts = this._metaOpts; + try { + compile_1.compileSchema.call(this, sch); + } + finally { + this.opts = currentOpts; + } + } + } + exports.default = Ajv; + Ajv.ValidationError = validation_error_1.default; + Ajv.MissingRefError = ref_error_1.default; + function checkOptions(checkOpts, options, msg, log = "error") { + for (const key in checkOpts) { + const opt = key; + if (opt in options) + this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`); + } + } + function getSchEnv(keyRef) { + keyRef = (0, resolve_1.normalizeId)(keyRef); // TODO tests fail without this line + return this.schemas[keyRef] || this.refs[keyRef]; + } + function addInitialSchemas() { + const optsSchemas = this.opts.schemas; + if (!optsSchemas) + return; + if (Array.isArray(optsSchemas)) + this.addSchema(optsSchemas); + else + for (const key in optsSchemas) + this.addSchema(optsSchemas[key], key); + } + function addInitialFormats() { + for (const name in this.opts.formats) { + const format = this.opts.formats[name]; + if (format) + this.addFormat(name, format); + } + } + function addInitialKeywords(defs) { + if (Array.isArray(defs)) { + this.addVocabulary(defs); + return; + } + this.logger.warn("keywords option as map is deprecated, pass array"); + for (const keyword in defs) { + const def = defs[keyword]; + if (!def.keyword) + def.keyword = keyword; + this.addKeyword(def); + } + } + function getMetaSchemaOptions() { + const metaOpts = { ...this.opts }; + for (const opt of META_IGNORE_OPTIONS) + delete metaOpts[opt]; + return metaOpts; + } + const noLogs = { log() { }, warn() { }, error() { } }; + function getLogger(logger) { + if (logger === false) + return noLogs; + if (logger === undefined) + return console; + if (logger.log && logger.warn && logger.error) + return logger; + throw new Error("logger must implement log, warn and error methods"); + } + const KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i; + function checkKeyword(keyword, def) { + const { RULES } = this; + (0, util_1.eachItem)(keyword, (kwd) => { + if (RULES.keywords[kwd]) + throw new Error(`Keyword ${kwd} is already defined`); + if (!KEYWORD_NAME.test(kwd)) + throw new Error(`Keyword ${kwd} has invalid name`); + }); + if (!def) + return; + if (def.$data && !("code" in def || "validate" in def)) { + throw new Error('$data keyword must have "code" or "validate" function'); + } + } + function addRule(keyword, definition, dataType) { + var _a; + const post = definition === null || definition === void 0 ? void 0 : definition.post; + if (dataType && post) + throw new Error('keyword with "post" flag cannot have "type"'); + const { RULES } = this; + let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t }) => t === dataType); + if (!ruleGroup) { + ruleGroup = { type: dataType, rules: [] }; + RULES.rules.push(ruleGroup); + } + RULES.keywords[keyword] = true; + if (!definition) + return; + const rule = { + keyword, + definition: { + ...definition, + type: (0, dataType_1.getJSONTypes)(definition.type), + schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType), + }, + }; + if (definition.before) + addBeforeRule.call(this, ruleGroup, rule, definition.before); + else + ruleGroup.rules.push(rule); + RULES.all[keyword] = rule; + (_a = definition.implements) === null || _a === void 0 ? void 0 : _a.forEach((kwd) => this.addKeyword(kwd)); + } + function addBeforeRule(ruleGroup, rule, before) { + const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before); + if (i >= 0) { + ruleGroup.rules.splice(i, 0, rule); + } + else { + ruleGroup.rules.push(rule); + this.logger.warn(`rule ${before} is not defined`); + } + } + function keywordMetaschema(def) { + let { metaSchema } = def; + if (metaSchema === undefined) + return; + if (def.$data && this.opts.$data) + metaSchema = schemaOrData(metaSchema); + def.validateSchema = this.compile(metaSchema, true); + } + const $dataRef = { + $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#", + }; + function schemaOrData(schema) { + return { anyOf: [schema, $dataRef] }; + } + +} (core$6)); + +var draft2020 = {}; + +var core$5 = {}; + +var id$1 = {}; + +Object.defineProperty(id$1, "__esModule", { value: true }); +const def$D = { + keyword: "id", + code() { + throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID'); + }, +}; +id$1.default = def$D; + +var ref = {}; + +Object.defineProperty(ref, "__esModule", { value: true }); +ref.callRef = ref.getValidate = void 0; +const ref_error_1 = requireRef_error(); +const code_1$8 = requireCode(); +const codegen_1$q = requireCodegen(); +const names_1$4 = requireNames(); +const compile_1$2 = compile; +const util_1$n = util$6; +const def$C = { + keyword: "$ref", + schemaType: "string", + code(cxt) { + const { gen, schema: $ref, it } = cxt; + const { baseId, schemaEnv: env, validateName, opts, self } = it; + const { root } = env; + if (($ref === "#" || $ref === "#/") && baseId === root.baseId) + return callRootRef(); + const schOrEnv = compile_1$2.resolveRef.call(self, root, baseId, $ref); + if (schOrEnv === undefined) + throw new ref_error_1.default(it.opts.uriResolver, baseId, $ref); + if (schOrEnv instanceof compile_1$2.SchemaEnv) + return callValidate(schOrEnv); + return inlineRefSchema(schOrEnv); + function callRootRef() { + if (env === root) + return callRef(cxt, validateName, env, env.$async); + const rootName = gen.scopeValue("root", { ref: root }); + return callRef(cxt, (0, codegen_1$q._) `${rootName}.validate`, root, root.$async); + } + function callValidate(sch) { + const v = getValidate(cxt, sch); + callRef(cxt, v, sch, sch.$async); + } + function inlineRefSchema(sch) { + const schName = gen.scopeValue("schema", opts.code.source === true ? { ref: sch, code: (0, codegen_1$q.stringify)(sch) } : { ref: sch }); + const valid = gen.name("valid"); + const schCxt = cxt.subschema({ + schema: sch, + dataTypes: [], + schemaPath: codegen_1$q.nil, + topSchemaRef: schName, + errSchemaPath: $ref, + }, valid); + cxt.mergeEvaluated(schCxt); + cxt.ok(valid); + } + }, +}; +function getValidate(cxt, sch) { + const { gen } = cxt; + return sch.validate + ? gen.scopeValue("validate", { ref: sch.validate }) + : (0, codegen_1$q._) `${gen.scopeValue("wrapper", { ref: sch })}.validate`; +} +ref.getValidate = getValidate; +function callRef(cxt, v, sch, $async) { + const { gen, it } = cxt; + const { allErrors, schemaEnv: env, opts } = it; + const passCxt = opts.passContext ? names_1$4.default.this : codegen_1$q.nil; + if ($async) + callAsyncRef(); + else + callSyncRef(); + function callAsyncRef() { + if (!env.$async) + throw new Error("async schema referenced by sync schema"); + const valid = gen.let("valid"); + gen.try(() => { + gen.code((0, codegen_1$q._) `await ${(0, code_1$8.callValidateCode)(cxt, v, passCxt)}`); + addEvaluatedFrom(v); // TODO will not work with async, it has to be returned with the result + if (!allErrors) + gen.assign(valid, true); + }, (e) => { + gen.if((0, codegen_1$q._) `!(${e} instanceof ${it.ValidationError})`, () => gen.throw(e)); + addErrorsFrom(e); + if (!allErrors) + gen.assign(valid, false); + }); + cxt.ok(valid); + } + function callSyncRef() { + cxt.result((0, code_1$8.callValidateCode)(cxt, v, passCxt), () => addEvaluatedFrom(v), () => addErrorsFrom(v)); + } + function addErrorsFrom(source) { + const errs = (0, codegen_1$q._) `${source}.errors`; + gen.assign(names_1$4.default.vErrors, (0, codegen_1$q._) `${names_1$4.default.vErrors} === null ? ${errs} : ${names_1$4.default.vErrors}.concat(${errs})`); // TODO tagged + gen.assign(names_1$4.default.errors, (0, codegen_1$q._) `${names_1$4.default.vErrors}.length`); + } + function addEvaluatedFrom(source) { + var _a; + if (!it.opts.unevaluated) + return; + const schEvaluated = (_a = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a === void 0 ? void 0 : _a.evaluated; + // TODO refactor + if (it.props !== true) { + if (schEvaluated && !schEvaluated.dynamicProps) { + if (schEvaluated.props !== undefined) { + it.props = util_1$n.mergeEvaluated.props(gen, schEvaluated.props, it.props); + } + } + else { + const props = gen.var("props", (0, codegen_1$q._) `${source}.evaluated.props`); + it.props = util_1$n.mergeEvaluated.props(gen, props, it.props, codegen_1$q.Name); + } + } + if (it.items !== true) { + if (schEvaluated && !schEvaluated.dynamicItems) { + if (schEvaluated.items !== undefined) { + it.items = util_1$n.mergeEvaluated.items(gen, schEvaluated.items, it.items); + } + } + else { + const items = gen.var("items", (0, codegen_1$q._) `${source}.evaluated.items`); + it.items = util_1$n.mergeEvaluated.items(gen, items, it.items, codegen_1$q.Name); + } + } + } +} +ref.callRef = callRef; +ref.default = def$C; + +Object.defineProperty(core$5, "__esModule", { value: true }); +const id_1 = id$1; +const ref_1$3 = ref; +const core$4 = [ + "$schema", + "$id", + "$defs", + "$vocabulary", + { keyword: "$comment" }, + "definitions", + id_1.default, + ref_1$3.default, +]; +core$5.default = core$4; + +var validation$4 = {}; + +var limitNumber$1 = {}; + +Object.defineProperty(limitNumber$1, "__esModule", { value: true }); +const codegen_1$p = requireCodegen(); +const ops$1 = codegen_1$p.operators; +const KWDs$2 = { + maximum: { okStr: "<=", ok: ops$1.LTE, fail: ops$1.GT }, + minimum: { okStr: ">=", ok: ops$1.GTE, fail: ops$1.LT }, + exclusiveMaximum: { okStr: "<", ok: ops$1.LT, fail: ops$1.GTE }, + exclusiveMinimum: { okStr: ">", ok: ops$1.GT, fail: ops$1.LTE }, +}; +const error$l = { + message: ({ keyword, schemaCode }) => (0, codegen_1$p.str) `must be ${KWDs$2[keyword].okStr} ${schemaCode}`, + params: ({ keyword, schemaCode }) => (0, codegen_1$p._) `{comparison: ${KWDs$2[keyword].okStr}, limit: ${schemaCode}}`, +}; +const def$B = { + keyword: Object.keys(KWDs$2), + type: "number", + schemaType: "number", + $data: true, + error: error$l, + code(cxt) { + const { keyword, data, schemaCode } = cxt; + cxt.fail$data((0, codegen_1$p._) `${data} ${KWDs$2[keyword].fail} ${schemaCode} || isNaN(${data})`); + }, +}; +limitNumber$1.default = def$B; + +var multipleOf = {}; + +Object.defineProperty(multipleOf, "__esModule", { value: true }); +const codegen_1$o = requireCodegen(); +const error$k = { + message: ({ schemaCode }) => (0, codegen_1$o.str) `must be multiple of ${schemaCode}`, + params: ({ schemaCode }) => (0, codegen_1$o._) `{multipleOf: ${schemaCode}}`, +}; +const def$A = { + keyword: "multipleOf", + type: "number", + schemaType: "number", + $data: true, + error: error$k, + code(cxt) { + const { gen, data, schemaCode, it } = cxt; + // const bdt = bad$DataType(schemaCode, <string>def.schemaType, $data) + const prec = it.opts.multipleOfPrecision; + const res = gen.let("res"); + const invalid = prec + ? (0, codegen_1$o._) `Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` + : (0, codegen_1$o._) `${res} !== parseInt(${res})`; + cxt.fail$data((0, codegen_1$o._) `(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`); + }, +}; +multipleOf.default = def$A; + +var limitLength = {}; + +var ucs2length$1 = {}; + +Object.defineProperty(ucs2length$1, "__esModule", { value: true }); +// https://mathiasbynens.be/notes/javascript-encoding +// https://github.com/bestiejs/punycode.js - punycode.ucs2.decode +function ucs2length(str) { + const len = str.length; + let length = 0; + let pos = 0; + let value; + while (pos < len) { + length++; + value = str.charCodeAt(pos++); + if (value >= 0xd800 && value <= 0xdbff && pos < len) { + // high surrogate, and there is a next character + value = str.charCodeAt(pos); + if ((value & 0xfc00) === 0xdc00) + pos++; // low surrogate + } + } + return length; +} +ucs2length$1.default = ucs2length; +ucs2length.code = 'require("ajv/dist/runtime/ucs2length").default'; + +Object.defineProperty(limitLength, "__esModule", { value: true }); +const codegen_1$n = requireCodegen(); +const util_1$m = util$6; +const ucs2length_1 = ucs2length$1; +const error$j = { + message({ keyword, schemaCode }) { + const comp = keyword === "maxLength" ? "more" : "fewer"; + return (0, codegen_1$n.str) `must NOT have ${comp} than ${schemaCode} characters`; + }, + params: ({ schemaCode }) => (0, codegen_1$n._) `{limit: ${schemaCode}}`, +}; +const def$z = { + keyword: ["maxLength", "minLength"], + type: "string", + schemaType: "number", + $data: true, + error: error$j, + code(cxt) { + const { keyword, data, schemaCode, it } = cxt; + const op = keyword === "maxLength" ? codegen_1$n.operators.GT : codegen_1$n.operators.LT; + const len = it.opts.unicode === false ? (0, codegen_1$n._) `${data}.length` : (0, codegen_1$n._) `${(0, util_1$m.useFunc)(cxt.gen, ucs2length_1.default)}(${data})`; + cxt.fail$data((0, codegen_1$n._) `${len} ${op} ${schemaCode}`); + }, +}; +limitLength.default = def$z; + +var pattern = {}; + +Object.defineProperty(pattern, "__esModule", { value: true }); +const code_1$7 = requireCode(); +const codegen_1$m = requireCodegen(); +const error$i = { + message: ({ schemaCode }) => (0, codegen_1$m.str) `must match pattern "${schemaCode}"`, + params: ({ schemaCode }) => (0, codegen_1$m._) `{pattern: ${schemaCode}}`, +}; +const def$y = { + keyword: "pattern", + type: "string", + schemaType: "string", + $data: true, + error: error$i, + code(cxt) { + const { data, $data, schema, schemaCode, it } = cxt; + // TODO regexp should be wrapped in try/catchs + const u = it.opts.unicodeRegExp ? "u" : ""; + const regExp = $data ? (0, codegen_1$m._) `(new RegExp(${schemaCode}, ${u}))` : (0, code_1$7.usePattern)(cxt, schema); + cxt.fail$data((0, codegen_1$m._) `!${regExp}.test(${data})`); + }, +}; +pattern.default = def$y; + +var limitProperties = {}; + +Object.defineProperty(limitProperties, "__esModule", { value: true }); +const codegen_1$l = requireCodegen(); +const error$h = { + message({ keyword, schemaCode }) { + const comp = keyword === "maxProperties" ? "more" : "fewer"; + return (0, codegen_1$l.str) `must NOT have ${comp} than ${schemaCode} properties`; + }, + params: ({ schemaCode }) => (0, codegen_1$l._) `{limit: ${schemaCode}}`, +}; +const def$x = { + keyword: ["maxProperties", "minProperties"], + type: "object", + schemaType: "number", + $data: true, + error: error$h, + code(cxt) { + const { keyword, data, schemaCode } = cxt; + const op = keyword === "maxProperties" ? codegen_1$l.operators.GT : codegen_1$l.operators.LT; + cxt.fail$data((0, codegen_1$l._) `Object.keys(${data}).length ${op} ${schemaCode}`); + }, +}; +limitProperties.default = def$x; + +var required$1 = {}; + +Object.defineProperty(required$1, "__esModule", { value: true }); +const code_1$6 = requireCode(); +const codegen_1$k = requireCodegen(); +const util_1$l = util$6; +const error$g = { + message: ({ params: { missingProperty } }) => (0, codegen_1$k.str) `must have required property '${missingProperty}'`, + params: ({ params: { missingProperty } }) => (0, codegen_1$k._) `{missingProperty: ${missingProperty}}`, +}; +const def$w = { + keyword: "required", + type: "object", + schemaType: "array", + $data: true, + error: error$g, + code(cxt) { + const { gen, schema, schemaCode, data, $data, it } = cxt; + const { opts } = it; + if (!$data && schema.length === 0) + return; + const useLoop = schema.length >= opts.loopRequired; + if (it.allErrors) + allErrorsMode(); + else + exitOnErrorMode(); + if (opts.strictRequired) { + const props = cxt.parentSchema.properties; + const { definedProperties } = cxt.it; + for (const requiredKey of schema) { + if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === undefined && !definedProperties.has(requiredKey)) { + const schemaPath = it.schemaEnv.baseId + it.errSchemaPath; + const msg = `required property "${requiredKey}" is not defined at "${schemaPath}" (strictRequired)`; + (0, util_1$l.checkStrictMode)(it, msg, it.opts.strictRequired); + } + } + } + function allErrorsMode() { + if (useLoop || $data) { + cxt.block$data(codegen_1$k.nil, loopAllRequired); + } + else { + for (const prop of schema) { + (0, code_1$6.checkReportMissingProp)(cxt, prop); + } + } + } + function exitOnErrorMode() { + const missing = gen.let("missing"); + if (useLoop || $data) { + const valid = gen.let("valid", true); + cxt.block$data(valid, () => loopUntilMissing(missing, valid)); + cxt.ok(valid); + } + else { + gen.if((0, code_1$6.checkMissingProp)(cxt, schema, missing)); + (0, code_1$6.reportMissingProp)(cxt, missing); + gen.else(); + } + } + function loopAllRequired() { + gen.forOf("prop", schemaCode, (prop) => { + cxt.setParams({ missingProperty: prop }); + gen.if((0, code_1$6.noPropertyInData)(gen, data, prop, opts.ownProperties), () => cxt.error()); + }); + } + function loopUntilMissing(missing, valid) { + cxt.setParams({ missingProperty: missing }); + gen.forOf(missing, schemaCode, () => { + gen.assign(valid, (0, code_1$6.propertyInData)(gen, data, missing, opts.ownProperties)); + gen.if((0, codegen_1$k.not)(valid), () => { + cxt.error(); + gen.break(); + }); + }, codegen_1$k.nil); + } + }, +}; +required$1.default = def$w; + +var limitItems = {}; + +Object.defineProperty(limitItems, "__esModule", { value: true }); +const codegen_1$j = requireCodegen(); +const error$f = { + message({ keyword, schemaCode }) { + const comp = keyword === "maxItems" ? "more" : "fewer"; + return (0, codegen_1$j.str) `must NOT have ${comp} than ${schemaCode} items`; + }, + params: ({ schemaCode }) => (0, codegen_1$j._) `{limit: ${schemaCode}}`, +}; +const def$v = { + keyword: ["maxItems", "minItems"], + type: "array", + schemaType: "number", + $data: true, + error: error$f, + code(cxt) { + const { keyword, data, schemaCode } = cxt; + const op = keyword === "maxItems" ? codegen_1$j.operators.GT : codegen_1$j.operators.LT; + cxt.fail$data((0, codegen_1$j._) `${data}.length ${op} ${schemaCode}`); + }, +}; +limitItems.default = def$v; + +var uniqueItems$1 = {}; + +var equal$1 = {}; + +Object.defineProperty(equal$1, "__esModule", { value: true }); +// https://github.com/ajv-validator/ajv/issues/889 +const equal = fastDeepEqual; +equal.code = 'require("ajv/dist/runtime/equal").default'; +equal$1.default = equal; + +Object.defineProperty(uniqueItems$1, "__esModule", { value: true }); +const dataType_1 = dataType; +const codegen_1$i = requireCodegen(); +const util_1$k = util$6; +const equal_1$2 = equal$1; +const error$e = { + message: ({ params: { i, j } }) => (0, codegen_1$i.str) `must NOT have duplicate items (items ## ${j} and ${i} are identical)`, + params: ({ params: { i, j } }) => (0, codegen_1$i._) `{i: ${i}, j: ${j}}`, +}; +const def$u = { + keyword: "uniqueItems", + type: "array", + schemaType: "boolean", + $data: true, + error: error$e, + code(cxt) { + const { gen, data, $data, schema, parentSchema, schemaCode, it } = cxt; + if (!$data && !schema) + return; + const valid = gen.let("valid"); + const itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : []; + cxt.block$data(valid, validateUniqueItems, (0, codegen_1$i._) `${schemaCode} === false`); + cxt.ok(valid); + function validateUniqueItems() { + const i = gen.let("i", (0, codegen_1$i._) `${data}.length`); + const j = gen.let("j"); + cxt.setParams({ i, j }); + gen.assign(valid, true); + gen.if((0, codegen_1$i._) `${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j)); + } + function canOptimize() { + return itemTypes.length > 0 && !itemTypes.some((t) => t === "object" || t === "array"); + } + function loopN(i, j) { + const item = gen.name("item"); + const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it.opts.strictNumbers, dataType_1.DataType.Wrong); + const indices = gen.const("indices", (0, codegen_1$i._) `{}`); + gen.for((0, codegen_1$i._) `;${i}--;`, () => { + gen.let(item, (0, codegen_1$i._) `${data}[${i}]`); + gen.if(wrongType, (0, codegen_1$i._) `continue`); + if (itemTypes.length > 1) + gen.if((0, codegen_1$i._) `typeof ${item} == "string"`, (0, codegen_1$i._) `${item} += "_"`); + gen + .if((0, codegen_1$i._) `typeof ${indices}[${item}] == "number"`, () => { + gen.assign(j, (0, codegen_1$i._) `${indices}[${item}]`); + cxt.error(); + gen.assign(valid, false).break(); + }) + .code((0, codegen_1$i._) `${indices}[${item}] = ${i}`); + }); + } + function loopN2(i, j) { + const eql = (0, util_1$k.useFunc)(gen, equal_1$2.default); + const outer = gen.name("outer"); + gen.label(outer).for((0, codegen_1$i._) `;${i}--;`, () => gen.for((0, codegen_1$i._) `${j} = ${i}; ${j}--;`, () => gen.if((0, codegen_1$i._) `${eql}(${data}[${i}], ${data}[${j}])`, () => { + cxt.error(); + gen.assign(valid, false).break(outer); + }))); + } + }, +}; +uniqueItems$1.default = def$u; + +var _const = {}; + +Object.defineProperty(_const, "__esModule", { value: true }); +const codegen_1$h = requireCodegen(); +const util_1$j = util$6; +const equal_1$1 = equal$1; +const error$d = { + message: "must be equal to constant", + params: ({ schemaCode }) => (0, codegen_1$h._) `{allowedValue: ${schemaCode}}`, +}; +const def$t = { + keyword: "const", + $data: true, + error: error$d, + code(cxt) { + const { gen, data, $data, schemaCode, schema } = cxt; + if ($data || (schema && typeof schema == "object")) { + cxt.fail$data((0, codegen_1$h._) `!${(0, util_1$j.useFunc)(gen, equal_1$1.default)}(${data}, ${schemaCode})`); + } + else { + cxt.fail((0, codegen_1$h._) `${schema} !== ${data}`); + } + }, +}; +_const.default = def$t; + +var _enum = {}; + +Object.defineProperty(_enum, "__esModule", { value: true }); +const codegen_1$g = requireCodegen(); +const util_1$i = util$6; +const equal_1 = equal$1; +const error$c = { + message: "must be equal to one of the allowed values", + params: ({ schemaCode }) => (0, codegen_1$g._) `{allowedValues: ${schemaCode}}`, +}; +const def$s = { + keyword: "enum", + schemaType: "array", + $data: true, + error: error$c, + code(cxt) { + const { gen, data, $data, schema, schemaCode, it } = cxt; + if (!$data && schema.length === 0) + throw new Error("enum must have non-empty array"); + const useLoop = schema.length >= it.opts.loopEnum; + let eql; + const getEql = () => (eql !== null && eql !== void 0 ? eql : (eql = (0, util_1$i.useFunc)(gen, equal_1.default))); + let valid; + if (useLoop || $data) { + valid = gen.let("valid"); + cxt.block$data(valid, loopEnum); + } + else { + /* istanbul ignore if */ + if (!Array.isArray(schema)) + throw new Error("ajv implementation error"); + const vSchema = gen.const("vSchema", schemaCode); + valid = (0, codegen_1$g.or)(...schema.map((_x, i) => equalCode(vSchema, i))); + } + cxt.pass(valid); + function loopEnum() { + gen.assign(valid, false); + gen.forOf("v", schemaCode, (v) => gen.if((0, codegen_1$g._) `${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break())); + } + function equalCode(vSchema, i) { + const sch = schema[i]; + return typeof sch === "object" && sch !== null + ? (0, codegen_1$g._) `${getEql()}(${data}, ${vSchema}[${i}])` + : (0, codegen_1$g._) `${data} === ${sch}`; + } + }, +}; +_enum.default = def$s; + +Object.defineProperty(validation$4, "__esModule", { value: true }); +const limitNumber_1$1 = limitNumber$1; +const multipleOf_1$1 = multipleOf; +const limitLength_1$1 = limitLength; +const pattern_1$1 = pattern; +const limitProperties_1$1 = limitProperties; +const required_1$1 = required$1; +const limitItems_1$1 = limitItems; +const uniqueItems_1$1 = uniqueItems$1; +const const_1$1 = _const; +const enum_1$1 = _enum; +const validation$3 = [ + // number + limitNumber_1$1.default, + multipleOf_1$1.default, + // string + limitLength_1$1.default, + pattern_1$1.default, + // object + limitProperties_1$1.default, + required_1$1.default, + // array + limitItems_1$1.default, + uniqueItems_1$1.default, + // any + { keyword: "type", schemaType: ["string", "array"] }, + { keyword: "nullable", schemaType: "boolean" }, + const_1$1.default, + enum_1$1.default, +]; +validation$4.default = validation$3; + +var applicator$1 = {}; + +var additionalItems = {}; + +Object.defineProperty(additionalItems, "__esModule", { value: true }); +additionalItems.validateAdditionalItems = void 0; +const codegen_1$f = requireCodegen(); +const util_1$h = util$6; +const error$b = { + message: ({ params: { len } }) => (0, codegen_1$f.str) `must NOT have more than ${len} items`, + params: ({ params: { len } }) => (0, codegen_1$f._) `{limit: ${len}}`, +}; +const def$r = { + keyword: "additionalItems", + type: "array", + schemaType: ["boolean", "object"], + before: "uniqueItems", + error: error$b, + code(cxt) { + const { parentSchema, it } = cxt; + const { items } = parentSchema; + if (!Array.isArray(items)) { + (0, util_1$h.checkStrictMode)(it, '"additionalItems" is ignored when "items" is not an array of schemas'); + return; + } + validateAdditionalItems(cxt, items); + }, +}; +function validateAdditionalItems(cxt, items) { + const { gen, schema, data, keyword, it } = cxt; + it.items = true; + const len = gen.const("len", (0, codegen_1$f._) `${data}.length`); + if (schema === false) { + cxt.setParams({ len: items.length }); + cxt.pass((0, codegen_1$f._) `${len} <= ${items.length}`); + } + else if (typeof schema == "object" && !(0, util_1$h.alwaysValidSchema)(it, schema)) { + const valid = gen.var("valid", (0, codegen_1$f._) `${len} <= ${items.length}`); // TODO var + gen.if((0, codegen_1$f.not)(valid), () => validateItems(valid)); + cxt.ok(valid); + } + function validateItems(valid) { + gen.forRange("i", items.length, len, (i) => { + cxt.subschema({ keyword, dataProp: i, dataPropType: util_1$h.Type.Num }, valid); + if (!it.allErrors) + gen.if((0, codegen_1$f.not)(valid), () => gen.break()); + }); + } +} +additionalItems.validateAdditionalItems = validateAdditionalItems; +additionalItems.default = def$r; + +var prefixItems = {}; + +var items$2 = {}; + +Object.defineProperty(items$2, "__esModule", { value: true }); +items$2.validateTuple = void 0; +const codegen_1$e = requireCodegen(); +const util_1$g = util$6; +const code_1$5 = requireCode(); +const def$q = { + keyword: "items", + type: "array", + schemaType: ["object", "array", "boolean"], + before: "uniqueItems", + code(cxt) { + const { schema, it } = cxt; + if (Array.isArray(schema)) + return validateTuple(cxt, "additionalItems", schema); + it.items = true; + if ((0, util_1$g.alwaysValidSchema)(it, schema)) + return; + cxt.ok((0, code_1$5.validateArray)(cxt)); + }, +}; +function validateTuple(cxt, extraItems, schArr = cxt.schema) { + const { gen, parentSchema, data, keyword, it } = cxt; + checkStrictTuple(parentSchema); + if (it.opts.unevaluated && schArr.length && it.items !== true) { + it.items = util_1$g.mergeEvaluated.items(gen, schArr.length, it.items); + } + const valid = gen.name("valid"); + const len = gen.const("len", (0, codegen_1$e._) `${data}.length`); + schArr.forEach((sch, i) => { + if ((0, util_1$g.alwaysValidSchema)(it, sch)) + return; + gen.if((0, codegen_1$e._) `${len} > ${i}`, () => cxt.subschema({ + keyword, + schemaProp: i, + dataProp: i, + }, valid)); + cxt.ok(valid); + }); + function checkStrictTuple(sch) { + const { opts, errSchemaPath } = it; + const l = schArr.length; + const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false); + if (opts.strictTuples && !fullTuple) { + const msg = `"${keyword}" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`; + (0, util_1$g.checkStrictMode)(it, msg, opts.strictTuples); + } + } +} +items$2.validateTuple = validateTuple; +items$2.default = def$q; + +Object.defineProperty(prefixItems, "__esModule", { value: true }); +const items_1$1 = items$2; +const def$p = { + keyword: "prefixItems", + type: "array", + schemaType: ["array"], + before: "uniqueItems", + code: (cxt) => (0, items_1$1.validateTuple)(cxt, "items"), +}; +prefixItems.default = def$p; + +var items2020 = {}; + +Object.defineProperty(items2020, "__esModule", { value: true }); +const codegen_1$d = requireCodegen(); +const util_1$f = util$6; +const code_1$4 = requireCode(); +const additionalItems_1$1 = additionalItems; +const error$a = { + message: ({ params: { len } }) => (0, codegen_1$d.str) `must NOT have more than ${len} items`, + params: ({ params: { len } }) => (0, codegen_1$d._) `{limit: ${len}}`, +}; +const def$o = { + keyword: "items", + type: "array", + schemaType: ["object", "boolean"], + before: "uniqueItems", + error: error$a, + code(cxt) { + const { schema, parentSchema, it } = cxt; + const { prefixItems } = parentSchema; + it.items = true; + if ((0, util_1$f.alwaysValidSchema)(it, schema)) + return; + if (prefixItems) + (0, additionalItems_1$1.validateAdditionalItems)(cxt, prefixItems); + else + cxt.ok((0, code_1$4.validateArray)(cxt)); + }, +}; +items2020.default = def$o; + +var contains$3 = {}; + +Object.defineProperty(contains$3, "__esModule", { value: true }); +const codegen_1$c = requireCodegen(); +const util_1$e = util$6; +const error$9 = { + message: ({ params: { min, max } }) => max === undefined + ? (0, codegen_1$c.str) `must contain at least ${min} valid item(s)` + : (0, codegen_1$c.str) `must contain at least ${min} and no more than ${max} valid item(s)`, + params: ({ params: { min, max } }) => max === undefined ? (0, codegen_1$c._) `{minContains: ${min}}` : (0, codegen_1$c._) `{minContains: ${min}, maxContains: ${max}}`, +}; +const def$n = { + keyword: "contains", + type: "array", + schemaType: ["object", "boolean"], + before: "uniqueItems", + trackErrors: true, + error: error$9, + code(cxt) { + const { gen, schema, parentSchema, data, it } = cxt; + let min; + let max; + const { minContains, maxContains } = parentSchema; + if (it.opts.next) { + min = minContains === undefined ? 1 : minContains; + max = maxContains; + } + else { + min = 1; + } + const len = gen.const("len", (0, codegen_1$c._) `${data}.length`); + cxt.setParams({ min, max }); + if (max === undefined && min === 0) { + (0, util_1$e.checkStrictMode)(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`); + return; + } + if (max !== undefined && min > max) { + (0, util_1$e.checkStrictMode)(it, `"minContains" > "maxContains" is always invalid`); + cxt.fail(); + return; + } + if ((0, util_1$e.alwaysValidSchema)(it, schema)) { + let cond = (0, codegen_1$c._) `${len} >= ${min}`; + if (max !== undefined) + cond = (0, codegen_1$c._) `${cond} && ${len} <= ${max}`; + cxt.pass(cond); + return; + } + it.items = true; + const valid = gen.name("valid"); + if (max === undefined && min === 1) { + validateItems(valid, () => gen.if(valid, () => gen.break())); + } + else if (min === 0) { + gen.let(valid, true); + if (max !== undefined) + gen.if((0, codegen_1$c._) `${data}.length > 0`, validateItemsWithCount); + } + else { + gen.let(valid, false); + validateItemsWithCount(); + } + cxt.result(valid, () => cxt.reset()); + function validateItemsWithCount() { + const schValid = gen.name("_valid"); + const count = gen.let("count", 0); + validateItems(schValid, () => gen.if(schValid, () => checkLimits(count))); + } + function validateItems(_valid, block) { + gen.forRange("i", 0, len, (i) => { + cxt.subschema({ + keyword: "contains", + dataProp: i, + dataPropType: util_1$e.Type.Num, + compositeRule: true, + }, _valid); + block(); + }); + } + function checkLimits(count) { + gen.code((0, codegen_1$c._) `${count}++`); + if (max === undefined) { + gen.if((0, codegen_1$c._) `${count} >= ${min}`, () => gen.assign(valid, true).break()); + } + else { + gen.if((0, codegen_1$c._) `${count} > ${max}`, () => gen.assign(valid, false).break()); + if (min === 1) + gen.assign(valid, true); + else + gen.if((0, codegen_1$c._) `${count} >= ${min}`, () => gen.assign(valid, true)); + } + } + }, +}; +contains$3.default = def$n; + +var dependencies$2 = {}; + +(function (exports) { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateSchemaDeps = exports.validatePropertyDeps = exports.error = void 0; + const codegen_1 = requireCodegen(); + const util_1 = util$6; + const code_1 = requireCode(); + exports.error = { + message: ({ params: { property, depsCount, deps } }) => { + const property_ies = depsCount === 1 ? "property" : "properties"; + return (0, codegen_1.str) `must have ${property_ies} ${deps} when property ${property} is present`; + }, + params: ({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._) `{property: ${property}, + missingProperty: ${missingProperty}, + depsCount: ${depsCount}, + deps: ${deps}}`, // TODO change to reference + }; + const def = { + keyword: "dependencies", + type: "object", + schemaType: "object", + error: exports.error, + code(cxt) { + const [propDeps, schDeps] = splitDependencies(cxt); + validatePropertyDeps(cxt, propDeps); + validateSchemaDeps(cxt, schDeps); + }, + }; + function splitDependencies({ schema }) { + const propertyDeps = {}; + const schemaDeps = {}; + for (const key in schema) { + if (key === "__proto__") + continue; + const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps; + deps[key] = schema[key]; + } + return [propertyDeps, schemaDeps]; + } + function validatePropertyDeps(cxt, propertyDeps = cxt.schema) { + const { gen, data, it } = cxt; + if (Object.keys(propertyDeps).length === 0) + return; + const missing = gen.let("missing"); + for (const prop in propertyDeps) { + const deps = propertyDeps[prop]; + if (deps.length === 0) + continue; + const hasProperty = (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties); + cxt.setParams({ + property: prop, + depsCount: deps.length, + deps: deps.join(", "), + }); + if (it.allErrors) { + gen.if(hasProperty, () => { + for (const depProp of deps) { + (0, code_1.checkReportMissingProp)(cxt, depProp); + } + }); + } + else { + gen.if((0, codegen_1._) `${hasProperty} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`); + (0, code_1.reportMissingProp)(cxt, missing); + gen.else(); + } + } + } + exports.validatePropertyDeps = validatePropertyDeps; + function validateSchemaDeps(cxt, schemaDeps = cxt.schema) { + const { gen, data, keyword, it } = cxt; + const valid = gen.name("valid"); + for (const prop in schemaDeps) { + if ((0, util_1.alwaysValidSchema)(it, schemaDeps[prop])) + continue; + gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties), () => { + const schCxt = cxt.subschema({ keyword, schemaProp: prop }, valid); + cxt.mergeValidEvaluated(schCxt, valid); + }, () => gen.var(valid, true) // TODO var + ); + cxt.ok(valid); + } + } + exports.validateSchemaDeps = validateSchemaDeps; + exports.default = def; + +} (dependencies$2)); + +var propertyNames = {}; + +Object.defineProperty(propertyNames, "__esModule", { value: true }); +const codegen_1$b = requireCodegen(); +const util_1$d = util$6; +const error$8 = { + message: "property name must be valid", + params: ({ params }) => (0, codegen_1$b._) `{propertyName: ${params.propertyName}}`, +}; +const def$m = { + keyword: "propertyNames", + type: "object", + schemaType: ["object", "boolean"], + error: error$8, + code(cxt) { + const { gen, schema, data, it } = cxt; + if ((0, util_1$d.alwaysValidSchema)(it, schema)) + return; + const valid = gen.name("valid"); + gen.forIn("key", data, (key) => { + cxt.setParams({ propertyName: key }); + cxt.subschema({ + keyword: "propertyNames", + data: key, + dataTypes: ["string"], + propertyName: key, + compositeRule: true, + }, valid); + gen.if((0, codegen_1$b.not)(valid), () => { + cxt.error(true); + if (!it.allErrors) + gen.break(); + }); + }); + cxt.ok(valid); + }, +}; +propertyNames.default = def$m; + +var additionalProperties$1 = {}; + +Object.defineProperty(additionalProperties$1, "__esModule", { value: true }); +const code_1$3 = requireCode(); +const codegen_1$a = requireCodegen(); +const names_1$3 = requireNames(); +const util_1$c = util$6; +const error$7 = { + message: "must NOT have additional properties", + params: ({ params }) => (0, codegen_1$a._) `{additionalProperty: ${params.additionalProperty}}`, +}; +const def$l = { + keyword: "additionalProperties", + type: ["object"], + schemaType: ["boolean", "object"], + allowUndefined: true, + trackErrors: true, + error: error$7, + code(cxt) { + const { gen, schema, parentSchema, data, errsCount, it } = cxt; + /* istanbul ignore if */ + if (!errsCount) + throw new Error("ajv implementation error"); + const { allErrors, opts } = it; + it.props = true; + if (opts.removeAdditional !== "all" && (0, util_1$c.alwaysValidSchema)(it, schema)) + return; + const props = (0, code_1$3.allSchemaProperties)(parentSchema.properties); + const patProps = (0, code_1$3.allSchemaProperties)(parentSchema.patternProperties); + checkAdditionalProperties(); + cxt.ok((0, codegen_1$a._) `${errsCount} === ${names_1$3.default.errors}`); + function checkAdditionalProperties() { + gen.forIn("key", data, (key) => { + if (!props.length && !patProps.length) + additionalPropertyCode(key); + else + gen.if(isAdditional(key), () => additionalPropertyCode(key)); + }); + } + function isAdditional(key) { + let definedProp; + if (props.length > 8) { + // TODO maybe an option instead of hard-coded 8? + const propsSchema = (0, util_1$c.schemaRefOrVal)(it, parentSchema.properties, "properties"); + definedProp = (0, code_1$3.isOwnProperty)(gen, propsSchema, key); + } + else if (props.length) { + definedProp = (0, codegen_1$a.or)(...props.map((p) => (0, codegen_1$a._) `${key} === ${p}`)); + } + else { + definedProp = codegen_1$a.nil; + } + if (patProps.length) { + definedProp = (0, codegen_1$a.or)(definedProp, ...patProps.map((p) => (0, codegen_1$a._) `${(0, code_1$3.usePattern)(cxt, p)}.test(${key})`)); + } + return (0, codegen_1$a.not)(definedProp); + } + function deleteAdditional(key) { + gen.code((0, codegen_1$a._) `delete ${data}[${key}]`); + } + function additionalPropertyCode(key) { + if (opts.removeAdditional === "all" || (opts.removeAdditional && schema === false)) { + deleteAdditional(key); + return; + } + if (schema === false) { + cxt.setParams({ additionalProperty: key }); + cxt.error(); + if (!allErrors) + gen.break(); + return; + } + if (typeof schema == "object" && !(0, util_1$c.alwaysValidSchema)(it, schema)) { + const valid = gen.name("valid"); + if (opts.removeAdditional === "failing") { + applyAdditionalSchema(key, valid, false); + gen.if((0, codegen_1$a.not)(valid), () => { + cxt.reset(); + deleteAdditional(key); + }); + } + else { + applyAdditionalSchema(key, valid); + if (!allErrors) + gen.if((0, codegen_1$a.not)(valid), () => gen.break()); + } + } + } + function applyAdditionalSchema(key, valid, errors) { + const subschema = { + keyword: "additionalProperties", + dataProp: key, + dataPropType: util_1$c.Type.Str, + }; + if (errors === false) { + Object.assign(subschema, { + compositeRule: true, + createErrors: false, + allErrors: false, + }); + } + cxt.subschema(subschema, valid); + } + }, +}; +additionalProperties$1.default = def$l; + +var properties$a = {}; + +Object.defineProperty(properties$a, "__esModule", { value: true }); +const validate_1 = requireValidate(); +const code_1$2 = requireCode(); +const util_1$b = util$6; +const additionalProperties_1$1 = additionalProperties$1; +const def$k = { + keyword: "properties", + type: "object", + schemaType: "object", + code(cxt) { + const { gen, schema, parentSchema, data, it } = cxt; + if (it.opts.removeAdditional === "all" && parentSchema.additionalProperties === undefined) { + additionalProperties_1$1.default.code(new validate_1.KeywordCxt(it, additionalProperties_1$1.default, "additionalProperties")); + } + const allProps = (0, code_1$2.allSchemaProperties)(schema); + for (const prop of allProps) { + it.definedProperties.add(prop); + } + if (it.opts.unevaluated && allProps.length && it.props !== true) { + it.props = util_1$b.mergeEvaluated.props(gen, (0, util_1$b.toHash)(allProps), it.props); + } + const properties = allProps.filter((p) => !(0, util_1$b.alwaysValidSchema)(it, schema[p])); + if (properties.length === 0) + return; + const valid = gen.name("valid"); + for (const prop of properties) { + if (hasDefault(prop)) { + applyPropertySchema(prop); + } + else { + gen.if((0, code_1$2.propertyInData)(gen, data, prop, it.opts.ownProperties)); + applyPropertySchema(prop); + if (!it.allErrors) + gen.else().var(valid, true); + gen.endIf(); + } + cxt.it.definedProperties.add(prop); + cxt.ok(valid); + } + function hasDefault(prop) { + return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== undefined; + } + function applyPropertySchema(prop) { + cxt.subschema({ + keyword: "properties", + schemaProp: prop, + dataProp: prop, + }, valid); + } + }, +}; +properties$a.default = def$k; + +var patternProperties = {}; + +Object.defineProperty(patternProperties, "__esModule", { value: true }); +const code_1$1 = requireCode(); +const codegen_1$9 = requireCodegen(); +const util_1$a = util$6; +const util_2 = util$6; +const def$j = { + keyword: "patternProperties", + type: "object", + schemaType: "object", + code(cxt) { + const { gen, schema, data, parentSchema, it } = cxt; + const { opts } = it; + const patterns = (0, code_1$1.allSchemaProperties)(schema); + const alwaysValidPatterns = patterns.filter((p) => (0, util_1$a.alwaysValidSchema)(it, schema[p])); + if (patterns.length === 0 || + (alwaysValidPatterns.length === patterns.length && + (!it.opts.unevaluated || it.props === true))) { + return; + } + const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties; + const valid = gen.name("valid"); + if (it.props !== true && !(it.props instanceof codegen_1$9.Name)) { + it.props = (0, util_2.evaluatedPropsToName)(gen, it.props); + } + const { props } = it; + validatePatternProperties(); + function validatePatternProperties() { + for (const pat of patterns) { + if (checkProperties) + checkMatchingProperties(pat); + if (it.allErrors) { + validateProperties(pat); + } + else { + gen.var(valid, true); // TODO var + validateProperties(pat); + gen.if(valid); + } + } + } + function checkMatchingProperties(pat) { + for (const prop in checkProperties) { + if (new RegExp(pat).test(prop)) { + (0, util_1$a.checkStrictMode)(it, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`); + } + } + } + function validateProperties(pat) { + gen.forIn("key", data, (key) => { + gen.if((0, codegen_1$9._) `${(0, code_1$1.usePattern)(cxt, pat)}.test(${key})`, () => { + const alwaysValid = alwaysValidPatterns.includes(pat); + if (!alwaysValid) { + cxt.subschema({ + keyword: "patternProperties", + schemaProp: pat, + dataProp: key, + dataPropType: util_2.Type.Str, + }, valid); + } + if (it.opts.unevaluated && props !== true) { + gen.assign((0, codegen_1$9._) `${props}[${key}]`, true); + } + else if (!alwaysValid && !it.allErrors) { + // can short-circuit if `unevaluatedProperties` is not supported (opts.next === false) + // or if all properties were evaluated (props === true) + gen.if((0, codegen_1$9.not)(valid), () => gen.break()); + } + }); + }); + } + }, +}; +patternProperties.default = def$j; + +var not = {}; + +Object.defineProperty(not, "__esModule", { value: true }); +const util_1$9 = util$6; +const def$i = { + keyword: "not", + schemaType: ["object", "boolean"], + trackErrors: true, + code(cxt) { + const { gen, schema, it } = cxt; + if ((0, util_1$9.alwaysValidSchema)(it, schema)) { + cxt.fail(); + return; + } + const valid = gen.name("valid"); + cxt.subschema({ + keyword: "not", + compositeRule: true, + createErrors: false, + allErrors: false, + }, valid); + cxt.failResult(valid, () => cxt.reset(), () => cxt.error()); + }, + error: { message: "must NOT be valid" }, +}; +not.default = def$i; + +var anyOf = {}; + +Object.defineProperty(anyOf, "__esModule", { value: true }); +const code_1 = requireCode(); +const def$h = { + keyword: "anyOf", + schemaType: "array", + trackErrors: true, + code: code_1.validateUnion, + error: { message: "must match a schema in anyOf" }, +}; +anyOf.default = def$h; + +var oneOf = {}; + +Object.defineProperty(oneOf, "__esModule", { value: true }); +const codegen_1$8 = requireCodegen(); +const util_1$8 = util$6; +const error$6 = { + message: "must match exactly one schema in oneOf", + params: ({ params }) => (0, codegen_1$8._) `{passingSchemas: ${params.passing}}`, +}; +const def$g = { + keyword: "oneOf", + schemaType: "array", + trackErrors: true, + error: error$6, + code(cxt) { + const { gen, schema, parentSchema, it } = cxt; + /* istanbul ignore if */ + if (!Array.isArray(schema)) + throw new Error("ajv implementation error"); + if (it.opts.discriminator && parentSchema.discriminator) + return; + const schArr = schema; + const valid = gen.let("valid", false); + const passing = gen.let("passing", null); + const schValid = gen.name("_valid"); + cxt.setParams({ passing }); + // TODO possibly fail straight away (with warning or exception) if there are two empty always valid schemas + gen.block(validateOneOf); + cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); + function validateOneOf() { + schArr.forEach((sch, i) => { + let schCxt; + if ((0, util_1$8.alwaysValidSchema)(it, sch)) { + gen.var(schValid, true); + } + else { + schCxt = cxt.subschema({ + keyword: "oneOf", + schemaProp: i, + compositeRule: true, + }, schValid); + } + if (i > 0) { + gen + .if((0, codegen_1$8._) `${schValid} && ${valid}`) + .assign(valid, false) + .assign(passing, (0, codegen_1$8._) `[${passing}, ${i}]`) + .else(); + } + gen.if(schValid, () => { + gen.assign(valid, true); + gen.assign(passing, i); + if (schCxt) + cxt.mergeEvaluated(schCxt, codegen_1$8.Name); + }); + }); + } + }, +}; +oneOf.default = def$g; + +var allOf$1 = {}; + +Object.defineProperty(allOf$1, "__esModule", { value: true }); +const util_1$7 = util$6; +const def$f = { + keyword: "allOf", + schemaType: "array", + code(cxt) { + const { gen, schema, it } = cxt; + /* istanbul ignore if */ + if (!Array.isArray(schema)) + throw new Error("ajv implementation error"); + const valid = gen.name("valid"); + schema.forEach((sch, i) => { + if ((0, util_1$7.alwaysValidSchema)(it, sch)) + return; + const schCxt = cxt.subschema({ keyword: "allOf", schemaProp: i }, valid); + cxt.ok(valid); + cxt.mergeEvaluated(schCxt); + }); + }, +}; +allOf$1.default = def$f; + +var _if = {}; + +Object.defineProperty(_if, "__esModule", { value: true }); +const codegen_1$7 = requireCodegen(); +const util_1$6 = util$6; +const error$5 = { + message: ({ params }) => (0, codegen_1$7.str) `must match "${params.ifClause}" schema`, + params: ({ params }) => (0, codegen_1$7._) `{failingKeyword: ${params.ifClause}}`, +}; +const def$e = { + keyword: "if", + schemaType: ["object", "boolean"], + trackErrors: true, + error: error$5, + code(cxt) { + const { gen, parentSchema, it } = cxt; + if (parentSchema.then === undefined && parentSchema.else === undefined) { + (0, util_1$6.checkStrictMode)(it, '"if" without "then" and "else" is ignored'); + } + const hasThen = hasSchema(it, "then"); + const hasElse = hasSchema(it, "else"); + if (!hasThen && !hasElse) + return; + const valid = gen.let("valid", true); + const schValid = gen.name("_valid"); + validateIf(); + cxt.reset(); + if (hasThen && hasElse) { + const ifClause = gen.let("ifClause"); + cxt.setParams({ ifClause }); + gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause)); + } + else if (hasThen) { + gen.if(schValid, validateClause("then")); + } + else { + gen.if((0, codegen_1$7.not)(schValid), validateClause("else")); + } + cxt.pass(valid, () => cxt.error(true)); + function validateIf() { + const schCxt = cxt.subschema({ + keyword: "if", + compositeRule: true, + createErrors: false, + allErrors: false, + }, schValid); + cxt.mergeEvaluated(schCxt); + } + function validateClause(keyword, ifClause) { + return () => { + const schCxt = cxt.subschema({ keyword }, schValid); + gen.assign(valid, schValid); + cxt.mergeValidEvaluated(schCxt, valid); + if (ifClause) + gen.assign(ifClause, (0, codegen_1$7._) `${keyword}`); + else + cxt.setParams({ ifClause: keyword }); + }; + } + }, +}; +function hasSchema(it, keyword) { + const schema = it.schema[keyword]; + return schema !== undefined && !(0, util_1$6.alwaysValidSchema)(it, schema); +} +_if.default = def$e; + +var thenElse = {}; + +Object.defineProperty(thenElse, "__esModule", { value: true }); +const util_1$5 = util$6; +const def$d = { + keyword: ["then", "else"], + schemaType: ["object", "boolean"], + code({ keyword, parentSchema, it }) { + if (parentSchema.if === undefined) + (0, util_1$5.checkStrictMode)(it, `"${keyword}" without "if" is ignored`); + }, +}; +thenElse.default = def$d; + +Object.defineProperty(applicator$1, "__esModule", { value: true }); +const additionalItems_1 = additionalItems; +const prefixItems_1 = prefixItems; +const items_1 = items$2; +const items2020_1 = items2020; +const contains_1 = contains$3; +const dependencies_1$2 = dependencies$2; +const propertyNames_1 = propertyNames; +const additionalProperties_1 = additionalProperties$1; +const properties_1 = properties$a; +const patternProperties_1 = patternProperties; +const not_1 = not; +const anyOf_1 = anyOf; +const oneOf_1 = oneOf; +const allOf_1 = allOf$1; +const if_1 = _if; +const thenElse_1 = thenElse; +function getApplicator(draft2020 = false) { + const applicator = [ + // any + not_1.default, + anyOf_1.default, + oneOf_1.default, + allOf_1.default, + if_1.default, + thenElse_1.default, + // object + propertyNames_1.default, + additionalProperties_1.default, + dependencies_1$2.default, + properties_1.default, + patternProperties_1.default, + ]; + // array + if (draft2020) + applicator.push(prefixItems_1.default, items2020_1.default); + else + applicator.push(additionalItems_1.default, items_1.default); + applicator.push(contains_1.default); + return applicator; +} +applicator$1.default = getApplicator; + +var dynamic$1 = {}; + +var dynamicAnchor$1 = {}; + +Object.defineProperty(dynamicAnchor$1, "__esModule", { value: true }); +dynamicAnchor$1.dynamicAnchor = void 0; +const codegen_1$6 = requireCodegen(); +const names_1$2 = requireNames(); +const compile_1$1 = compile; +const ref_1$2 = ref; +const def$c = { + keyword: "$dynamicAnchor", + schemaType: "string", + code: (cxt) => dynamicAnchor(cxt, cxt.schema), +}; +function dynamicAnchor(cxt, anchor) { + const { gen, it } = cxt; + it.schemaEnv.root.dynamicAnchors[anchor] = true; + const v = (0, codegen_1$6._) `${names_1$2.default.dynamicAnchors}${(0, codegen_1$6.getProperty)(anchor)}`; + const validate = it.errSchemaPath === "#" ? it.validateName : _getValidate(cxt); + gen.if((0, codegen_1$6._) `!${v}`, () => gen.assign(v, validate)); +} +dynamicAnchor$1.dynamicAnchor = dynamicAnchor; +function _getValidate(cxt) { + const { schemaEnv, schema, self } = cxt.it; + const { root, baseId, localRefs, meta } = schemaEnv.root; + const { schemaId } = self.opts; + const sch = new compile_1$1.SchemaEnv({ schema, schemaId, root, baseId, localRefs, meta }); + compile_1$1.compileSchema.call(self, sch); + return (0, ref_1$2.getValidate)(cxt, sch); +} +dynamicAnchor$1.default = def$c; + +var dynamicRef$1 = {}; + +Object.defineProperty(dynamicRef$1, "__esModule", { value: true }); +dynamicRef$1.dynamicRef = void 0; +const codegen_1$5 = requireCodegen(); +const names_1$1 = requireNames(); +const ref_1$1 = ref; +const def$b = { + keyword: "$dynamicRef", + schemaType: "string", + code: (cxt) => dynamicRef(cxt, cxt.schema), +}; +function dynamicRef(cxt, ref) { + const { gen, keyword, it } = cxt; + if (ref[0] !== "#") + throw new Error(`"${keyword}" only supports hash fragment reference`); + const anchor = ref.slice(1); + if (it.allErrors) { + _dynamicRef(); + } + else { + const valid = gen.let("valid", false); + _dynamicRef(valid); + cxt.ok(valid); + } + function _dynamicRef(valid) { + // TODO the assumption here is that `recursiveRef: #` always points to the root + // of the schema object, which is not correct, because there may be $id that + // makes # point to it, and the target schema may not contain dynamic/recursiveAnchor. + // Because of that 2 tests in recursiveRef.json fail. + // This is a similar problem to #815 (`$id` doesn't alter resolution scope for `{ "$ref": "#" }`). + // (This problem is not tested in JSON-Schema-Test-Suite) + if (it.schemaEnv.root.dynamicAnchors[anchor]) { + const v = gen.let("_v", (0, codegen_1$5._) `${names_1$1.default.dynamicAnchors}${(0, codegen_1$5.getProperty)(anchor)}`); + gen.if(v, _callRef(v, valid), _callRef(it.validateName, valid)); + } + else { + _callRef(it.validateName, valid)(); + } + } + function _callRef(validate, valid) { + return valid + ? () => gen.block(() => { + (0, ref_1$1.callRef)(cxt, validate); + gen.let(valid, true); + }) + : () => (0, ref_1$1.callRef)(cxt, validate); + } +} +dynamicRef$1.dynamicRef = dynamicRef; +dynamicRef$1.default = def$b; + +var recursiveAnchor = {}; + +Object.defineProperty(recursiveAnchor, "__esModule", { value: true }); +const dynamicAnchor_1$1 = dynamicAnchor$1; +const util_1$4 = util$6; +const def$a = { + keyword: "$recursiveAnchor", + schemaType: "boolean", + code(cxt) { + if (cxt.schema) + (0, dynamicAnchor_1$1.dynamicAnchor)(cxt, ""); + else + (0, util_1$4.checkStrictMode)(cxt.it, "$recursiveAnchor: false is ignored"); + }, +}; +recursiveAnchor.default = def$a; + +var recursiveRef = {}; + +Object.defineProperty(recursiveRef, "__esModule", { value: true }); +const dynamicRef_1$1 = dynamicRef$1; +const def$9 = { + keyword: "$recursiveRef", + schemaType: "string", + code: (cxt) => (0, dynamicRef_1$1.dynamicRef)(cxt, cxt.schema), +}; +recursiveRef.default = def$9; + +Object.defineProperty(dynamic$1, "__esModule", { value: true }); +const dynamicAnchor_1 = dynamicAnchor$1; +const dynamicRef_1 = dynamicRef$1; +const recursiveAnchor_1 = recursiveAnchor; +const recursiveRef_1 = recursiveRef; +const dynamic = [dynamicAnchor_1.default, dynamicRef_1.default, recursiveAnchor_1.default, recursiveRef_1.default]; +dynamic$1.default = dynamic; + +var next$1 = {}; + +var dependentRequired = {}; + +Object.defineProperty(dependentRequired, "__esModule", { value: true }); +const dependencies_1$1 = dependencies$2; +const def$8 = { + keyword: "dependentRequired", + type: "object", + schemaType: "object", + error: dependencies_1$1.error, + code: (cxt) => (0, dependencies_1$1.validatePropertyDeps)(cxt), +}; +dependentRequired.default = def$8; + +var dependentSchemas = {}; + +Object.defineProperty(dependentSchemas, "__esModule", { value: true }); +const dependencies_1 = dependencies$2; +const def$7 = { + keyword: "dependentSchemas", + type: "object", + schemaType: "object", + code: (cxt) => (0, dependencies_1.validateSchemaDeps)(cxt), +}; +dependentSchemas.default = def$7; + +var limitContains = {}; + +Object.defineProperty(limitContains, "__esModule", { value: true }); +const util_1$3 = util$6; +const def$6 = { + keyword: ["maxContains", "minContains"], + type: "array", + schemaType: "number", + code({ keyword, parentSchema, it }) { + if (parentSchema.contains === undefined) { + (0, util_1$3.checkStrictMode)(it, `"${keyword}" without "contains" is ignored`); + } + }, +}; +limitContains.default = def$6; + +Object.defineProperty(next$1, "__esModule", { value: true }); +const dependentRequired_1 = dependentRequired; +const dependentSchemas_1 = dependentSchemas; +const limitContains_1 = limitContains; +const next = [dependentRequired_1.default, dependentSchemas_1.default, limitContains_1.default]; +next$1.default = next; + +var unevaluated$2 = {}; + +var unevaluatedProperties = {}; + +Object.defineProperty(unevaluatedProperties, "__esModule", { value: true }); +const codegen_1$4 = requireCodegen(); +const util_1$2 = util$6; +const names_1 = requireNames(); +const error$4 = { + message: "must NOT have unevaluated properties", + params: ({ params }) => (0, codegen_1$4._) `{unevaluatedProperty: ${params.unevaluatedProperty}}`, +}; +const def$5 = { + keyword: "unevaluatedProperties", + type: "object", + schemaType: ["boolean", "object"], + trackErrors: true, + error: error$4, + code(cxt) { + const { gen, schema, data, errsCount, it } = cxt; + /* istanbul ignore if */ + if (!errsCount) + throw new Error("ajv implementation error"); + const { allErrors, props } = it; + if (props instanceof codegen_1$4.Name) { + gen.if((0, codegen_1$4._) `${props} !== true`, () => gen.forIn("key", data, (key) => gen.if(unevaluatedDynamic(props, key), () => unevaluatedPropCode(key)))); + } + else if (props !== true) { + gen.forIn("key", data, (key) => props === undefined + ? unevaluatedPropCode(key) + : gen.if(unevaluatedStatic(props, key), () => unevaluatedPropCode(key))); + } + it.props = true; + cxt.ok((0, codegen_1$4._) `${errsCount} === ${names_1.default.errors}`); + function unevaluatedPropCode(key) { + if (schema === false) { + cxt.setParams({ unevaluatedProperty: key }); + cxt.error(); + if (!allErrors) + gen.break(); + return; + } + if (!(0, util_1$2.alwaysValidSchema)(it, schema)) { + const valid = gen.name("valid"); + cxt.subschema({ + keyword: "unevaluatedProperties", + dataProp: key, + dataPropType: util_1$2.Type.Str, + }, valid); + if (!allErrors) + gen.if((0, codegen_1$4.not)(valid), () => gen.break()); + } + } + function unevaluatedDynamic(evaluatedProps, key) { + return (0, codegen_1$4._) `!${evaluatedProps} || !${evaluatedProps}[${key}]`; + } + function unevaluatedStatic(evaluatedProps, key) { + const ps = []; + for (const p in evaluatedProps) { + if (evaluatedProps[p] === true) + ps.push((0, codegen_1$4._) `${key} !== ${p}`); + } + return (0, codegen_1$4.and)(...ps); + } + }, +}; +unevaluatedProperties.default = def$5; + +var unevaluatedItems = {}; + +Object.defineProperty(unevaluatedItems, "__esModule", { value: true }); +const codegen_1$3 = requireCodegen(); +const util_1$1 = util$6; +const error$3 = { + message: ({ params: { len } }) => (0, codegen_1$3.str) `must NOT have more than ${len} items`, + params: ({ params: { len } }) => (0, codegen_1$3._) `{limit: ${len}}`, +}; +const def$4 = { + keyword: "unevaluatedItems", + type: "array", + schemaType: ["boolean", "object"], + error: error$3, + code(cxt) { + const { gen, schema, data, it } = cxt; + const items = it.items || 0; + if (items === true) + return; + const len = gen.const("len", (0, codegen_1$3._) `${data}.length`); + if (schema === false) { + cxt.setParams({ len: items }); + cxt.fail((0, codegen_1$3._) `${len} > ${items}`); + } + else if (typeof schema == "object" && !(0, util_1$1.alwaysValidSchema)(it, schema)) { + const valid = gen.var("valid", (0, codegen_1$3._) `${len} <= ${items}`); + gen.if((0, codegen_1$3.not)(valid), () => validateItems(valid, items)); + cxt.ok(valid); + } + it.items = true; + function validateItems(valid, from) { + gen.forRange("i", from, len, (i) => { + cxt.subschema({ keyword: "unevaluatedItems", dataProp: i, dataPropType: util_1$1.Type.Num }, valid); + if (!it.allErrors) + gen.if((0, codegen_1$3.not)(valid), () => gen.break()); + }); + } + }, +}; +unevaluatedItems.default = def$4; + +Object.defineProperty(unevaluated$2, "__esModule", { value: true }); +const unevaluatedProperties_1 = unevaluatedProperties; +const unevaluatedItems_1 = unevaluatedItems; +const unevaluated$1 = [unevaluatedProperties_1.default, unevaluatedItems_1.default]; +unevaluated$2.default = unevaluated$1; + +var format$5 = {}; + +var format$4 = {}; + +Object.defineProperty(format$4, "__esModule", { value: true }); +const codegen_1$2 = requireCodegen(); +const error$2 = { + message: ({ schemaCode }) => (0, codegen_1$2.str) `must match format "${schemaCode}"`, + params: ({ schemaCode }) => (0, codegen_1$2._) `{format: ${schemaCode}}`, +}; +const def$3 = { + keyword: "format", + type: ["number", "string"], + schemaType: "string", + $data: true, + error: error$2, + code(cxt, ruleType) { + const { gen, data, $data, schema, schemaCode, it } = cxt; + const { opts, errSchemaPath, schemaEnv, self } = it; + if (!opts.validateFormats) + return; + if ($data) + validate$DataFormat(); + else + validateFormat(); + function validate$DataFormat() { + const fmts = gen.scopeValue("formats", { + ref: self.formats, + code: opts.code.formats, + }); + const fDef = gen.const("fDef", (0, codegen_1$2._) `${fmts}[${schemaCode}]`); + const fType = gen.let("fType"); + const format = gen.let("format"); + // TODO simplify + gen.if((0, codegen_1$2._) `typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, () => gen.assign(fType, (0, codegen_1$2._) `${fDef}.type || "string"`).assign(format, (0, codegen_1$2._) `${fDef}.validate`), () => gen.assign(fType, (0, codegen_1$2._) `"string"`).assign(format, fDef)); + cxt.fail$data((0, codegen_1$2.or)(unknownFmt(), invalidFmt())); + function unknownFmt() { + if (opts.strictSchema === false) + return codegen_1$2.nil; + return (0, codegen_1$2._) `${schemaCode} && !${format}`; + } + function invalidFmt() { + const callFormat = schemaEnv.$async + ? (0, codegen_1$2._) `(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))` + : (0, codegen_1$2._) `${format}(${data})`; + const validData = (0, codegen_1$2._) `(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))`; + return (0, codegen_1$2._) `${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`; + } + } + function validateFormat() { + const formatDef = self.formats[schema]; + if (!formatDef) { + unknownFormat(); + return; + } + if (formatDef === true) + return; + const [fmtType, format, fmtRef] = getFormat(formatDef); + if (fmtType === ruleType) + cxt.pass(validCondition()); + function unknownFormat() { + if (opts.strictSchema === false) { + self.logger.warn(unknownMsg()); + return; + } + throw new Error(unknownMsg()); + function unknownMsg() { + return `unknown format "${schema}" ignored in schema at path "${errSchemaPath}"`; + } + } + function getFormat(fmtDef) { + const code = fmtDef instanceof RegExp + ? (0, codegen_1$2.regexpCode)(fmtDef) + : opts.code.formats + ? (0, codegen_1$2._) `${opts.code.formats}${(0, codegen_1$2.getProperty)(schema)}` + : undefined; + const fmt = gen.scopeValue("formats", { key: schema, ref: fmtDef, code }); + if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) { + return [fmtDef.type || "string", fmtDef.validate, (0, codegen_1$2._) `${fmt}.validate`]; + } + return ["string", fmtDef, fmt]; + } + function validCondition() { + if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) { + if (!schemaEnv.$async) + throw new Error("async format in sync schema"); + return (0, codegen_1$2._) `await ${fmtRef}(${data})`; + } + return typeof format == "function" ? (0, codegen_1$2._) `${fmtRef}(${data})` : (0, codegen_1$2._) `${fmtRef}.test(${data})`; + } + } + }, +}; +format$4.default = def$3; + +Object.defineProperty(format$5, "__esModule", { value: true }); +const format_1$2 = format$4; +const format$3 = [format_1$2.default]; +format$5.default = format$3; + +var metadata$1 = {}; + +Object.defineProperty(metadata$1, "__esModule", { value: true }); +metadata$1.contentVocabulary = metadata$1.metadataVocabulary = void 0; +metadata$1.metadataVocabulary = [ + "title", + "description", + "default", + "deprecated", + "readOnly", + "writeOnly", + "examples", +]; +metadata$1.contentVocabulary = [ + "contentMediaType", + "contentEncoding", + "contentSchema", +]; + +Object.defineProperty(draft2020, "__esModule", { value: true }); +const core_1$2 = core$5; +const validation_1$1 = validation$4; +const applicator_1$1 = applicator$1; +const dynamic_1 = dynamic$1; +const next_1 = next$1; +const unevaluated_1 = unevaluated$2; +const format_1$1 = format$5; +const metadata_1 = metadata$1; +const draft2020Vocabularies = [ + dynamic_1.default, + core_1$2.default, + validation_1$1.default, + (0, applicator_1$1.default)(true), + format_1$1.default, + metadata_1.metadataVocabulary, + metadata_1.contentVocabulary, + next_1.default, + unevaluated_1.default, +]; +draft2020.default = draft2020Vocabularies; + +var discriminator = {}; + +var types$1 = {}; + +(function (exports) { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DiscrError = void 0; + (function (DiscrError) { + DiscrError["Tag"] = "tag"; + DiscrError["Mapping"] = "mapping"; + })(exports.DiscrError || (exports.DiscrError = {})); + +} (types$1)); + +Object.defineProperty(discriminator, "__esModule", { value: true }); +const codegen_1$1 = requireCodegen(); +const types_1 = types$1; +const compile_1 = compile; +const util_1 = util$6; +const error$1 = { + message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag + ? `tag "${tagName}" must be string` + : `value of tag "${tagName}" must be in oneOf`, + params: ({ params: { discrError, tag, tagName } }) => (0, codegen_1$1._) `{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}`, +}; +const def$2 = { + keyword: "discriminator", + type: "object", + schemaType: "object", + error: error$1, + code(cxt) { + const { gen, data, schema, parentSchema, it } = cxt; + const { oneOf } = parentSchema; + if (!it.opts.discriminator) { + throw new Error("discriminator: requires discriminator option"); + } + const tagName = schema.propertyName; + if (typeof tagName != "string") + throw new Error("discriminator: requires propertyName"); + if (schema.mapping) + throw new Error("discriminator: mapping is not supported"); + if (!oneOf) + throw new Error("discriminator: requires oneOf keyword"); + const valid = gen.let("valid", false); + const tag = gen.const("tag", (0, codegen_1$1._) `${data}${(0, codegen_1$1.getProperty)(tagName)}`); + gen.if((0, codegen_1$1._) `typeof ${tag} == "string"`, () => validateMapping(), () => cxt.error(false, { discrError: types_1.DiscrError.Tag, tag, tagName })); + cxt.ok(valid); + function validateMapping() { + const mapping = getMapping(); + gen.if(false); + for (const tagValue in mapping) { + gen.elseIf((0, codegen_1$1._) `${tag} === ${tagValue}`); + gen.assign(valid, applyTagSchema(mapping[tagValue])); + } + gen.else(); + cxt.error(false, { discrError: types_1.DiscrError.Mapping, tag, tagName }); + gen.endIf(); + } + function applyTagSchema(schemaProp) { + const _valid = gen.name("valid"); + const schCxt = cxt.subschema({ keyword: "oneOf", schemaProp }, _valid); + cxt.mergeEvaluated(schCxt, codegen_1$1.Name); + return _valid; + } + function getMapping() { + var _a; + const oneOfMapping = {}; + const topRequired = hasRequired(parentSchema); + let tagRequired = true; + for (let i = 0; i < oneOf.length; i++) { + let sch = oneOf[i]; + if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it.self.RULES)) { + sch = compile_1.resolveRef.call(it.self, it.schemaEnv.root, it.baseId, sch === null || sch === void 0 ? void 0 : sch.$ref); + if (sch instanceof compile_1.SchemaEnv) + sch = sch.schema; + } + const propSch = (_a = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a === void 0 ? void 0 : _a[tagName]; + if (typeof propSch != "object") { + throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`); + } + tagRequired = tagRequired && (topRequired || hasRequired(sch)); + addMappings(propSch, i); + } + if (!tagRequired) + throw new Error(`discriminator: "${tagName}" must be required`); + return oneOfMapping; + function hasRequired({ required }) { + return Array.isArray(required) && required.includes(tagName); + } + function addMappings(sch, i) { + if (sch.const) { + addMapping(sch.const, i); + } + else if (sch.enum) { + for (const tagValue of sch.enum) { + addMapping(tagValue, i); + } + } + else { + throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`); + } + } + function addMapping(tagValue, i) { + if (typeof tagValue != "string" || tagValue in oneOfMapping) { + throw new Error(`discriminator: "${tagName}" values must be unique strings`); + } + oneOfMapping[tagValue] = i; + } + } + }, +}; +discriminator.default = def$2; + +var jsonSchema202012 = {}; + +var $schema$8 = "https://json-schema.org/draft/2020-12/schema"; +var $id$7 = "https://json-schema.org/draft/2020-12/schema"; +var $vocabulary$7 = { + "https://json-schema.org/draft/2020-12/vocab/core": true, + "https://json-schema.org/draft/2020-12/vocab/applicator": true, + "https://json-schema.org/draft/2020-12/vocab/unevaluated": true, + "https://json-schema.org/draft/2020-12/vocab/validation": true, + "https://json-schema.org/draft/2020-12/vocab/meta-data": true, + "https://json-schema.org/draft/2020-12/vocab/format-annotation": true, + "https://json-schema.org/draft/2020-12/vocab/content": true +}; +var $dynamicAnchor$7 = "meta"; +var title$7 = "Core and Validation specifications meta-schema"; +var allOf = [ + { + $ref: "meta/core" + }, + { + $ref: "meta/applicator" + }, + { + $ref: "meta/unevaluated" + }, + { + $ref: "meta/validation" + }, + { + $ref: "meta/meta-data" + }, + { + $ref: "meta/format-annotation" + }, + { + $ref: "meta/content" + } +]; +var type$8 = [ + "object", + "boolean" +]; +var $comment = "This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use."; +var properties$9 = { + definitions: { + $comment: "\"definitions\" has been replaced by \"$defs\".", + type: "object", + additionalProperties: { + $dynamicRef: "#meta" + }, + deprecated: true, + "default": { + } + }, + dependencies: { + $comment: "\"dependencies\" has been split and replaced by \"dependentSchemas\" and \"dependentRequired\" in order to serve their differing semantics.", + type: "object", + additionalProperties: { + anyOf: [ + { + $dynamicRef: "#meta" + }, + { + $ref: "meta/validation#/$defs/stringArray" + } + ] + }, + deprecated: true, + "default": { + } + }, + $recursiveAnchor: { + $comment: "\"$recursiveAnchor\" has been replaced by \"$dynamicAnchor\".", + $ref: "meta/core#/$defs/anchorString", + deprecated: true + }, + $recursiveRef: { + $comment: "\"$recursiveRef\" has been replaced by \"$dynamicRef\".", + $ref: "meta/core#/$defs/uriReferenceString", + deprecated: true + } +}; +var require$$0$1 = { + $schema: $schema$8, + $id: $id$7, + $vocabulary: $vocabulary$7, + $dynamicAnchor: $dynamicAnchor$7, + title: title$7, + allOf: allOf, + type: type$8, + $comment: $comment, + properties: properties$9 +}; + +var $schema$7 = "https://json-schema.org/draft/2020-12/schema"; +var $id$6 = "https://json-schema.org/draft/2020-12/meta/applicator"; +var $vocabulary$6 = { + "https://json-schema.org/draft/2020-12/vocab/applicator": true +}; +var $dynamicAnchor$6 = "meta"; +var title$6 = "Applicator vocabulary meta-schema"; +var type$7 = [ + "object", + "boolean" +]; +var properties$8 = { + prefixItems: { + $ref: "#/$defs/schemaArray" + }, + items: { + $dynamicRef: "#meta" + }, + contains: { + $dynamicRef: "#meta" + }, + additionalProperties: { + $dynamicRef: "#meta" + }, + properties: { + type: "object", + additionalProperties: { + $dynamicRef: "#meta" + }, + "default": { + } + }, + patternProperties: { + type: "object", + additionalProperties: { + $dynamicRef: "#meta" + }, + propertyNames: { + format: "regex" + }, + "default": { + } + }, + dependentSchemas: { + type: "object", + additionalProperties: { + $dynamicRef: "#meta" + }, + "default": { + } + }, + propertyNames: { + $dynamicRef: "#meta" + }, + "if": { + $dynamicRef: "#meta" + }, + then: { + $dynamicRef: "#meta" + }, + "else": { + $dynamicRef: "#meta" + }, + allOf: { + $ref: "#/$defs/schemaArray" + }, + anyOf: { + $ref: "#/$defs/schemaArray" + }, + oneOf: { + $ref: "#/$defs/schemaArray" + }, + not: { + $dynamicRef: "#meta" + } +}; +var $defs$2 = { + schemaArray: { + type: "array", + minItems: 1, + items: { + $dynamicRef: "#meta" + } + } +}; +var require$$1$1 = { + $schema: $schema$7, + $id: $id$6, + $vocabulary: $vocabulary$6, + $dynamicAnchor: $dynamicAnchor$6, + title: title$6, + type: type$7, + properties: properties$8, + $defs: $defs$2 +}; + +var $schema$6 = "https://json-schema.org/draft/2020-12/schema"; +var $id$5 = "https://json-schema.org/draft/2020-12/meta/unevaluated"; +var $vocabulary$5 = { + "https://json-schema.org/draft/2020-12/vocab/unevaluated": true +}; +var $dynamicAnchor$5 = "meta"; +var title$5 = "Unevaluated applicator vocabulary meta-schema"; +var type$6 = [ + "object", + "boolean" +]; +var properties$7 = { + unevaluatedItems: { + $dynamicRef: "#meta" + }, + unevaluatedProperties: { + $dynamicRef: "#meta" + } +}; +var require$$2 = { + $schema: $schema$6, + $id: $id$5, + $vocabulary: $vocabulary$5, + $dynamicAnchor: $dynamicAnchor$5, + title: title$5, + type: type$6, + properties: properties$7 +}; + +var $schema$5 = "https://json-schema.org/draft/2020-12/schema"; +var $id$4 = "https://json-schema.org/draft/2020-12/meta/content"; +var $vocabulary$4 = { + "https://json-schema.org/draft/2020-12/vocab/content": true +}; +var $dynamicAnchor$4 = "meta"; +var title$4 = "Content vocabulary meta-schema"; +var type$5 = [ + "object", + "boolean" +]; +var properties$6 = { + contentEncoding: { + type: "string" + }, + contentMediaType: { + type: "string" + }, + contentSchema: { + $dynamicRef: "#meta" + } +}; +var require$$3$2 = { + $schema: $schema$5, + $id: $id$4, + $vocabulary: $vocabulary$4, + $dynamicAnchor: $dynamicAnchor$4, + title: title$4, + type: type$5, + properties: properties$6 +}; + +var $schema$4 = "https://json-schema.org/draft/2020-12/schema"; +var $id$3 = "https://json-schema.org/draft/2020-12/meta/core"; +var $vocabulary$3 = { + "https://json-schema.org/draft/2020-12/vocab/core": true +}; +var $dynamicAnchor$3 = "meta"; +var title$3 = "Core vocabulary meta-schema"; +var type$4 = [ + "object", + "boolean" +]; +var properties$5 = { + $id: { + $ref: "#/$defs/uriReferenceString", + $comment: "Non-empty fragments not allowed.", + pattern: "^[^#]*#?$" + }, + $schema: { + $ref: "#/$defs/uriString" + }, + $ref: { + $ref: "#/$defs/uriReferenceString" + }, + $anchor: { + $ref: "#/$defs/anchorString" + }, + $dynamicRef: { + $ref: "#/$defs/uriReferenceString" + }, + $dynamicAnchor: { + $ref: "#/$defs/anchorString" + }, + $vocabulary: { + type: "object", + propertyNames: { + $ref: "#/$defs/uriString" + }, + additionalProperties: { + type: "boolean" + } + }, + $comment: { + type: "string" + }, + $defs: { + type: "object", + additionalProperties: { + $dynamicRef: "#meta" + } + } +}; +var $defs$1 = { + anchorString: { + type: "string", + pattern: "^[A-Za-z_][-A-Za-z0-9._]*$" + }, + uriString: { + type: "string", + format: "uri" + }, + uriReferenceString: { + type: "string", + format: "uri-reference" + } +}; +var require$$4$1 = { + $schema: $schema$4, + $id: $id$3, + $vocabulary: $vocabulary$3, + $dynamicAnchor: $dynamicAnchor$3, + title: title$3, + type: type$4, + properties: properties$5, + $defs: $defs$1 +}; + +var $schema$3 = "https://json-schema.org/draft/2020-12/schema"; +var $id$2 = "https://json-schema.org/draft/2020-12/meta/format-annotation"; +var $vocabulary$2 = { + "https://json-schema.org/draft/2020-12/vocab/format-annotation": true +}; +var $dynamicAnchor$2 = "meta"; +var title$2 = "Format vocabulary meta-schema for annotation results"; +var type$3 = [ + "object", + "boolean" +]; +var properties$4 = { + format: { + type: "string" + } +}; +var require$$5 = { + $schema: $schema$3, + $id: $id$2, + $vocabulary: $vocabulary$2, + $dynamicAnchor: $dynamicAnchor$2, + title: title$2, + type: type$3, + properties: properties$4 +}; + +var $schema$2 = "https://json-schema.org/draft/2020-12/schema"; +var $id$1 = "https://json-schema.org/draft/2020-12/meta/meta-data"; +var $vocabulary$1 = { + "https://json-schema.org/draft/2020-12/vocab/meta-data": true +}; +var $dynamicAnchor$1 = "meta"; +var title$1 = "Meta-data vocabulary meta-schema"; +var type$2 = [ + "object", + "boolean" +]; +var properties$3 = { + title: { + type: "string" + }, + description: { + type: "string" + }, + "default": true, + deprecated: { + type: "boolean", + "default": false + }, + readOnly: { + type: "boolean", + "default": false + }, + writeOnly: { + type: "boolean", + "default": false + }, + examples: { + type: "array", + items: true + } +}; +var require$$6 = { + $schema: $schema$2, + $id: $id$1, + $vocabulary: $vocabulary$1, + $dynamicAnchor: $dynamicAnchor$1, + title: title$1, + type: type$2, + properties: properties$3 +}; + +var $schema$1 = "https://json-schema.org/draft/2020-12/schema"; +var $id = "https://json-schema.org/draft/2020-12/meta/validation"; +var $vocabulary = { + "https://json-schema.org/draft/2020-12/vocab/validation": true +}; +var $dynamicAnchor = "meta"; +var title = "Validation vocabulary meta-schema"; +var type$1 = [ + "object", + "boolean" +]; +var properties$2 = { + type: { + anyOf: [ + { + $ref: "#/$defs/simpleTypes" + }, + { + type: "array", + items: { + $ref: "#/$defs/simpleTypes" + }, + minItems: 1, + uniqueItems: true + } + ] + }, + "const": true, + "enum": { + type: "array", + items: true + }, + multipleOf: { + type: "number", + exclusiveMinimum: 0 + }, + maximum: { + type: "number" + }, + exclusiveMaximum: { + type: "number" + }, + minimum: { + type: "number" + }, + exclusiveMinimum: { + type: "number" + }, + maxLength: { + $ref: "#/$defs/nonNegativeInteger" + }, + minLength: { + $ref: "#/$defs/nonNegativeIntegerDefault0" + }, + pattern: { + type: "string", + format: "regex" + }, + maxItems: { + $ref: "#/$defs/nonNegativeInteger" + }, + minItems: { + $ref: "#/$defs/nonNegativeIntegerDefault0" + }, + uniqueItems: { + type: "boolean", + "default": false + }, + maxContains: { + $ref: "#/$defs/nonNegativeInteger" + }, + minContains: { + $ref: "#/$defs/nonNegativeInteger", + "default": 1 + }, + maxProperties: { + $ref: "#/$defs/nonNegativeInteger" + }, + minProperties: { + $ref: "#/$defs/nonNegativeIntegerDefault0" + }, + required: { + $ref: "#/$defs/stringArray" + }, + dependentRequired: { + type: "object", + additionalProperties: { + $ref: "#/$defs/stringArray" + } + } +}; +var $defs = { + nonNegativeInteger: { + type: "integer", + minimum: 0 + }, + nonNegativeIntegerDefault0: { + $ref: "#/$defs/nonNegativeInteger", + "default": 0 + }, + simpleTypes: { + "enum": [ + "array", + "boolean", + "integer", + "null", + "number", + "object", + "string" + ] + }, + stringArray: { + type: "array", + items: { + type: "string" + }, + uniqueItems: true, + "default": [ + ] + } +}; +var require$$7 = { + $schema: $schema$1, + $id: $id, + $vocabulary: $vocabulary, + $dynamicAnchor: $dynamicAnchor, + title: title, + type: type$1, + properties: properties$2, + $defs: $defs +}; + +Object.defineProperty(jsonSchema202012, "__esModule", { value: true }); +const metaSchema = require$$0$1; +const applicator = require$$1$1; +const unevaluated = require$$2; +const content = require$$3$2; +const core$3 = require$$4$1; +const format$2 = require$$5; +const metadata = require$$6; +const validation$2 = require$$7; +const META_SUPPORT_DATA = ["/properties"]; +function addMetaSchema2020($data) { + [ + metaSchema, + applicator, + unevaluated, + content, + core$3, + with$data(this, format$2), + metadata, + with$data(this, validation$2), + ].forEach((sch) => this.addMetaSchema(sch, undefined, false)); + return this; + function with$data(ajv, sch) { + return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : sch; + } +} +jsonSchema202012.default = addMetaSchema2020; + +(function (module, exports) { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0; + const core_1 = core$6; + const draft2020_1 = draft2020; + const discriminator_1 = discriminator; + const json_schema_2020_12_1 = jsonSchema202012; + const META_SCHEMA_ID = "https://json-schema.org/draft/2020-12/schema"; + class Ajv2020 extends core_1.default { + constructor(opts = {}) { + super({ + ...opts, + dynamicRef: true, + next: true, + unevaluated: true, + }); + } + _addVocabularies() { + super._addVocabularies(); + draft2020_1.default.forEach((v) => this.addVocabulary(v)); + if (this.opts.discriminator) + this.addKeyword(discriminator_1.default); + } + _addDefaultMetaSchema() { + super._addDefaultMetaSchema(); + const { $data, meta } = this.opts; + if (!meta) + return; + json_schema_2020_12_1.default.call(this, $data); + this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; + } + defaultMeta() { + return (this.opts.defaultMeta = + super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined)); + } + } + module.exports = exports = Ajv2020; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.default = Ajv2020; + var validate_1 = requireValidate(); + Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function () { return validate_1.KeywordCxt; } }); + var codegen_1 = requireCodegen(); + Object.defineProperty(exports, "_", { enumerable: true, get: function () { return codegen_1._; } }); + Object.defineProperty(exports, "str", { enumerable: true, get: function () { return codegen_1.str; } }); + Object.defineProperty(exports, "stringify", { enumerable: true, get: function () { return codegen_1.stringify; } }); + Object.defineProperty(exports, "nil", { enumerable: true, get: function () { return codegen_1.nil; } }); + Object.defineProperty(exports, "Name", { enumerable: true, get: function () { return codegen_1.Name; } }); + Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function () { return codegen_1.CodeGen; } }); + var validation_error_1 = requireValidation_error(); + Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function () { return validation_error_1.default; } }); + var ref_error_1 = requireRef_error(); + Object.defineProperty(exports, "MissingRefError", { enumerable: true, get: function () { return ref_error_1.default; } }); + +} (_2020, _2020.exports)); + +var _2020Exports = _2020.exports; + +var dist$1 = {exports: {}}; + +var draft4 = {}; + +var core$2 = {}; + +Object.defineProperty(core$2, "__esModule", { value: true }); +const ref_1 = ref; +const core$1 = [ + "$schema", + "id", + "$defs", + { keyword: "$comment" }, + "definitions", + ref_1.default, +]; +core$2.default = core$1; + +var validation$1 = {}; + +var limitNumber = {}; + +Object.defineProperty(limitNumber, "__esModule", { value: true }); +const core_1$1 = core$6; +const codegen_1 = requireCodegen(); +const ops = codegen_1.operators; +const KWDs$1 = { + maximum: { + exclusive: "exclusiveMaximum", + ops: [ + { okStr: "<=", ok: ops.LTE, fail: ops.GT }, + { okStr: "<", ok: ops.LT, fail: ops.GTE }, + ], + }, + minimum: { + exclusive: "exclusiveMinimum", + ops: [ + { okStr: ">=", ok: ops.GTE, fail: ops.LT }, + { okStr: ">", ok: ops.GT, fail: ops.LTE }, + ], + }, +}; +const error = { + message: (cxt) => core_1$1.str `must be ${kwdOp(cxt).okStr} ${cxt.schemaCode}`, + params: (cxt) => core_1$1._ `{comparison: ${kwdOp(cxt).okStr}, limit: ${cxt.schemaCode}}`, +}; +const def$1 = { + keyword: Object.keys(KWDs$1), + type: "number", + schemaType: "number", + $data: true, + error, + code(cxt) { + const { data, schemaCode } = cxt; + cxt.fail$data(core_1$1._ `${data} ${kwdOp(cxt).fail} ${schemaCode} || isNaN(${data})`); + }, +}; +function kwdOp(cxt) { + var _a; + const keyword = cxt.keyword; + const opsIdx = ((_a = cxt.parentSchema) === null || _a === void 0 ? void 0 : _a[KWDs$1[keyword].exclusive]) ? 1 : 0; + return KWDs$1[keyword].ops[opsIdx]; +} +limitNumber.default = def$1; + +var limitNumberExclusive = {}; + +Object.defineProperty(limitNumberExclusive, "__esModule", { value: true }); +const KWDs = { + exclusiveMaximum: "maximum", + exclusiveMinimum: "minimum", +}; +const def = { + keyword: Object.keys(KWDs), + type: "number", + schemaType: "boolean", + code({ keyword, parentSchema }) { + const limitKwd = KWDs[keyword]; + if (parentSchema[limitKwd] === undefined) { + throw new Error(`${keyword} can only be used with ${limitKwd}`); + } + }, +}; +limitNumberExclusive.default = def; + +Object.defineProperty(validation$1, "__esModule", { value: true }); +const limitNumber_1 = limitNumber; +const limitNumberExclusive_1 = limitNumberExclusive; +const multipleOf_1 = multipleOf; +const limitLength_1 = limitLength; +const pattern_1 = pattern; +const limitProperties_1 = limitProperties; +const required_1 = required$1; +const limitItems_1 = limitItems; +const uniqueItems_1 = uniqueItems$1; +const const_1 = _const; +const enum_1 = _enum; +const validation = [ + // number + limitNumber_1.default, + limitNumberExclusive_1.default, + multipleOf_1.default, + // string + limitLength_1.default, + pattern_1.default, + // object + limitProperties_1.default, + required_1.default, + // array + limitItems_1.default, + uniqueItems_1.default, + // any + { keyword: "type", schemaType: ["string", "array"] }, + { keyword: "nullable", schemaType: "boolean" }, + const_1.default, + enum_1.default, +]; +validation$1.default = validation; + +Object.defineProperty(draft4, "__esModule", { value: true }); +const core_1 = core$2; +const validation_1 = validation$1; +const applicator_1 = applicator$1; +const format_1 = format$5; +const metadataVocabulary = ["title", "description", "default"]; +const draft4Vocabularies = [ + core_1.default, + validation_1.default, + applicator_1.default(), + format_1.default, + metadataVocabulary, +]; +draft4.default = draft4Vocabularies; + +var id = "http://json-schema.org/draft-04/schema#"; +var $schema = "http://json-schema.org/draft-04/schema#"; +var description$1 = "Core schema meta-schema"; +var definitions = { + schemaArray: { + type: "array", + minItems: 1, + items: { + $ref: "#" + } + }, + positiveInteger: { + type: "integer", + minimum: 0 + }, + positiveIntegerDefault0: { + allOf: [ + { + $ref: "#/definitions/positiveInteger" + }, + { + "default": 0 + } + ] + }, + simpleTypes: { + "enum": [ + "array", + "boolean", + "integer", + "null", + "number", + "object", + "string" + ] + }, + stringArray: { + type: "array", + items: { + type: "string" + }, + minItems: 1, + uniqueItems: true + } +}; +var type = "object"; +var properties$1 = { + id: { + type: "string", + format: "uri" + }, + $schema: { + type: "string", + format: "uri" + }, + title: { + type: "string" + }, + description: { + type: "string" + }, + "default": { + }, + multipleOf: { + type: "number", + minimum: 0, + exclusiveMinimum: true + }, + maximum: { + type: "number" + }, + exclusiveMaximum: { + type: "boolean", + "default": false + }, + minimum: { + type: "number" + }, + exclusiveMinimum: { + type: "boolean", + "default": false + }, + maxLength: { + $ref: "#/definitions/positiveInteger" + }, + minLength: { + $ref: "#/definitions/positiveIntegerDefault0" + }, + pattern: { + type: "string", + format: "regex" + }, + additionalItems: { + anyOf: [ + { + type: "boolean" + }, + { + $ref: "#" + } + ], + "default": { + } + }, + items: { + anyOf: [ + { + $ref: "#" + }, + { + $ref: "#/definitions/schemaArray" + } + ], + "default": { + } + }, + maxItems: { + $ref: "#/definitions/positiveInteger" + }, + minItems: { + $ref: "#/definitions/positiveIntegerDefault0" + }, + uniqueItems: { + type: "boolean", + "default": false + }, + maxProperties: { + $ref: "#/definitions/positiveInteger" + }, + minProperties: { + $ref: "#/definitions/positiveIntegerDefault0" + }, + required: { + $ref: "#/definitions/stringArray" + }, + additionalProperties: { + anyOf: [ + { + type: "boolean" + }, + { + $ref: "#" + } + ], + "default": { + } + }, + definitions: { + type: "object", + additionalProperties: { + $ref: "#" + }, + "default": { + } + }, + properties: { + type: "object", + additionalProperties: { + $ref: "#" + }, + "default": { + } + }, + patternProperties: { + type: "object", + additionalProperties: { + $ref: "#" + }, + "default": { + } + }, + dependencies: { + type: "object", + additionalProperties: { + anyOf: [ + { + $ref: "#" + }, + { + $ref: "#/definitions/stringArray" + } + ] + } + }, + "enum": { + type: "array", + minItems: 1, + uniqueItems: true + }, + type: { + anyOf: [ + { + $ref: "#/definitions/simpleTypes" + }, + { + type: "array", + items: { + $ref: "#/definitions/simpleTypes" + }, + minItems: 1, + uniqueItems: true + } + ] + }, + allOf: { + $ref: "#/definitions/schemaArray" + }, + anyOf: { + $ref: "#/definitions/schemaArray" + }, + oneOf: { + $ref: "#/definitions/schemaArray" + }, + not: { + $ref: "#" + } +}; +var dependencies$1 = { + exclusiveMaximum: [ + "maximum" + ], + exclusiveMinimum: [ + "minimum" + ] +}; +var require$$3$1 = { + id: id, + $schema: $schema, + description: description$1, + definitions: definitions, + type: type, + properties: properties$1, + dependencies: dependencies$1, + "default": { +} +}; + +(function (module, exports) { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0; + const core_1 = core$6; + const draft4_1 = draft4; + const discriminator_1 = discriminator; + const draft4MetaSchema = require$$3$1; + const META_SUPPORT_DATA = ["/properties"]; + const META_SCHEMA_ID = "http://json-schema.org/draft-04/schema"; + class Ajv extends core_1.default { + constructor(opts = {}) { + super({ + ...opts, + schemaId: "id", + }); + } + _addVocabularies() { + super._addVocabularies(); + draft4_1.default.forEach((v) => this.addVocabulary(v)); + if (this.opts.discriminator) + this.addKeyword(discriminator_1.default); + } + _addDefaultMetaSchema() { + super._addDefaultMetaSchema(); + if (!this.opts.meta) + return; + const metaSchema = this.opts.$data + ? this.$dataMetaSchema(draft4MetaSchema, META_SUPPORT_DATA) + : draft4MetaSchema; + this.addMetaSchema(metaSchema, META_SCHEMA_ID, false); + this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; + } + defaultMeta() { + return (this.opts.defaultMeta = + super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined)); + } + } + module.exports = exports = Ajv; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.default = Ajv; + var core_2 = core$6; + Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function () { return core_2.KeywordCxt; } }); + var core_3 = core$6; + Object.defineProperty(exports, "_", { enumerable: true, get: function () { return core_3._; } }); + Object.defineProperty(exports, "str", { enumerable: true, get: function () { return core_3.str; } }); + Object.defineProperty(exports, "stringify", { enumerable: true, get: function () { return core_3.stringify; } }); + Object.defineProperty(exports, "nil", { enumerable: true, get: function () { return core_3.nil; } }); + Object.defineProperty(exports, "Name", { enumerable: true, get: function () { return core_3.Name; } }); + Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function () { return core_3.CodeGen; } }); + +} (dist$1, dist$1.exports)); + +var distExports = dist$1.exports; + +const { openapi: openapi$1 } = libExports$1; +const { ono: ono$3 } = require$$0$3; +const betterAjvErrors = libExports; +const Ajv = _2020Exports; +const AjvDraft4 = distExports; + +const { getSpecificationName } = util$9; + +/** + * We've had issues with specs larger than 2MB+ with 1,000+ errors causing memory leaks so if we + * have a spec with more than `LARGE_SPEC_ERROR_CAP` errors and it's **stringified** length is + * larger than `LARGE_SPEC_LIMITS` then we will only return the first `LARGE_SPEC_ERROR_CAP` errors. + * + * Ideally we'd be looking at the byte size of the spec instead of looking at its stringified + * length value but the Blob API, which we'd use to get its size with `new Blob([str]).size;`, was + * only recently introduced in Node 15. + * + * w/r/t the 5,000,000 limit here: The spec we found causing these memory leaks had a size of + * 13,934,323 so 5mil seems like a decent cap to start with. + * + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Blob} + */ +const LARGE_SPEC_ERROR_CAP = 20; +const LARGE_SPEC_SIZE_CAP = 5000000; + +var schema = validateSchema$3; + +/** + * Validates the given Swagger API against the Swagger 2.0 or OpenAPI 3.0 and 3.1 schemas. + * + * @param {SwaggerObject} api + * @param {Object} options + */ +function validateSchema$3(api, options) { + let ajv; + + // Choose the appropriate schema (Swagger or OpenAPI) + let schema; + + if (api.swagger) { + schema = openapi$1.v2; + ajv = initializeAjv(); + } else if (api.openapi.startsWith('3.1')) { + schema = openapi$1.v31; + + // There's a bug with Ajv in how it handles `$dynamicRef` in the way that it's used within the 3.1 schema so we + // need to do some adhoc workarounds. + // https://github.com/OAI/OpenAPI-Specification/issues/2689 + // https://github.com/ajv-validator/ajv/issues/1573 + const schemaDynamicRef = schema.$defs.schema; + delete schemaDynamicRef.$dynamicAnchor; + + schema.$defs.components.properties.schemas.additionalProperties = schemaDynamicRef; + schema.$defs.header.dependentSchemas.schema.properties.schema = schemaDynamicRef; + schema.$defs['media-type'].properties.schema = schemaDynamicRef; + schema.$defs.parameter.properties.schema = schemaDynamicRef; + + ajv = initializeAjv(false); + } else { + schema = openapi$1.v3; + ajv = initializeAjv(); + } + + // Validate against the schema + const isValid = ajv.validate(schema, api); + if (!isValid) { + const err = ajv.errors; + + let additionalErrors = 0; + let reducedErrors = reduceAjvErrors(err); + if (reducedErrors.length >= LARGE_SPEC_ERROR_CAP) { + try { + if (JSON.stringify(api).length >= LARGE_SPEC_SIZE_CAP) { + additionalErrors = reducedErrors.length - 20; + reducedErrors = reducedErrors.slice(0, 20); + } + } catch (err) { + // If we failed to stringify the API definition to look at its size then we should process + // all of its errors as-is. + } + } + + let message = `${getSpecificationName(api)} schema validation failed.\n`; + message += '\n'; + message += betterAjvErrors(schema, api, reducedErrors, { + colorize: options.validate.colorizeErrors, + indent: 2, + }); + + if (additionalErrors) { + message += '\n\n'; + message += `Plus an additional ${additionalErrors} errors. Please resolve the above and re-run validation to see more.`; + } + + throw ono$3.syntax(err, { details: err }, message); + } +} + +/** + * Determines which version of Ajv to load and prepares it for use. + * + * @param {bool} draft04 + * @returns {Ajv} + */ +function initializeAjv(draft04 = true) { + const opts = { + allErrors: true, + strict: false, + validateFormats: false, + }; + + if (draft04) { + return new AjvDraft4(opts); + } + + return new Ajv(opts); +} + +/** + * Because of the way that Ajv works, if a validation error occurs deep within a schema there's a chance that errors + * will also be thrown for its immediate parents, leading to a case where we'll eventually show the error indecipherable + * errors like "$ref is missing here!" instance of what's _actually_ going on where they may have mistyped `enum` as + * `enumm`. + * + * To alleviate this confusing noise, we're compressing Ajv errors down to only surface the deepest point for each + * lineage, so that if a user typos `enum` as `enumm` we'll surface just that error for them (because really that's + * **the** error). + * + * @param {Array} errors + * @returns {Array} + */ +function reduceAjvErrors(errors) { + const flattened = new Map(); + + errors.forEach(err => { + // These two errors appear when a child schema of them has a problem and instead of polluting the user with + // indecipherable noise we should instead relay the more specific error to them. If this is all that's present in + // the stack then as a safety net before we wrap up we'll just return the original `errors` stack. + if (["must have required property '$ref'", 'must match exactly one schema in oneOf'].includes(err.message)) { + return; + } + + // If this is our first run through let's initialize our dataset and move along. + if (!flattened.size) { + flattened.set(err.instancePath, err); + return; + } else if (flattened.has(err.instancePath)) { + // If we already have an error recorded for this `instancePath` we can ignore it because we (likely) already have + // recorded the more specific error. + return; + } + + // If this error hasn't already been recorded, maybe it's an error against the same `instancePath` stack, in which + // case we should ignore it because the more specific error has already been recorded. + let shouldRecordError = true; + flattened.forEach(flat => { + if (flat.instancePath.includes(err.instancePath)) { + shouldRecordError = false; + } + }); + + if (shouldRecordError) { + flattened.set(err.instancePath, err); + } + }); + + // If we weren't able to fold errors down for whatever reason just return the original stack. + if (!flattened.size) { + return errors; + } + + return [...flattened.values()]; +} + +var lib$b = [ + "get", "put", "post", "delete", "options", "head", "patch" +]; + +const swaggerMethods$1 = lib$b; +const { ono: ono$2 } = require$$0$3; + +const util$5 = util$9; + +var openapi = validateSpec$2; + +/** + * Validates parts of the OpenAPI 3.0 and 3.1 that aren't covered by their JSON Schema definitions. + * + * @todo This library currently does not validate required properties like the Swagger validator does due to some + * gnarly quirks with cases where a required property exists within a `oneOf` or `anyOf` (and within a child `allOf` + * of one of those). See https://api.apis.guru/v2/specs/twitter.com/labs/2.13/openapi.yaml for a good example. + * + * @param {SwaggerObject} api + * @link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md + * @link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md + */ +function validateSpec$2(api) { + const operationIds = []; + Object.keys(api.paths || {}).forEach(pathName => { + const path = api.paths[pathName]; + const pathId = `/paths${pathName}`; + + if (path && pathName.indexOf('/') === 0) { + validatePath$1(api, path, pathId, operationIds); + } + }); + + // There's a problem with how the 3.0 schema uses `patternProperties` for defining the format of scheme names that it + // ignores anything that doesn't match, so if you for example have a space in a schema name it'll be seen as valid + // when it should instead trigger a validation error. + // + // https://github.com/APIDevTools/swagger-parser/issues/184 + if (api.openapi.startsWith('3.0')) { + if (api.components) { + Object.keys(api.components).forEach(componentType => { + Object.keys(api.components[componentType]).forEach(componentName => { + const componentId = `/components/${componentType}/${componentName}`; + + if (!/^[a-zA-Z0-9.\-_]+$/.test(componentName)) { + throw ono$2.syntax( + `Validation failed. ${componentId} has an invalid name. Component names should match against: /^[a-zA-Z0-9.-_]+$/` + ); + } + }); + }); + } + } +} + +/** + * Validates the given path. + * + * @param {SwaggerObject} api - The entire OpenAPI API definition + * @param {object} path - A Path object, from the OpenAPI API definition + * @param {string} pathId - A value that uniquely identifies the path + * @param {string} operationIds - An array of collected operationIds found in other paths + */ +function validatePath$1(api, path, pathId, operationIds) { + // `@apidevtools/swagger-methods` doesn't ship a `trace` method so we need to improvise. + [...swaggerMethods$1, 'trace'].forEach(operationName => { + const operation = path[operationName]; + const operationId = `${pathId}/${operationName}`; + + if (operation) { + const declaredOperationId = operation.operationId; + if (declaredOperationId) { + if (operationIds.indexOf(declaredOperationId) === -1) { + operationIds.push(declaredOperationId); + } else { + throw ono$2.syntax(`Validation failed. Duplicate operation id '${declaredOperationId}'`); + } + } + + validateParameters$1(api, path, pathId, operation, operationId); + + Object.keys(operation.responses || {}).forEach(responseCode => { + const response = operation.responses[responseCode]; + const responseId = `${operationId}/responses/${responseCode}`; + validateResponse$1(responseCode, response || {}, responseId); + }); + } + }); +} + +/** + * Validates the parameters for the given operation. + * + * @param {SwaggerObject} api - The entire Swagger API object + * @param {object} path - A Path object, from the Swagger API + * @param {string} pathId - A value that uniquely identifies the path + * @param {object} operation - An Operation object, from the Swagger API + * @param {string} operationId - A value that uniquely identifies the operation + */ +function validateParameters$1(api, path, pathId, operation, operationId) { + const pathParams = path.parameters || []; + const operationParams = operation.parameters || []; + + // Check for duplicate path parameters. + try { + checkForDuplicates$1(pathParams); + } catch (e) { + throw ono$2.syntax(e, `Validation failed. ${pathId} has duplicate parameters`); + } + + // Check for duplicate operation parameters. + try { + checkForDuplicates$1(operationParams); + } catch (e) { + throw ono$2.syntax(e, `Validation failed. ${operationId} has duplicate parameters`); + } + + // Combine the path and operation parameters, with the operation params taking precedence over the path params. + const params = pathParams.reduce((combinedParams, value) => { + const duplicate = combinedParams.some(param => { + return param.in === value.in && param.name === value.name; + }); + + if (!duplicate) { + combinedParams.push(value); + } + + return combinedParams; + }, operationParams.slice()); + + validatePathParameters$1(params, pathId, operationId); + validateParameterTypes$1(params, api, operation, operationId); +} + +/** + * Validates path parameters for the given path. + * + * @param {object[]} params - An array of Parameter objects + * @param {string} pathId - A value that uniquely identifies the path + * @param {string} operationId - A value that uniquely identifies the operation + */ +function validatePathParameters$1(params, pathId, operationId) { + // Find all `{placeholders}` in the path string. And because paths can have path parameters duped we need to convert + // this to a unique array so we can eliminate false positives of placeholders that might be duplicated. + const placeholders = [...new Set(pathId.match(util$5.swaggerParamRegExp) || [])]; + + params + .filter(param => param.in === 'path') + .forEach(param => { + if (param.required !== true) { + throw ono$2.syntax( + 'Validation failed. Path parameters cannot be optional. ' + + `Set required=true for the "${param.name}" parameter at ${operationId}` + ); + } + + const match = placeholders.indexOf(`{${param.name}}`); + if (match === -1) { + throw ono$2.syntax( + `Validation failed. ${operationId} has a path parameter named "${param.name}", ` + + `but there is no corresponding {${param.name}} in the path string` + ); + } + + placeholders.splice(match, 1); + }); + + if (placeholders.length > 0) { + throw ono$2.syntax(`Validation failed. ${operationId} is missing path parameter(s) for ${placeholders}`); + } +} + +/** + * Validates data types of parameters for the given operation. + * + * @param {object[]} params - An array of Parameter objects + * @param {object} api - The entire Swagger API object + * @param {object} operation - An Operation object, from the Swagger API + * @param {string} operationId - A value that uniquely identifies the operation + */ +function validateParameterTypes$1(params, api, operation, operationId) { + params.forEach(param => { + /** + * @todo add better handling when `content` is present instead of `schema`. + * @link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#fixed-fields-10 + * @link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#fixed-fields-10 + */ + if (!param.schema && param.content) { + return; + } + + const parameterId = `${operationId}/parameters/${param.name}`; + + validateSchema$2(param.schema, parameterId); + }); +} + +/** + * Checks the given parameter list for duplicates, and throws an error if found. + * + * @param {object[]} params - An array of Parameter objects + */ +function checkForDuplicates$1(params) { + for (let i = 0; i < params.length - 1; i++) { + const outer = params[i]; + for (let j = i + 1; j < params.length; j++) { + const inner = params[j]; + if (outer.name === inner.name && outer.in === inner.in) { + throw ono$2.syntax(`Validation failed. Found multiple ${outer.in} parameters named "${outer.name}"`); + } + } + } +} + +/** + * Validates the given response object. + * + * @param {string} code - The HTTP response code (or "default") + * @param {object} response - A Response object, from the Swagger API + * @param {string} responseId - A value that uniquely identifies the response + */ +function validateResponse$1(code, response, responseId) { + Object.keys(response.headers || {}).forEach(headerName => { + const header = response.headers[headerName]; + const headerId = `${responseId}/headers/${headerName}`; + + if (header.schema) { + validateSchema$2(header.schema, headerId); + } else if (header.content) { + Object.keys(header.content).forEach(mediaType => { + if (header.content[mediaType].schema) { + validateSchema$2(header.content[mediaType].schema || {}, `${headerId}/content/${mediaType}/schema`); + } + }); + } + }); + + if (response.content) { + Object.keys(response.content).forEach(mediaType => { + if (response.content[mediaType].schema) { + validateSchema$2(response.content[mediaType].schema || {}, `${responseId}/content/${mediaType}/schema`); + } + }); + } +} + +/** + * Validates the given Swagger schema object. + * + * @param {object} schema - A Schema object, from the Swagger API + * @param {string} schemaId - A value that uniquely identifies the schema object + */ +function validateSchema$2(schema, schemaId) { + if (schema.type === 'array' && !schema.items) { + throw ono$2.syntax(`Validation failed. ${schemaId} is an array, so it must include an "items" schema`); + } +} + +const swaggerMethods = lib$b; +const { ono: ono$1 } = require$$0$3; + +const util$4 = util$9; + +const primitiveTypes = ['array', 'boolean', 'integer', 'number', 'string']; +const schemaTypes = ['array', 'boolean', 'integer', 'number', 'string', 'object', 'null', undefined]; + +var swagger = validateSpec$1; + +/** + * Validates parts of the Swagger 2.0 spec that aren't covered by the Swagger 2.0 JSON Schema. + * + * @param {SwaggerObject} api + */ +function validateSpec$1(api) { + const operationIds = []; + Object.keys(api.paths || {}).forEach(pathName => { + const path = api.paths[pathName]; + const pathId = `/paths${pathName}`; + + if (path && pathName.indexOf('/') === 0) { + validatePath(api, path, pathId, operationIds); + } + }); + + Object.keys(api.definitions || {}).forEach(definitionName => { + const definition = api.definitions[definitionName]; + const definitionId = `/definitions/${definitionName}`; + + if (!/^[a-zA-Z0-9.\-_]+$/.test(definitionName)) { + throw ono$1.syntax( + `Validation failed. ${definitionId} has an invalid name. Definition names should match against: /^[a-zA-Z0-9.-_]+$/` + ); + } + + validateRequiredPropertiesExist(definition, definitionId); + }); +} + +/** + * Validates the given path. + * + * @param {SwaggerObject} api - The entire Swagger API object + * @param {object} path - A Path object, from the Swagger API + * @param {string} pathId - A value that uniquely identifies the path + * @param {string} operationIds - An array of collected operationIds found in other paths + */ +function validatePath(api, path, pathId, operationIds) { + swaggerMethods.forEach(operationName => { + const operation = path[operationName]; + const operationId = `${pathId}/${operationName}`; + + if (operation) { + const declaredOperationId = operation.operationId; + if (declaredOperationId) { + if (operationIds.indexOf(declaredOperationId) === -1) { + operationIds.push(declaredOperationId); + } else { + throw ono$1.syntax(`Validation failed. Duplicate operation id '${declaredOperationId}'`); + } + } + validateParameters(api, path, pathId, operation, operationId); + + Object.keys(operation.responses || {}).forEach(responseName => { + const response = operation.responses[responseName]; + const responseId = `${operationId}/responses/${responseName}`; + validateResponse(responseName, response || {}, responseId); + }); + } + }); +} + +/** + * Validates the parameters for the given operation. + * + * @param {SwaggerObject} api - The entire Swagger API object + * @param {object} path - A Path object, from the Swagger API + * @param {string} pathId - A value that uniquely identifies the path + * @param {object} operation - An Operation object, from the Swagger API + * @param {string} operationId - A value that uniquely identifies the operation + */ +function validateParameters(api, path, pathId, operation, operationId) { + const pathParams = path.parameters || []; + const operationParams = operation.parameters || []; + + // Check for duplicate path parameters + try { + checkForDuplicates(pathParams); + } catch (e) { + throw ono$1.syntax(e, `Validation failed. ${pathId} has duplicate parameters`); + } + + // Check for duplicate operation parameters + try { + checkForDuplicates(operationParams); + } catch (e) { + throw ono$1.syntax(e, `Validation failed. ${operationId} has duplicate parameters`); + } + + // Combine the path and operation parameters, + // with the operation params taking precedence over the path params + const params = pathParams.reduce((combinedParams, value) => { + const duplicate = combinedParams.some(param => { + return param.in === value.in && param.name === value.name; + }); + if (!duplicate) { + combinedParams.push(value); + } + return combinedParams; + }, operationParams.slice()); + + validateBodyParameters(params, operationId); + validatePathParameters(params, pathId, operationId); + validateParameterTypes(params, api, operation, operationId); +} + +/** + * Validates body and formData parameters for the given operation. + * + * @param {object[]} params - An array of Parameter objects + * @param {string} operationId - A value that uniquely identifies the operation + */ +function validateBodyParameters(params, operationId) { + const bodyParams = params.filter(param => { + return param.in === 'body'; + }); + const formParams = params.filter(param => { + return param.in === 'formData'; + }); + + // There can only be one "body" parameter + if (bodyParams.length > 1) { + throw ono$1.syntax( + `Validation failed. ${operationId} has ${bodyParams.length} body parameters. Only one is allowed.` + ); + } else if (bodyParams.length > 0 && formParams.length > 0) { + // "body" params and "formData" params are mutually exclusive + throw ono$1.syntax( + `Validation failed. ${operationId} has body parameters and formData parameters. Only one or the other is allowed.` + ); + } +} + +/** + * Validates path parameters for the given path. + * + * @param {object[]} params - An array of Parameter objects + * @param {string} pathId - A value that uniquely identifies the path + * @param {string} operationId - A value that uniquely identifies the operation + */ +function validatePathParameters(params, pathId, operationId) { + // Find all {placeholders} in the path string + const placeholders = pathId.match(util$4.swaggerParamRegExp) || []; + + // Check for duplicates + for (let i = 0; i < placeholders.length; i++) { + for (let j = i + 1; j < placeholders.length; j++) { + if (placeholders[i] === placeholders[j]) { + throw ono$1.syntax(`Validation failed. ${operationId} has multiple path placeholders named ${placeholders[i]}`); + } + } + } + + params + .filter(param => param.in === 'path') + .forEach(param => { + if (param.required !== true) { + throw ono$1.syntax( + 'Validation failed. Path parameters cannot be optional. ' + + `Set required=true for the "${param.name}" parameter at ${operationId}` + ); + } + + const match = placeholders.indexOf(`{${param.name}}`); + if (match === -1) { + throw ono$1.syntax( + `Validation failed. ${operationId} has a path parameter named "${param.name}", ` + + `but there is no corresponding {${param.name}} in the path string` + ); + } + + placeholders.splice(match, 1); + }); + + if (placeholders.length > 0) { + throw ono$1.syntax(`Validation failed. ${operationId} is missing path parameter(s) for ${placeholders}`); + } +} + +/** + * Validates data types of parameters for the given operation. + * + * @param {object[]} params - An array of Parameter objects + * @param {object} api - The entire Swagger API object + * @param {object} operation - An Operation object, from the Swagger API + * @param {string} operationId - A value that uniquely identifies the operation + */ +function validateParameterTypes(params, api, operation, operationId) { + params.forEach(param => { + const parameterId = `${operationId}/parameters/${param.name}`; + let schema; + let validTypes; + + switch (param.in) { + case 'body': + schema = param.schema; + validTypes = schemaTypes; + break; + case 'formData': + schema = param; + validTypes = primitiveTypes.concat('file'); + break; + default: + schema = param; + validTypes = primitiveTypes; + } + + validateSchema$1(schema, parameterId, validTypes); + validateRequiredPropertiesExist(schema, parameterId); + + if (schema.type === 'file') { + // "file" params must consume at least one of these MIME types + const formData = /multipart\/(.*\+)?form-data/; // eslint-disable-line unicorn/no-unsafe-regex + const urlEncoded = /application\/(.*\+)?x-www-form-urlencoded/; // eslint-disable-line unicorn/no-unsafe-regex + + const consumes = operation.consumes || api.consumes || []; + + const hasValidMimeType = consumes.some(consume => { + return formData.test(consume) || urlEncoded.test(consume); + }); + + if (!hasValidMimeType) { + throw ono$1.syntax( + `Validation failed. ${operationId} has a file parameter, so it must consume multipart/form-data ` + + 'or application/x-www-form-urlencoded' + ); + } + } + }); +} + +/** + * Checks the given parameter list for duplicates, and throws an error if found. + * + * @param {object[]} params - An array of Parameter objects + */ +function checkForDuplicates(params) { + for (let i = 0; i < params.length - 1; i++) { + const outer = params[i]; + for (let j = i + 1; j < params.length; j++) { + const inner = params[j]; + if (outer.name === inner.name && outer.in === inner.in) { + throw ono$1.syntax(`Validation failed. Found multiple ${outer.in} parameters named "${outer.name}"`); + } + } + } +} + +/** + * Validates the given response object. + * + * @param {string} code - The HTTP response code (or "default") + * @param {object} response - A Response object, from the Swagger API + * @param {string} responseId - A value that uniquely identifies the response + */ +function validateResponse(code, response, responseId) { + if (code !== 'default' && (code < 100 || code > 599)) { + throw ono$1.syntax(`Validation failed. ${responseId} has an invalid response code (${code})`); + } + + Object.keys(response.headers || {}).forEach(headerName => { + const header = response.headers[headerName]; + const headerId = `${responseId}/headers/${headerName}`; + validateSchema$1(header, headerId, primitiveTypes); + }); + + if (response.schema) { + const validTypes = schemaTypes.concat('file'); + if (validTypes.indexOf(response.schema.type) === -1) { + throw ono$1.syntax( + `Validation failed. ${responseId} has an invalid response schema type (${response.schema.type})` + ); + } else { + validateSchema$1(response.schema, `${responseId}/schema`, validTypes); + } + } +} + +/** + * Validates the given Swagger schema object. + * + * @param {object} schema - A Schema object, from the Swagger API + * @param {string} schemaId - A value that uniquely identifies the schema object + * @param {string[]} validTypes - An array of the allowed schema types + */ +function validateSchema$1(schema, schemaId, validTypes) { + if (validTypes.indexOf(schema.type) === -1) { + throw ono$1.syntax(`Validation failed. ${schemaId} has an invalid type (${schema.type})`); + } + + if (schema.type === 'array' && !schema.items) { + throw ono$1.syntax(`Validation failed. ${schemaId} is an array, so it must include an "items" schema`); + } +} + +/** + * Validates that the declared properties of the given Swagger schema object actually exist. + * + * @param {object} schema - A Schema object, from the Swagger API + * @param {string} schemaId - A value that uniquely identifies the schema object + */ +function validateRequiredPropertiesExist(schema, schemaId) { + // Recursively collects all properties of the schema and its ancestors. They are added to the props object. + function collectProperties(schemaObj, props) { + if (schemaObj.properties) { + Object.keys(schemaObj.properties).forEach(property => { + // eslint-disable-next-line no-prototype-builtins + if (schemaObj.properties.hasOwnProperty(property)) { + // eslint-disable-next-line no-param-reassign + props[property] = schemaObj.properties[property]; + } + }); + } + + if (schemaObj.allOf) { + schemaObj.allOf.forEach(parent => { + collectProperties(parent, props); + }); + } + } + + if (schema.required && Array.isArray(schema.required)) { + const props = {}; + collectProperties(schema, props); + schema.required.forEach(requiredProperty => { + if (!props[requiredProperty]) { + throw ono$1.syntax( + `Validation failed. Property '${requiredProperty}' listed as required but does not exist in '${schemaId}'` + ); + } + }); + } +} + +const validateOpenAPI = openapi; +const validateSwagger = swagger; + +/** + * Validates either a Swagger 2.0 or OpenAPI 3.x API definition against cases that aren't covered by their JSON Schema + * definitions. + * + * @param {SwaggerObject} api + */ +var spec = function validateSpec(api) { + if (api.openapi) { + return validateOpenAPI(api); + } + + return validateSwagger(api); +}; + +const $RefParserOptions = options$1; + +const util$3 = util$9; +const schemaValidator = schema; +const specValidator = spec; + +var options = ParserOptions; + +/** + * Options that determine how Swagger APIs are parsed, resolved, dereferenced, and validated. + * + * @param {object|ParserOptions} [_options] - Overridden options + * @class + * @augments $RefParserOptions + */ +// eslint-disable-next-line no-unused-vars +function ParserOptions(_options) { + $RefParserOptions.call(this, ParserOptions.defaults); + $RefParserOptions.apply(this, arguments); +} + +ParserOptions.defaults = { + /** + * Determines how the API definition will be validated. + * + * You can add additional validators of your own, replace an existing one with + * your own implemenation, or disable any validator by setting it to false. + */ + validate: { + colorizeErrors: false, + schema: schemaValidator, + spec: specValidator, + }, +}; + +util$3.inherits(ParserOptions, $RefParserOptions); + +/* eslint-disable no-unused-vars */ + +const { ono } = require$$0$3; +const $RefParser = libExports$2; +const dereference$1 = dereference$2; +const normalizeArgs = normalizeArgs$2; +const maybe$1 = maybe$3; + +const Options = options; +const util$2 = util$9; +const validateSchema = schema; +const validateSpec = spec; + +var lib$a = OpenAPIParser; + +/** + * This class parses a Swagger 2.0 or 3.0 API, resolves its JSON references and their resolved values, + * and provides methods for traversing, dereferencing, and validating the API. + * + * @class + * @augments $RefParser + */ +function OpenAPIParser() { + $RefParser.apply(this, arguments); +} + +util$2.inherits(OpenAPIParser, $RefParser); +OpenAPIParser.parse = $RefParser.parse; +OpenAPIParser.resolve = $RefParser.resolve; +OpenAPIParser.bundle = $RefParser.bundle; +OpenAPIParser.dereference = $RefParser.dereference; + +/** + * Alias {@link $RefParser#schema} as {@link OpenAPIParser#api} + */ +Object.defineProperty(OpenAPIParser.prototype, 'api', { + configurable: true, + enumerable: true, + get() { + return this.schema; + }, +}); + +/** + * Parses the given Swagger API. + * This method does not resolve any JSON references. + * It just reads a single file in JSON or YAML format, and parse it as a JavaScript object. + * + * @param {string} [path] - The file path or URL of the JSON schema + * @param {object} [api] - The Swagger API object. This object will be used instead of reading from `path`. + * @param {ParserOptions} [options] - Options that determine how the API is parsed + * @param {Function} [callback] - An error-first callback. The second parameter is the parsed API object. + * @returns {Promise} - The returned promise resolves with the parsed API object. + */ +OpenAPIParser.prototype.parse = async function (path, api, options, callback) { + const args = normalizeArgs(arguments); + args.options = new Options(args.options); + + try { + const schema = await $RefParser.prototype.parse.call(this, args.path, args.schema, args.options); + + if (schema.swagger) { + // Verify that the parsed object is a Swagger API + if (schema.swagger === undefined || schema.info === undefined || schema.paths === undefined) { + throw ono.syntax(`${args.path || 'Supplied schema'} is not a valid Swagger API definition.`); + } else if (typeof schema.swagger === 'number') { + // This is a very common mistake, so give a helpful error message + throw ono.syntax('Swagger version number must be a string (e.g. "2.0") not a number.'); + } else if (typeof schema.info.version === 'number') { + // This is a very common mistake, so give a helpful error message + throw ono.syntax('API version number must be a string (e.g. "1.0.0") not a number.'); + } else if (schema.swagger !== '2.0') { + throw ono.syntax(`Unrecognized Swagger version: ${schema.swagger}. Expected 2.0`); + } + } else { + const supportedVersions = ['3.0.0', '3.0.1', '3.0.2', '3.0.3', '3.1.0']; + + // Verify that the parsed object is an OpenAPI definition + if (schema.openapi === undefined || schema.info === undefined) { + throw ono.syntax(`${args.path || 'Supplied schema'} is not a valid OpenAPI definition.`); + } else if (schema.paths === undefined) { + if (schema.openapi === '3.1.0') { + if (schema.webhooks === undefined) { + throw ono.syntax(`${args.path || 'Supplied schema'} is not a valid OpenAPI definition.`); + } + } else { + throw ono.syntax(`${args.path || 'Supplied schema'} is not a valid OpenAPI definition.`); + } + } else if (typeof schema.openapi === 'number') { + // This is a very common mistake, so give a helpful error message + throw ono.syntax('OpenAPI version number must be a string (e.g. "3.0.0") not a number.'); + } else if (typeof schema.info.version === 'number') { + // This is a very common mistake, so give a helpful error message + throw ono.syntax('API version number must be a string (e.g. "1.0.0") not a number.'); + } else if (supportedVersions.indexOf(schema.openapi) === -1) { + throw ono.syntax( + `Unsupported OpenAPI version: ${schema.openapi}. ` + + `Swagger Parser only supports versions ${supportedVersions.join(', ')}` + ); + } + + // This is an OpenAPI v3 schema, check if the "servers" have any relative paths and + // fix them if the content was pulled from a web resource + util$2.fixOasRelativeServers(schema, args.path); + } + + // Looks good! + return maybe$1(args.callback, Promise.resolve(schema)); + } catch (err) { + return maybe$1(args.callback, Promise.reject(err)); + } +}; + +/** + * Parses, dereferences, and validates the given Swagger API. + * Depending on the options, validation can include JSON Schema validation and/or Swagger Spec validation. + * + * @param {string} [path] - The file path or URL of the JSON schema + * @param {object} [api] - The Swagger API object. This object will be used instead of reading from `path`. + * @param {ParserOptions} [options] - Options that determine how the API is parsed, dereferenced, and validated + * @param {Function} [callback] - An error-first callback. The second parameter is the parsed API object. + * @returns {Promise} - The returned promise resolves with the parsed API object. + */ +OpenAPIParser.validate = function (path, api, options, callback) { + const Class = this; + const instance = new Class(); + return instance.validate.apply(instance, arguments); +}; + +/** + * Parses, dereferences, and validates the given Swagger API. + * Depending on the options, validation can include JSON Schema validation and/or Swagger Spec validation. + * + * @param {string} [path] - The file path or URL of the JSON schema + * @param {object} [api] - The Swagger API object. This object will be used instead of reading from `path`. + * @param {ParserOptions} [options] - Options that determine how the API is parsed, dereferenced, and validated + * @param {Function} [callback] - An error-first callback. The second parameter is the parsed API object. + * @returns {Promise} - The returned promise resolves with the parsed API object. + */ +OpenAPIParser.prototype.validate = async function (path, api, options, callback) { + const me = this; + const args = normalizeArgs(arguments); + args.options = new Options(args.options); + + // ZSchema doesn't support circular objects, so don't dereference circular $refs yet + // (see https://github.com/zaggino/z-schema/issues/137) + const circular$RefOption = args.options.dereference.circular; + if (args.options.validate.schema) { + args.options.dereference.circular = 'ignore'; + } + + try { + await this.dereference(args.path, args.schema, args.options); + + // Restore the original options, now that we're done dereferencing + args.options.dereference.circular = circular$RefOption; + + if (args.options.validate.schema) { + // Validate the API against the Swagger schema + // NOTE: This is safe to do, because we haven't dereferenced circular $refs yet + validateSchema(me.api, args.options); + + if (me.$refs.circular) { + if (circular$RefOption === true) { + // The API has circular references, + // so we need to do a second-pass to fully-dereference it + dereference$1(me, args.options); + } else if (circular$RefOption === false) { + // The API has circular references, and they're not allowed, so throw an error + throw ono.reference('The API contains circular references'); + } + } + } + + if (args.options.validate.spec) { + // Validate the API against the Swagger spec + validateSpec(me.api); + } + + return maybe$1(args.callback, Promise.resolve(me.schema)); + } catch (err) { + return maybe$1(args.callback, Promise.reject(err)); + } +}; + +/** + * The Swagger object + * https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#swagger-object + * + * @typedef {{swagger: string, info: {}, paths: {}}} SwaggerObject + */ + +var openapiParser = /*@__PURE__*/getDefaultExportFromCjs(lib$a); + +// https://github.com/nodejs/node/blob/master/lib/_http_server.js + +const codes = { + default: ['Default', true], + + '1XX': ['Informational', true], + 100: ['Continue', true], + 101: ['Switching Protocols', true], + 102: ['Processing', true], + 103: ['Early Hints', true], // Also informally used as "Checkpoint". + + '2XX': ['Success', true], + 200: ['OK', true], + 201: ['Created', true], + 202: ['Accepted', true], + 203: ['Non-Authoritative Information', true], + 204: ['No Content', true], + 205: ['Reset Content', true], + 206: ['Partial Content', true], + 207: ['Multi-Status', true], + 208: ['Already Reported', true], + 218: ['This is fine', true], // Unofficial + 226: ['IM Used', true], + + '3XX': ['Redirection', true], + 300: ['Multiple Choices', true], + 301: ['Moved Permanently', true], + 302: ['Found', true], + 303: ['See Other', true], + 304: ['Not Modified', true], + 305: ['Use Proxy', true], + 306: ['Switch Proxy', true], + 307: ['Temporary Redirect', true], + 308: ['Permanent Redirect', true], + + '4XX': ['Client Error', false], + 400: ['Bad Request', false], + 401: ['Unauthorized', false], + 402: ['Payment Required', false], + 403: ['Forbidden', false], + 404: ['Not Found', false], + 405: ['Method Not Allowed', false], + 406: ['Not Acceptable', false], + 407: ['Proxy Authentication Required', false], + 408: ['Request Timeout', false], + 409: ['Conflict', false], + 410: ['Gone', false], + 411: ['Length Required', false], + 412: ['Precondition Failed', false], + 413: ['Payload Too Large', false], + 414: ['URI Too Long', false], + 415: ['Unsupported Media Type', false], + 416: ['Range Not Satisfiable', false], + 417: ['Expectation Failed', false], + 418: ["I'm a teapot", false], + 419: ['Page Expired', false], // Unofficial + 420: ['Enhance Your Calm', false], // Unofficial + 421: ['Misdirected Request', false], + 422: ['Unprocessable Entity', false], + 423: ['Locked', false], + 424: ['Failed Dependency', false], + 425: ['Too Early', false], + 426: ['Upgrade Required', false], + 428: ['Precondition Required', false], + 429: ['Too Many Requests', false], + 430: ['Request Header Fields Too Large', false], // Unofficial + 431: ['Request Header Fields Too Large', false], + 440: ['Login Time-out', false], // Unofficial + 444: ['No Response', false], // Unofficial + 449: ['Retry With', false], // Unofficial + 450: ['Blocked by Windows Parental Controls', false], // Unofficial + 451: ['Unavailable For Legal Reasons', false], + 494: ['Request Header Too Large', false], // Unofficial + 495: ['SSL Certificate Error', false], // Unofficial + 496: ['SSL Certificate Required', false], // Unofficial + 497: ['HTTP Request Sent to HTTPS Port', false], // Unofficial + 498: ['Invalid Token', false], // Unofficial + 499: ['Client Error', false], // "Token Request" on ArcGIS, "Client Closed Request" on nginx + + '5XX': ['Server Error', false], + 500: ['Internal Server Error', false], + 501: ['Not Implemented', false], + 502: ['Bad Gateway', false], + 503: ['Service Unavailable', false], + 504: ['Gateway Timeout', false], + 505: ['HTTP Version Not Supported', false], + 506: ['Variant Also Negotiates', false], + 507: ['Insufficient Storage', false], + 508: ['Loop Detected', false], + 509: ['Bandwidth Limit Exceeded', false], + 510: ['Not Extended', false], + 511: ['Network Authentication Required', false], + 520: ['Web Server Returned an Unknown Error', false], // Unofficial + 521: ['Web Server Is Down', false], // Unofficial + 522: ['Connection Timed Out', false], // Unofficial + 523: ['Origin Is Unreachable', false], // Unofficial + 524: ['A Timeout Occurred', false], // Unofficial + 525: ['SSL Handshake Failed', false], // Unofficial + 526: ['Invalid SSL Certificate', false], // Unofficial + 527: ['Railgun Error', false], // Unofficial + 529: ['Site is Overloaded', false], // Unofficial + 530: ['Site is Frozen', false], // Unofficial + 598: ['Network Read Timeout Error', false], // Unofficial +}; + +function isStatusCodeValid(code) { + return code in codes; +} + +function getStatusCode(code) { + if (!isStatusCodeValid(code)) { + throw new Error(`${code} is not a known HTTP status code.`); + } + + return { + // Since there's no HTTP status code that can really match up with `default`, code should just be empty. + code: code === 'default' ? '' : code, + message: codes[code][0], + success: codes[code][1], + }; +} + +function getStatusCodeMessage$1(code) { + const res = getStatusCode(code); + return `${res.code} ${res.message}`; +} + +function isStatusCodeSuccessful(code) { + try { + return getStatusCode(code).success; + } catch (e) { + return false; + } +} + +var src$4 = { + codes, + getStatusCode, + getStatusCodeMessage: getStatusCodeMessage$1, + isStatusCodeSuccessful, + isStatusCodeValid, +}; + +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +/** + * Creates a JSON scanner on the given text. + * If ignoreTrivia is set, whitespaces or comments are ignored. + */ +function createScanner$1(text, ignoreTrivia = false) { + const len = text.length; + let pos = 0, value = '', tokenOffset = 0, token = 16 /* SyntaxKind.Unknown */, lineNumber = 0, lineStartOffset = 0, tokenLineStartOffset = 0, prevTokenLineStartOffset = 0, scanError = 0 /* ScanError.None */; + function scanHexDigits(count, exact) { + let digits = 0; + let value = 0; + while (digits < count || !exact) { + let ch = text.charCodeAt(pos); + if (ch >= 48 /* CharacterCodes._0 */ && ch <= 57 /* CharacterCodes._9 */) { + value = value * 16 + ch - 48 /* CharacterCodes._0 */; + } + else if (ch >= 65 /* CharacterCodes.A */ && ch <= 70 /* CharacterCodes.F */) { + value = value * 16 + ch - 65 /* CharacterCodes.A */ + 10; + } + else if (ch >= 97 /* CharacterCodes.a */ && ch <= 102 /* CharacterCodes.f */) { + value = value * 16 + ch - 97 /* CharacterCodes.a */ + 10; + } + else { + break; + } + pos++; + digits++; + } + if (digits < count) { + value = -1; + } + return value; + } + function setPosition(newPosition) { + pos = newPosition; + value = ''; + tokenOffset = 0; + token = 16 /* SyntaxKind.Unknown */; + scanError = 0 /* ScanError.None */; + } + function scanNumber() { + let start = pos; + if (text.charCodeAt(pos) === 48 /* CharacterCodes._0 */) { + pos++; + } + else { + pos++; + while (pos < text.length && isDigit(text.charCodeAt(pos))) { + pos++; + } + } + if (pos < text.length && text.charCodeAt(pos) === 46 /* CharacterCodes.dot */) { + pos++; + if (pos < text.length && isDigit(text.charCodeAt(pos))) { + pos++; + while (pos < text.length && isDigit(text.charCodeAt(pos))) { + pos++; + } + } + else { + scanError = 3 /* ScanError.UnexpectedEndOfNumber */; + return text.substring(start, pos); + } + } + let end = pos; + if (pos < text.length && (text.charCodeAt(pos) === 69 /* CharacterCodes.E */ || text.charCodeAt(pos) === 101 /* CharacterCodes.e */)) { + pos++; + if (pos < text.length && text.charCodeAt(pos) === 43 /* CharacterCodes.plus */ || text.charCodeAt(pos) === 45 /* CharacterCodes.minus */) { + pos++; + } + if (pos < text.length && isDigit(text.charCodeAt(pos))) { + pos++; + while (pos < text.length && isDigit(text.charCodeAt(pos))) { + pos++; + } + end = pos; + } + else { + scanError = 3 /* ScanError.UnexpectedEndOfNumber */; + } + } + return text.substring(start, end); + } + function scanString() { + let result = '', start = pos; + while (true) { + if (pos >= len) { + result += text.substring(start, pos); + scanError = 2 /* ScanError.UnexpectedEndOfString */; + break; + } + const ch = text.charCodeAt(pos); + if (ch === 34 /* CharacterCodes.doubleQuote */) { + result += text.substring(start, pos); + pos++; + break; + } + if (ch === 92 /* CharacterCodes.backslash */) { + result += text.substring(start, pos); + pos++; + if (pos >= len) { + scanError = 2 /* ScanError.UnexpectedEndOfString */; + break; + } + const ch2 = text.charCodeAt(pos++); + switch (ch2) { + case 34 /* CharacterCodes.doubleQuote */: + result += '\"'; + break; + case 92 /* CharacterCodes.backslash */: + result += '\\'; + break; + case 47 /* CharacterCodes.slash */: + result += '/'; + break; + case 98 /* CharacterCodes.b */: + result += '\b'; + break; + case 102 /* CharacterCodes.f */: + result += '\f'; + break; + case 110 /* CharacterCodes.n */: + result += '\n'; + break; + case 114 /* CharacterCodes.r */: + result += '\r'; + break; + case 116 /* CharacterCodes.t */: + result += '\t'; + break; + case 117 /* CharacterCodes.u */: + const ch3 = scanHexDigits(4, true); + if (ch3 >= 0) { + result += String.fromCharCode(ch3); + } + else { + scanError = 4 /* ScanError.InvalidUnicode */; + } + break; + default: + scanError = 5 /* ScanError.InvalidEscapeCharacter */; + } + start = pos; + continue; + } + if (ch >= 0 && ch <= 0x1f) { + if (isLineBreak(ch)) { + result += text.substring(start, pos); + scanError = 2 /* ScanError.UnexpectedEndOfString */; + break; + } + else { + scanError = 6 /* ScanError.InvalidCharacter */; + // mark as error but continue with string + } + } + pos++; + } + return result; + } + function scanNext() { + value = ''; + scanError = 0 /* ScanError.None */; + tokenOffset = pos; + lineStartOffset = lineNumber; + prevTokenLineStartOffset = tokenLineStartOffset; + if (pos >= len) { + // at the end + tokenOffset = len; + return token = 17 /* SyntaxKind.EOF */; + } + let code = text.charCodeAt(pos); + // trivia: whitespace + if (isWhiteSpace(code)) { + do { + pos++; + value += String.fromCharCode(code); + code = text.charCodeAt(pos); + } while (isWhiteSpace(code)); + return token = 15 /* SyntaxKind.Trivia */; + } + // trivia: newlines + if (isLineBreak(code)) { + pos++; + value += String.fromCharCode(code); + if (code === 13 /* CharacterCodes.carriageReturn */ && text.charCodeAt(pos) === 10 /* CharacterCodes.lineFeed */) { + pos++; + value += '\n'; + } + lineNumber++; + tokenLineStartOffset = pos; + return token = 14 /* SyntaxKind.LineBreakTrivia */; + } + switch (code) { + // tokens: []{}:, + case 123 /* CharacterCodes.openBrace */: + pos++; + return token = 1 /* SyntaxKind.OpenBraceToken */; + case 125 /* CharacterCodes.closeBrace */: + pos++; + return token = 2 /* SyntaxKind.CloseBraceToken */; + case 91 /* CharacterCodes.openBracket */: + pos++; + return token = 3 /* SyntaxKind.OpenBracketToken */; + case 93 /* CharacterCodes.closeBracket */: + pos++; + return token = 4 /* SyntaxKind.CloseBracketToken */; + case 58 /* CharacterCodes.colon */: + pos++; + return token = 6 /* SyntaxKind.ColonToken */; + case 44 /* CharacterCodes.comma */: + pos++; + return token = 5 /* SyntaxKind.CommaToken */; + // strings + case 34 /* CharacterCodes.doubleQuote */: + pos++; + value = scanString(); + return token = 10 /* SyntaxKind.StringLiteral */; + // comments + case 47 /* CharacterCodes.slash */: + const start = pos - 1; + // Single-line comment + if (text.charCodeAt(pos + 1) === 47 /* CharacterCodes.slash */) { + pos += 2; + while (pos < len) { + if (isLineBreak(text.charCodeAt(pos))) { + break; + } + pos++; + } + value = text.substring(start, pos); + return token = 12 /* SyntaxKind.LineCommentTrivia */; + } + // Multi-line comment + if (text.charCodeAt(pos + 1) === 42 /* CharacterCodes.asterisk */) { + pos += 2; + const safeLength = len - 1; // For lookahead. + let commentClosed = false; + while (pos < safeLength) { + const ch = text.charCodeAt(pos); + if (ch === 42 /* CharacterCodes.asterisk */ && text.charCodeAt(pos + 1) === 47 /* CharacterCodes.slash */) { + pos += 2; + commentClosed = true; + break; + } + pos++; + if (isLineBreak(ch)) { + if (ch === 13 /* CharacterCodes.carriageReturn */ && text.charCodeAt(pos) === 10 /* CharacterCodes.lineFeed */) { + pos++; + } + lineNumber++; + tokenLineStartOffset = pos; + } + } + if (!commentClosed) { + pos++; + scanError = 1 /* ScanError.UnexpectedEndOfComment */; + } + value = text.substring(start, pos); + return token = 13 /* SyntaxKind.BlockCommentTrivia */; + } + // just a single slash + value += String.fromCharCode(code); + pos++; + return token = 16 /* SyntaxKind.Unknown */; + // numbers + case 45 /* CharacterCodes.minus */: + value += String.fromCharCode(code); + pos++; + if (pos === len || !isDigit(text.charCodeAt(pos))) { + return token = 16 /* SyntaxKind.Unknown */; + } + // found a minus, followed by a number so + // we fall through to proceed with scanning + // numbers + case 48 /* CharacterCodes._0 */: + case 49 /* CharacterCodes._1 */: + case 50 /* CharacterCodes._2 */: + case 51 /* CharacterCodes._3 */: + case 52 /* CharacterCodes._4 */: + case 53 /* CharacterCodes._5 */: + case 54 /* CharacterCodes._6 */: + case 55 /* CharacterCodes._7 */: + case 56 /* CharacterCodes._8 */: + case 57 /* CharacterCodes._9 */: + value += scanNumber(); + return token = 11 /* SyntaxKind.NumericLiteral */; + // literals and unknown symbols + default: + // is a literal? Read the full word. + while (pos < len && isUnknownContentCharacter(code)) { + pos++; + code = text.charCodeAt(pos); + } + if (tokenOffset !== pos) { + value = text.substring(tokenOffset, pos); + // keywords: true, false, null + switch (value) { + case 'true': return token = 8 /* SyntaxKind.TrueKeyword */; + case 'false': return token = 9 /* SyntaxKind.FalseKeyword */; + case 'null': return token = 7 /* SyntaxKind.NullKeyword */; + } + return token = 16 /* SyntaxKind.Unknown */; + } + // some + value += String.fromCharCode(code); + pos++; + return token = 16 /* SyntaxKind.Unknown */; + } + } + function isUnknownContentCharacter(code) { + if (isWhiteSpace(code) || isLineBreak(code)) { + return false; + } + switch (code) { + case 125 /* CharacterCodes.closeBrace */: + case 93 /* CharacterCodes.closeBracket */: + case 123 /* CharacterCodes.openBrace */: + case 91 /* CharacterCodes.openBracket */: + case 34 /* CharacterCodes.doubleQuote */: + case 58 /* CharacterCodes.colon */: + case 44 /* CharacterCodes.comma */: + case 47 /* CharacterCodes.slash */: + return false; + } + return true; + } + function scanNextNonTrivia() { + let result; + do { + result = scanNext(); + } while (result >= 12 /* SyntaxKind.LineCommentTrivia */ && result <= 15 /* SyntaxKind.Trivia */); + return result; + } + return { + setPosition: setPosition, + getPosition: () => pos, + scan: ignoreTrivia ? scanNextNonTrivia : scanNext, + getToken: () => token, + getTokenValue: () => value, + getTokenOffset: () => tokenOffset, + getTokenLength: () => pos - tokenOffset, + getTokenStartLine: () => lineStartOffset, + getTokenStartCharacter: () => tokenOffset - prevTokenLineStartOffset, + getTokenError: () => scanError, + }; +} +function isWhiteSpace(ch) { + return ch === 32 /* CharacterCodes.space */ || ch === 9 /* CharacterCodes.tab */; +} +function isLineBreak(ch) { + return ch === 10 /* CharacterCodes.lineFeed */ || ch === 13 /* CharacterCodes.carriageReturn */; +} +function isDigit(ch) { + return ch >= 48 /* CharacterCodes._0 */ && ch <= 57 /* CharacterCodes._9 */; +} +var CharacterCodes; +(function (CharacterCodes) { + CharacterCodes[CharacterCodes["lineFeed"] = 10] = "lineFeed"; + CharacterCodes[CharacterCodes["carriageReturn"] = 13] = "carriageReturn"; + CharacterCodes[CharacterCodes["space"] = 32] = "space"; + CharacterCodes[CharacterCodes["_0"] = 48] = "_0"; + CharacterCodes[CharacterCodes["_1"] = 49] = "_1"; + CharacterCodes[CharacterCodes["_2"] = 50] = "_2"; + CharacterCodes[CharacterCodes["_3"] = 51] = "_3"; + CharacterCodes[CharacterCodes["_4"] = 52] = "_4"; + CharacterCodes[CharacterCodes["_5"] = 53] = "_5"; + CharacterCodes[CharacterCodes["_6"] = 54] = "_6"; + CharacterCodes[CharacterCodes["_7"] = 55] = "_7"; + CharacterCodes[CharacterCodes["_8"] = 56] = "_8"; + CharacterCodes[CharacterCodes["_9"] = 57] = "_9"; + CharacterCodes[CharacterCodes["a"] = 97] = "a"; + CharacterCodes[CharacterCodes["b"] = 98] = "b"; + CharacterCodes[CharacterCodes["c"] = 99] = "c"; + CharacterCodes[CharacterCodes["d"] = 100] = "d"; + CharacterCodes[CharacterCodes["e"] = 101] = "e"; + CharacterCodes[CharacterCodes["f"] = 102] = "f"; + CharacterCodes[CharacterCodes["g"] = 103] = "g"; + CharacterCodes[CharacterCodes["h"] = 104] = "h"; + CharacterCodes[CharacterCodes["i"] = 105] = "i"; + CharacterCodes[CharacterCodes["j"] = 106] = "j"; + CharacterCodes[CharacterCodes["k"] = 107] = "k"; + CharacterCodes[CharacterCodes["l"] = 108] = "l"; + CharacterCodes[CharacterCodes["m"] = 109] = "m"; + CharacterCodes[CharacterCodes["n"] = 110] = "n"; + CharacterCodes[CharacterCodes["o"] = 111] = "o"; + CharacterCodes[CharacterCodes["p"] = 112] = "p"; + CharacterCodes[CharacterCodes["q"] = 113] = "q"; + CharacterCodes[CharacterCodes["r"] = 114] = "r"; + CharacterCodes[CharacterCodes["s"] = 115] = "s"; + CharacterCodes[CharacterCodes["t"] = 116] = "t"; + CharacterCodes[CharacterCodes["u"] = 117] = "u"; + CharacterCodes[CharacterCodes["v"] = 118] = "v"; + CharacterCodes[CharacterCodes["w"] = 119] = "w"; + CharacterCodes[CharacterCodes["x"] = 120] = "x"; + CharacterCodes[CharacterCodes["y"] = 121] = "y"; + CharacterCodes[CharacterCodes["z"] = 122] = "z"; + CharacterCodes[CharacterCodes["A"] = 65] = "A"; + CharacterCodes[CharacterCodes["B"] = 66] = "B"; + CharacterCodes[CharacterCodes["C"] = 67] = "C"; + CharacterCodes[CharacterCodes["D"] = 68] = "D"; + CharacterCodes[CharacterCodes["E"] = 69] = "E"; + CharacterCodes[CharacterCodes["F"] = 70] = "F"; + CharacterCodes[CharacterCodes["G"] = 71] = "G"; + CharacterCodes[CharacterCodes["H"] = 72] = "H"; + CharacterCodes[CharacterCodes["I"] = 73] = "I"; + CharacterCodes[CharacterCodes["J"] = 74] = "J"; + CharacterCodes[CharacterCodes["K"] = 75] = "K"; + CharacterCodes[CharacterCodes["L"] = 76] = "L"; + CharacterCodes[CharacterCodes["M"] = 77] = "M"; + CharacterCodes[CharacterCodes["N"] = 78] = "N"; + CharacterCodes[CharacterCodes["O"] = 79] = "O"; + CharacterCodes[CharacterCodes["P"] = 80] = "P"; + CharacterCodes[CharacterCodes["Q"] = 81] = "Q"; + CharacterCodes[CharacterCodes["R"] = 82] = "R"; + CharacterCodes[CharacterCodes["S"] = 83] = "S"; + CharacterCodes[CharacterCodes["T"] = 84] = "T"; + CharacterCodes[CharacterCodes["U"] = 85] = "U"; + CharacterCodes[CharacterCodes["V"] = 86] = "V"; + CharacterCodes[CharacterCodes["W"] = 87] = "W"; + CharacterCodes[CharacterCodes["X"] = 88] = "X"; + CharacterCodes[CharacterCodes["Y"] = 89] = "Y"; + CharacterCodes[CharacterCodes["Z"] = 90] = "Z"; + CharacterCodes[CharacterCodes["asterisk"] = 42] = "asterisk"; + CharacterCodes[CharacterCodes["backslash"] = 92] = "backslash"; + CharacterCodes[CharacterCodes["closeBrace"] = 125] = "closeBrace"; + CharacterCodes[CharacterCodes["closeBracket"] = 93] = "closeBracket"; + CharacterCodes[CharacterCodes["colon"] = 58] = "colon"; + CharacterCodes[CharacterCodes["comma"] = 44] = "comma"; + CharacterCodes[CharacterCodes["dot"] = 46] = "dot"; + CharacterCodes[CharacterCodes["doubleQuote"] = 34] = "doubleQuote"; + CharacterCodes[CharacterCodes["minus"] = 45] = "minus"; + CharacterCodes[CharacterCodes["openBrace"] = 123] = "openBrace"; + CharacterCodes[CharacterCodes["openBracket"] = 91] = "openBracket"; + CharacterCodes[CharacterCodes["plus"] = 43] = "plus"; + CharacterCodes[CharacterCodes["slash"] = 47] = "slash"; + CharacterCodes[CharacterCodes["formFeed"] = 12] = "formFeed"; + CharacterCodes[CharacterCodes["tab"] = 9] = "tab"; +})(CharacterCodes || (CharacterCodes = {})); + +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +function format$1(documentText, range, options) { + let initialIndentLevel; + let formatText; + let formatTextStart; + let rangeStart; + let rangeEnd; + if (range) { + rangeStart = range.offset; + rangeEnd = rangeStart + range.length; + formatTextStart = rangeStart; + while (formatTextStart > 0 && !isEOL(documentText, formatTextStart - 1)) { + formatTextStart--; + } + let endOffset = rangeEnd; + while (endOffset < documentText.length && !isEOL(documentText, endOffset)) { + endOffset++; + } + formatText = documentText.substring(formatTextStart, endOffset); + initialIndentLevel = computeIndentLevel(formatText, options); + } + else { + formatText = documentText; + initialIndentLevel = 0; + formatTextStart = 0; + rangeStart = 0; + rangeEnd = documentText.length; + } + const eol = getEOL(options, documentText); + let numberLineBreaks = 0; + let indentLevel = 0; + let indentValue; + if (options.insertSpaces) { + indentValue = repeat(' ', options.tabSize || 4); + } + else { + indentValue = '\t'; + } + let scanner = createScanner$1(formatText, false); + let hasError = false; + function newLinesAndIndent() { + if (numberLineBreaks > 1) { + return repeat(eol, numberLineBreaks) + repeat(indentValue, initialIndentLevel + indentLevel); + } + else { + return eol + repeat(indentValue, initialIndentLevel + indentLevel); + } + } + function scanNext() { + let token = scanner.scan(); + numberLineBreaks = 0; + while (token === 15 /* SyntaxKind.Trivia */ || token === 14 /* SyntaxKind.LineBreakTrivia */) { + if (token === 14 /* SyntaxKind.LineBreakTrivia */ && options.keepLines) { + numberLineBreaks += 1; + } + else if (token === 14 /* SyntaxKind.LineBreakTrivia */) { + numberLineBreaks = 1; + } + token = scanner.scan(); + } + hasError = token === 16 /* SyntaxKind.Unknown */ || scanner.getTokenError() !== 0 /* ScanError.None */; + return token; + } + const editOperations = []; + function addEdit(text, startOffset, endOffset) { + if (!hasError && (!range || (startOffset < rangeEnd && endOffset > rangeStart)) && documentText.substring(startOffset, endOffset) !== text) { + editOperations.push({ offset: startOffset, length: endOffset - startOffset, content: text }); + } + } + let firstToken = scanNext(); + if (options.keepLines && numberLineBreaks > 0) { + addEdit(repeat(eol, numberLineBreaks), 0, 0); + } + if (firstToken !== 17 /* SyntaxKind.EOF */) { + let firstTokenStart = scanner.getTokenOffset() + formatTextStart; + let initialIndent = repeat(indentValue, initialIndentLevel); + addEdit(initialIndent, formatTextStart, firstTokenStart); + } + while (firstToken !== 17 /* SyntaxKind.EOF */) { + let firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart; + let secondToken = scanNext(); + let replaceContent = ''; + let needsLineBreak = false; + while (numberLineBreaks === 0 && (secondToken === 12 /* SyntaxKind.LineCommentTrivia */ || secondToken === 13 /* SyntaxKind.BlockCommentTrivia */)) { + let commentTokenStart = scanner.getTokenOffset() + formatTextStart; + addEdit(' ', firstTokenEnd, commentTokenStart); + firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart; + needsLineBreak = secondToken === 12 /* SyntaxKind.LineCommentTrivia */; + replaceContent = needsLineBreak ? newLinesAndIndent() : ''; + secondToken = scanNext(); + } + if (secondToken === 2 /* SyntaxKind.CloseBraceToken */) { + if (firstToken !== 1 /* SyntaxKind.OpenBraceToken */) { + indentLevel--; + } + if (options.keepLines && numberLineBreaks > 0 || !options.keepLines && firstToken !== 1 /* SyntaxKind.OpenBraceToken */) { + replaceContent = newLinesAndIndent(); + } + else if (options.keepLines) { + replaceContent = ' '; + } + } + else if (secondToken === 4 /* SyntaxKind.CloseBracketToken */) { + if (firstToken !== 3 /* SyntaxKind.OpenBracketToken */) { + indentLevel--; + } + if (options.keepLines && numberLineBreaks > 0 || !options.keepLines && firstToken !== 3 /* SyntaxKind.OpenBracketToken */) { + replaceContent = newLinesAndIndent(); + } + else if (options.keepLines) { + replaceContent = ' '; + } + } + else { + switch (firstToken) { + case 3 /* SyntaxKind.OpenBracketToken */: + case 1 /* SyntaxKind.OpenBraceToken */: + indentLevel++; + if (options.keepLines && numberLineBreaks > 0 || !options.keepLines) { + replaceContent = newLinesAndIndent(); + } + else { + replaceContent = ' '; + } + break; + case 5 /* SyntaxKind.CommaToken */: + if (options.keepLines && numberLineBreaks > 0 || !options.keepLines) { + replaceContent = newLinesAndIndent(); + } + else { + replaceContent = ' '; + } + break; + case 12 /* SyntaxKind.LineCommentTrivia */: + replaceContent = newLinesAndIndent(); + break; + case 13 /* SyntaxKind.BlockCommentTrivia */: + if (numberLineBreaks > 0) { + replaceContent = newLinesAndIndent(); + } + else if (!needsLineBreak) { + replaceContent = ' '; + } + break; + case 6 /* SyntaxKind.ColonToken */: + if (options.keepLines && numberLineBreaks > 0) { + replaceContent = newLinesAndIndent(); + } + else if (!needsLineBreak) { + replaceContent = ' '; + } + break; + case 10 /* SyntaxKind.StringLiteral */: + if (options.keepLines && numberLineBreaks > 0) { + replaceContent = newLinesAndIndent(); + } + else if (secondToken === 6 /* SyntaxKind.ColonToken */ && !needsLineBreak) { + replaceContent = ''; + } + break; + case 7 /* SyntaxKind.NullKeyword */: + case 8 /* SyntaxKind.TrueKeyword */: + case 9 /* SyntaxKind.FalseKeyword */: + case 11 /* SyntaxKind.NumericLiteral */: + case 2 /* SyntaxKind.CloseBraceToken */: + case 4 /* SyntaxKind.CloseBracketToken */: + if (options.keepLines && numberLineBreaks > 0) { + replaceContent = newLinesAndIndent(); + } + else { + if ((secondToken === 12 /* SyntaxKind.LineCommentTrivia */ || secondToken === 13 /* SyntaxKind.BlockCommentTrivia */) && !needsLineBreak) { + replaceContent = ' '; + } + else if (secondToken !== 5 /* SyntaxKind.CommaToken */ && secondToken !== 17 /* SyntaxKind.EOF */) { + hasError = true; + } + } + break; + case 16 /* SyntaxKind.Unknown */: + hasError = true; + break; + } + if (numberLineBreaks > 0 && (secondToken === 12 /* SyntaxKind.LineCommentTrivia */ || secondToken === 13 /* SyntaxKind.BlockCommentTrivia */)) { + replaceContent = newLinesAndIndent(); + } + } + if (secondToken === 17 /* SyntaxKind.EOF */) { + if (options.keepLines && numberLineBreaks > 0) { + replaceContent = newLinesAndIndent(); + } + else { + replaceContent = options.insertFinalNewline ? eol : ''; + } + } + const secondTokenStart = scanner.getTokenOffset() + formatTextStart; + addEdit(replaceContent, firstTokenEnd, secondTokenStart); + firstToken = secondToken; + } + return editOperations; +} +function repeat(s, count) { + let result = ''; + for (let i = 0; i < count; i++) { + result += s; + } + return result; +} +function computeIndentLevel(content, options) { + let i = 0; + let nChars = 0; + const tabSize = options.tabSize || 4; + while (i < content.length) { + let ch = content.charAt(i); + if (ch === ' ') { + nChars++; + } + else if (ch === '\t') { + nChars += tabSize; + } + else { + break; + } + i++; + } + return Math.floor(nChars / tabSize); +} +function getEOL(options, text) { + for (let i = 0; i < text.length; i++) { + const ch = text.charAt(i); + if (ch === '\r') { + if (i + 1 < text.length && text.charAt(i + 1) === '\n') { + return '\r\n'; + } + return '\r'; + } + else if (ch === '\n') { + return '\n'; + } + } + return (options && options.eol) || '\n'; +} +function isEOL(text, offset) { + return '\r\n'.indexOf(text.charAt(offset)) !== -1; +} + +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +var ParseOptions; +(function (ParseOptions) { + ParseOptions.DEFAULT = { + allowTrailingComma: false + }; +})(ParseOptions || (ParseOptions = {})); +/** + * For a given offset, evaluate the location in the JSON document. Each segment in the location path is either a property name or an array index. + */ +function getLocation$1(text, position) { + const segments = []; // strings or numbers + const earlyReturnException = new Object(); + let previousNode = undefined; + const previousNodeInst = { + value: {}, + offset: 0, + length: 0, + type: 'object', + parent: undefined + }; + let isAtPropertyKey = false; + function setPreviousNode(value, offset, length, type) { + previousNodeInst.value = value; + previousNodeInst.offset = offset; + previousNodeInst.length = length; + previousNodeInst.type = type; + previousNodeInst.colonOffset = undefined; + previousNode = previousNodeInst; + } + try { + visit$2(text, { + onObjectBegin: (offset, length) => { + if (position <= offset) { + throw earlyReturnException; + } + previousNode = undefined; + isAtPropertyKey = position > offset; + segments.push(''); // push a placeholder (will be replaced) + }, + onObjectProperty: (name, offset, length) => { + if (position < offset) { + throw earlyReturnException; + } + setPreviousNode(name, offset, length, 'property'); + segments[segments.length - 1] = name; + if (position <= offset + length) { + throw earlyReturnException; + } + }, + onObjectEnd: (offset, length) => { + if (position <= offset) { + throw earlyReturnException; + } + previousNode = undefined; + segments.pop(); + }, + onArrayBegin: (offset, length) => { + if (position <= offset) { + throw earlyReturnException; + } + previousNode = undefined; + segments.push(0); + }, + onArrayEnd: (offset, length) => { + if (position <= offset) { + throw earlyReturnException; + } + previousNode = undefined; + segments.pop(); + }, + onLiteralValue: (value, offset, length) => { + if (position < offset) { + throw earlyReturnException; + } + setPreviousNode(value, offset, length, getNodeType(value)); + if (position <= offset + length) { + throw earlyReturnException; + } + }, + onSeparator: (sep, offset, length) => { + if (position <= offset) { + throw earlyReturnException; + } + if (sep === ':' && previousNode && previousNode.type === 'property') { + previousNode.colonOffset = offset; + isAtPropertyKey = false; + previousNode = undefined; + } + else if (sep === ',') { + const last = segments[segments.length - 1]; + if (typeof last === 'number') { + segments[segments.length - 1] = last + 1; + } + else { + isAtPropertyKey = true; + segments[segments.length - 1] = ''; + } + previousNode = undefined; + } + } + }); + } + catch (e) { + if (e !== earlyReturnException) { + throw e; + } + } + return { + path: segments, + previousNode, + isAtPropertyKey, + matches: (pattern) => { + let k = 0; + for (let i = 0; k < pattern.length && i < segments.length; i++) { + if (pattern[k] === segments[i] || pattern[k] === '*') { + k++; + } + else if (pattern[k] !== '**') { + return false; + } + } + return k === pattern.length; + } + }; +} +/** + * Parses the given text and returns the object the JSON content represents. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result. + * Therefore always check the errors list to find out if the input was valid. + */ +function parse$5(text, errors = [], options = ParseOptions.DEFAULT) { + let currentProperty = null; + let currentParent = []; + const previousParents = []; + function onValue(value) { + if (Array.isArray(currentParent)) { + currentParent.push(value); + } + else if (currentProperty !== null) { + currentParent[currentProperty] = value; + } + } + const visitor = { + onObjectBegin: () => { + const object = {}; + onValue(object); + previousParents.push(currentParent); + currentParent = object; + currentProperty = null; + }, + onObjectProperty: (name) => { + currentProperty = name; + }, + onObjectEnd: () => { + currentParent = previousParents.pop(); + }, + onArrayBegin: () => { + const array = []; + onValue(array); + previousParents.push(currentParent); + currentParent = array; + currentProperty = null; + }, + onArrayEnd: () => { + currentParent = previousParents.pop(); + }, + onLiteralValue: onValue, + onError: (error, offset, length) => { + errors.push({ error, offset, length }); + } + }; + visit$2(text, visitor, options); + return currentParent[0]; +} +/** + * Parses the given text and returns a tree representation the JSON content. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result. + */ +function parseTree$1(text, errors = [], options = ParseOptions.DEFAULT) { + let currentParent = { type: 'array', offset: -1, length: -1, children: [], parent: undefined }; // artificial root + function ensurePropertyComplete(endOffset) { + if (currentParent.type === 'property') { + currentParent.length = endOffset - currentParent.offset; + currentParent = currentParent.parent; + } + } + function onValue(valueNode) { + currentParent.children.push(valueNode); + return valueNode; + } + const visitor = { + onObjectBegin: (offset) => { + currentParent = onValue({ type: 'object', offset, length: -1, parent: currentParent, children: [] }); + }, + onObjectProperty: (name, offset, length) => { + currentParent = onValue({ type: 'property', offset, length: -1, parent: currentParent, children: [] }); + currentParent.children.push({ type: 'string', value: name, offset, length, parent: currentParent }); + }, + onObjectEnd: (offset, length) => { + ensurePropertyComplete(offset + length); // in case of a missing value for a property: make sure property is complete + currentParent.length = offset + length - currentParent.offset; + currentParent = currentParent.parent; + ensurePropertyComplete(offset + length); + }, + onArrayBegin: (offset, length) => { + currentParent = onValue({ type: 'array', offset, length: -1, parent: currentParent, children: [] }); + }, + onArrayEnd: (offset, length) => { + currentParent.length = offset + length - currentParent.offset; + currentParent = currentParent.parent; + ensurePropertyComplete(offset + length); + }, + onLiteralValue: (value, offset, length) => { + onValue({ type: getNodeType(value), offset, length, parent: currentParent, value }); + ensurePropertyComplete(offset + length); + }, + onSeparator: (sep, offset, length) => { + if (currentParent.type === 'property') { + if (sep === ':') { + currentParent.colonOffset = offset; + } + else if (sep === ',') { + ensurePropertyComplete(offset); + } + } + }, + onError: (error, offset, length) => { + errors.push({ error, offset, length }); + } + }; + visit$2(text, visitor, options); + const result = currentParent.children[0]; + if (result) { + delete result.parent; + } + return result; +} +/** + * Finds the node at the given path in a JSON DOM. + */ +function findNodeAtLocation$1(root, path) { + if (!root) { + return undefined; + } + let node = root; + for (let segment of path) { + if (typeof segment === 'string') { + if (node.type !== 'object' || !Array.isArray(node.children)) { + return undefined; + } + let found = false; + for (const propertyNode of node.children) { + if (Array.isArray(propertyNode.children) && propertyNode.children[0].value === segment && propertyNode.children.length === 2) { + node = propertyNode.children[1]; + found = true; + break; + } + } + if (!found) { + return undefined; + } + } + else { + const index = segment; + if (node.type !== 'array' || index < 0 || !Array.isArray(node.children) || index >= node.children.length) { + return undefined; + } + node = node.children[index]; + } + } + return node; +} +/** + * Gets the JSON path of the given JSON DOM node + */ +function getNodePath$1(node) { + if (!node.parent || !node.parent.children) { + return []; + } + const path = getNodePath$1(node.parent); + if (node.parent.type === 'property') { + const key = node.parent.children[0].value; + path.push(key); + } + else if (node.parent.type === 'array') { + const index = node.parent.children.indexOf(node); + if (index !== -1) { + path.push(index); + } + } + return path; +} +/** + * Evaluates the JavaScript object of the given JSON DOM node + */ +function getNodeValue$1(node) { + switch (node.type) { + case 'array': + return node.children.map(getNodeValue$1); + case 'object': + const obj = Object.create(null); + for (let prop of node.children) { + const valueNode = prop.children[1]; + if (valueNode) { + obj[prop.children[0].value] = getNodeValue$1(valueNode); + } + } + return obj; + case 'null': + case 'string': + case 'number': + case 'boolean': + return node.value; + default: + return undefined; + } +} +function contains$2(node, offset, includeRightBound = false) { + return (offset >= node.offset && offset < (node.offset + node.length)) || includeRightBound && (offset === (node.offset + node.length)); +} +/** + * Finds the most inner node at the given offset. If includeRightBound is set, also finds nodes that end at the given offset. + */ +function findNodeAtOffset$1(node, offset, includeRightBound = false) { + if (contains$2(node, offset, includeRightBound)) { + const children = node.children; + if (Array.isArray(children)) { + for (let i = 0; i < children.length && children[i].offset <= offset; i++) { + const item = findNodeAtOffset$1(children[i], offset, includeRightBound); + if (item) { + return item; + } + } + } + return node; + } + return undefined; +} +/** + * Parses the given text and invokes the visitor functions for each object, array and literal reached. + */ +function visit$2(text, visitor, options = ParseOptions.DEFAULT) { + const _scanner = createScanner$1(text, false); + // Important: Only pass copies of this to visitor functions to prevent accidental modification, and + // to not affect visitor functions which stored a reference to a previous JSONPath + const _jsonPath = []; + function toNoArgVisit(visitFunction) { + return visitFunction ? () => visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true; + } + function toNoArgVisitWithPath(visitFunction) { + return visitFunction ? () => visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter(), () => _jsonPath.slice()) : () => true; + } + function toOneArgVisit(visitFunction) { + return visitFunction ? (arg) => visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true; + } + function toOneArgVisitWithPath(visitFunction) { + return visitFunction ? (arg) => visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter(), () => _jsonPath.slice()) : () => true; + } + const onObjectBegin = toNoArgVisitWithPath(visitor.onObjectBegin), onObjectProperty = toOneArgVisitWithPath(visitor.onObjectProperty), onObjectEnd = toNoArgVisit(visitor.onObjectEnd), onArrayBegin = toNoArgVisitWithPath(visitor.onArrayBegin), onArrayEnd = toNoArgVisit(visitor.onArrayEnd), onLiteralValue = toOneArgVisitWithPath(visitor.onLiteralValue), onSeparator = toOneArgVisit(visitor.onSeparator), onComment = toNoArgVisit(visitor.onComment), onError = toOneArgVisit(visitor.onError); + const disallowComments = options && options.disallowComments; + const allowTrailingComma = options && options.allowTrailingComma; + function scanNext() { + while (true) { + const token = _scanner.scan(); + switch (_scanner.getTokenError()) { + case 4 /* ScanError.InvalidUnicode */: + handleError(14 /* ParseErrorCode.InvalidUnicode */); + break; + case 5 /* ScanError.InvalidEscapeCharacter */: + handleError(15 /* ParseErrorCode.InvalidEscapeCharacter */); + break; + case 3 /* ScanError.UnexpectedEndOfNumber */: + handleError(13 /* ParseErrorCode.UnexpectedEndOfNumber */); + break; + case 1 /* ScanError.UnexpectedEndOfComment */: + if (!disallowComments) { + handleError(11 /* ParseErrorCode.UnexpectedEndOfComment */); + } + break; + case 2 /* ScanError.UnexpectedEndOfString */: + handleError(12 /* ParseErrorCode.UnexpectedEndOfString */); + break; + case 6 /* ScanError.InvalidCharacter */: + handleError(16 /* ParseErrorCode.InvalidCharacter */); + break; + } + switch (token) { + case 12 /* SyntaxKind.LineCommentTrivia */: + case 13 /* SyntaxKind.BlockCommentTrivia */: + if (disallowComments) { + handleError(10 /* ParseErrorCode.InvalidCommentToken */); + } + else { + onComment(); + } + break; + case 16 /* SyntaxKind.Unknown */: + handleError(1 /* ParseErrorCode.InvalidSymbol */); + break; + case 15 /* SyntaxKind.Trivia */: + case 14 /* SyntaxKind.LineBreakTrivia */: + break; + default: + return token; + } + } + } + function handleError(error, skipUntilAfter = [], skipUntil = []) { + onError(error); + if (skipUntilAfter.length + skipUntil.length > 0) { + let token = _scanner.getToken(); + while (token !== 17 /* SyntaxKind.EOF */) { + if (skipUntilAfter.indexOf(token) !== -1) { + scanNext(); + break; + } + else if (skipUntil.indexOf(token) !== -1) { + break; + } + token = scanNext(); + } + } + } + function parseString(isValue) { + const value = _scanner.getTokenValue(); + if (isValue) { + onLiteralValue(value); + } + else { + onObjectProperty(value); + // add property name afterwards + _jsonPath.push(value); + } + scanNext(); + return true; + } + function parseLiteral() { + switch (_scanner.getToken()) { + case 11 /* SyntaxKind.NumericLiteral */: + const tokenValue = _scanner.getTokenValue(); + let value = Number(tokenValue); + if (isNaN(value)) { + handleError(2 /* ParseErrorCode.InvalidNumberFormat */); + value = 0; + } + onLiteralValue(value); + break; + case 7 /* SyntaxKind.NullKeyword */: + onLiteralValue(null); + break; + case 8 /* SyntaxKind.TrueKeyword */: + onLiteralValue(true); + break; + case 9 /* SyntaxKind.FalseKeyword */: + onLiteralValue(false); + break; + default: + return false; + } + scanNext(); + return true; + } + function parseProperty() { + if (_scanner.getToken() !== 10 /* SyntaxKind.StringLiteral */) { + handleError(3 /* ParseErrorCode.PropertyNameExpected */, [], [2 /* SyntaxKind.CloseBraceToken */, 5 /* SyntaxKind.CommaToken */]); + return false; + } + parseString(false); + if (_scanner.getToken() === 6 /* SyntaxKind.ColonToken */) { + onSeparator(':'); + scanNext(); // consume colon + if (!parseValue()) { + handleError(4 /* ParseErrorCode.ValueExpected */, [], [2 /* SyntaxKind.CloseBraceToken */, 5 /* SyntaxKind.CommaToken */]); + } + } + else { + handleError(5 /* ParseErrorCode.ColonExpected */, [], [2 /* SyntaxKind.CloseBraceToken */, 5 /* SyntaxKind.CommaToken */]); + } + _jsonPath.pop(); // remove processed property name + return true; + } + function parseObject() { + onObjectBegin(); + scanNext(); // consume open brace + let needsComma = false; + while (_scanner.getToken() !== 2 /* SyntaxKind.CloseBraceToken */ && _scanner.getToken() !== 17 /* SyntaxKind.EOF */) { + if (_scanner.getToken() === 5 /* SyntaxKind.CommaToken */) { + if (!needsComma) { + handleError(4 /* ParseErrorCode.ValueExpected */, [], []); + } + onSeparator(','); + scanNext(); // consume comma + if (_scanner.getToken() === 2 /* SyntaxKind.CloseBraceToken */ && allowTrailingComma) { + break; + } + } + else if (needsComma) { + handleError(6 /* ParseErrorCode.CommaExpected */, [], []); + } + if (!parseProperty()) { + handleError(4 /* ParseErrorCode.ValueExpected */, [], [2 /* SyntaxKind.CloseBraceToken */, 5 /* SyntaxKind.CommaToken */]); + } + needsComma = true; + } + onObjectEnd(); + if (_scanner.getToken() !== 2 /* SyntaxKind.CloseBraceToken */) { + handleError(7 /* ParseErrorCode.CloseBraceExpected */, [2 /* SyntaxKind.CloseBraceToken */], []); + } + else { + scanNext(); // consume close brace + } + return true; + } + function parseArray() { + onArrayBegin(); + scanNext(); // consume open bracket + let isFirstElement = true; + let needsComma = false; + while (_scanner.getToken() !== 4 /* SyntaxKind.CloseBracketToken */ && _scanner.getToken() !== 17 /* SyntaxKind.EOF */) { + if (_scanner.getToken() === 5 /* SyntaxKind.CommaToken */) { + if (!needsComma) { + handleError(4 /* ParseErrorCode.ValueExpected */, [], []); + } + onSeparator(','); + scanNext(); // consume comma + if (_scanner.getToken() === 4 /* SyntaxKind.CloseBracketToken */ && allowTrailingComma) { + break; + } + } + else if (needsComma) { + handleError(6 /* ParseErrorCode.CommaExpected */, [], []); + } + if (isFirstElement) { + _jsonPath.push(0); + isFirstElement = false; + } + else { + _jsonPath[_jsonPath.length - 1]++; + } + if (!parseValue()) { + handleError(4 /* ParseErrorCode.ValueExpected */, [], [4 /* SyntaxKind.CloseBracketToken */, 5 /* SyntaxKind.CommaToken */]); + } + needsComma = true; + } + onArrayEnd(); + if (!isFirstElement) { + _jsonPath.pop(); // remove array index + } + if (_scanner.getToken() !== 4 /* SyntaxKind.CloseBracketToken */) { + handleError(8 /* ParseErrorCode.CloseBracketExpected */, [4 /* SyntaxKind.CloseBracketToken */], []); + } + else { + scanNext(); // consume close bracket + } + return true; + } + function parseValue() { + switch (_scanner.getToken()) { + case 3 /* SyntaxKind.OpenBracketToken */: + return parseArray(); + case 1 /* SyntaxKind.OpenBraceToken */: + return parseObject(); + case 10 /* SyntaxKind.StringLiteral */: + return parseString(true); + default: + return parseLiteral(); + } + } + scanNext(); + if (_scanner.getToken() === 17 /* SyntaxKind.EOF */) { + if (options.allowEmptyContent) { + return true; + } + handleError(4 /* ParseErrorCode.ValueExpected */, [], []); + return false; + } + if (!parseValue()) { + handleError(4 /* ParseErrorCode.ValueExpected */, [], []); + return false; + } + if (_scanner.getToken() !== 17 /* SyntaxKind.EOF */) { + handleError(9 /* ParseErrorCode.EndOfFileExpected */, [], []); + } + return true; +} +/** + * Takes JSON with JavaScript-style comments and remove + * them. Optionally replaces every none-newline character + * of comments with a replaceCharacter + */ +function stripComments$1(text, replaceCh) { + let _scanner = createScanner$1(text), parts = [], kind, offset = 0, pos; + do { + pos = _scanner.getPosition(); + kind = _scanner.scan(); + switch (kind) { + case 12 /* SyntaxKind.LineCommentTrivia */: + case 13 /* SyntaxKind.BlockCommentTrivia */: + case 17 /* SyntaxKind.EOF */: + if (offset !== pos) { + parts.push(text.substring(offset, pos)); + } + if (replaceCh !== undefined) { + parts.push(_scanner.getTokenValue().replace(/[^\r\n]/g, replaceCh)); + } + offset = _scanner.getPosition(); + break; + } + } while (kind !== 17 /* SyntaxKind.EOF */); + return parts.join(''); +} +function getNodeType(value) { + switch (typeof value) { + case 'boolean': return 'boolean'; + case 'number': return 'number'; + case 'string': return 'string'; + case 'object': { + if (!value) { + return 'null'; + } + else if (Array.isArray(value)) { + return 'array'; + } + return 'object'; + } + default: return 'null'; + } +} + +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +function setProperty(text, originalPath, value, options) { + const path = originalPath.slice(); + const errors = []; + const root = parseTree$1(text, errors); + let parent = void 0; + let lastSegment = void 0; + while (path.length > 0) { + lastSegment = path.pop(); + parent = findNodeAtLocation$1(root, path); + if (parent === void 0 && value !== void 0) { + if (typeof lastSegment === 'string') { + value = { [lastSegment]: value }; + } + else { + value = [value]; + } + } + else { + break; + } + } + if (!parent) { + // empty document + if (value === void 0) { // delete + throw new Error('Can not delete in empty document'); + } + return withFormatting(text, { offset: root ? root.offset : 0, length: root ? root.length : 0, content: JSON.stringify(value) }, options); + } + else if (parent.type === 'object' && typeof lastSegment === 'string' && Array.isArray(parent.children)) { + const existing = findNodeAtLocation$1(parent, [lastSegment]); + if (existing !== void 0) { + if (value === void 0) { // delete + if (!existing.parent) { + throw new Error('Malformed AST'); + } + const propertyIndex = parent.children.indexOf(existing.parent); + let removeBegin; + let removeEnd = existing.parent.offset + existing.parent.length; + if (propertyIndex > 0) { + // remove the comma of the previous node + let previous = parent.children[propertyIndex - 1]; + removeBegin = previous.offset + previous.length; + } + else { + removeBegin = parent.offset + 1; + if (parent.children.length > 1) { + // remove the comma of the next node + let next = parent.children[1]; + removeEnd = next.offset; + } + } + return withFormatting(text, { offset: removeBegin, length: removeEnd - removeBegin, content: '' }, options); + } + else { + // set value of existing property + return withFormatting(text, { offset: existing.offset, length: existing.length, content: JSON.stringify(value) }, options); + } + } + else { + if (value === void 0) { // delete + return []; // property does not exist, nothing to do + } + const newProperty = `${JSON.stringify(lastSegment)}: ${JSON.stringify(value)}`; + const index = options.getInsertionIndex ? options.getInsertionIndex(parent.children.map(p => p.children[0].value)) : parent.children.length; + let edit; + if (index > 0) { + let previous = parent.children[index - 1]; + edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty }; + } + else if (parent.children.length === 0) { + edit = { offset: parent.offset + 1, length: 0, content: newProperty }; + } + else { + edit = { offset: parent.offset + 1, length: 0, content: newProperty + ',' }; + } + return withFormatting(text, edit, options); + } + } + else if (parent.type === 'array' && typeof lastSegment === 'number' && Array.isArray(parent.children)) { + const insertIndex = lastSegment; + if (insertIndex === -1) { + // Insert + const newProperty = `${JSON.stringify(value)}`; + let edit; + if (parent.children.length === 0) { + edit = { offset: parent.offset + 1, length: 0, content: newProperty }; + } + else { + const previous = parent.children[parent.children.length - 1]; + edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty }; + } + return withFormatting(text, edit, options); + } + else if (value === void 0 && parent.children.length >= 0) { + // Removal + const removalIndex = lastSegment; + const toRemove = parent.children[removalIndex]; + let edit; + if (parent.children.length === 1) { + // only item + edit = { offset: parent.offset + 1, length: parent.length - 2, content: '' }; + } + else if (parent.children.length - 1 === removalIndex) { + // last item + let previous = parent.children[removalIndex - 1]; + let offset = previous.offset + previous.length; + let parentEndOffset = parent.offset + parent.length; + edit = { offset, length: parentEndOffset - 2 - offset, content: '' }; + } + else { + edit = { offset: toRemove.offset, length: parent.children[removalIndex + 1].offset - toRemove.offset, content: '' }; + } + return withFormatting(text, edit, options); + } + else if (value !== void 0) { + let edit; + const newProperty = `${JSON.stringify(value)}`; + if (!options.isArrayInsertion && parent.children.length > lastSegment) { + const toModify = parent.children[lastSegment]; + edit = { offset: toModify.offset, length: toModify.length, content: newProperty }; + } + else if (parent.children.length === 0 || lastSegment === 0) { + edit = { offset: parent.offset + 1, length: 0, content: parent.children.length === 0 ? newProperty : newProperty + ',' }; + } + else { + const index = lastSegment > parent.children.length ? parent.children.length : lastSegment; + const previous = parent.children[index - 1]; + edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty }; + } + return withFormatting(text, edit, options); + } + else { + throw new Error(`Can not ${value === void 0 ? 'remove' : (options.isArrayInsertion ? 'insert' : 'modify')} Array index ${insertIndex} as length is not sufficient`); + } + } + else { + throw new Error(`Can not add ${typeof lastSegment !== 'number' ? 'index' : 'property'} to parent of type ${parent.type}`); + } +} +function withFormatting(text, edit, options) { + if (!options.formattingOptions) { + return [edit]; + } + // apply the edit + let newText = applyEdit(text, edit); + // format the new text + let begin = edit.offset; + let end = edit.offset + edit.content.length; + if (edit.length === 0 || edit.content.length === 0) { // insert or remove + while (begin > 0 && !isEOL(newText, begin - 1)) { + begin--; + } + while (end < newText.length && !isEOL(newText, end)) { + end++; + } + } + const edits = format$1(newText, { offset: begin, length: end - begin }, { ...options.formattingOptions, keepLines: false }); + // apply the formatting edits and track the begin and end offsets of the changes + for (let i = edits.length - 1; i >= 0; i--) { + const edit = edits[i]; + newText = applyEdit(newText, edit); + begin = Math.min(begin, edit.offset); + end = Math.max(end, edit.offset + edit.length); + end += edit.content.length - edit.length; + } + // create a single edit with all changes + const editLength = text.length - (newText.length - end) - begin; + return [{ offset: begin, length: editLength, content: newText.substring(begin, end) }]; +} +function applyEdit(text, edit) { + return text.substring(0, edit.offset) + edit.content + text.substring(edit.offset + edit.length); +} + +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +/** + * Creates a JSON scanner on the given text. + * If ignoreTrivia is set, whitespaces or comments are ignored. + */ +const createScanner = createScanner$1; +var ScanError; +(function (ScanError) { + ScanError[ScanError["None"] = 0] = "None"; + ScanError[ScanError["UnexpectedEndOfComment"] = 1] = "UnexpectedEndOfComment"; + ScanError[ScanError["UnexpectedEndOfString"] = 2] = "UnexpectedEndOfString"; + ScanError[ScanError["UnexpectedEndOfNumber"] = 3] = "UnexpectedEndOfNumber"; + ScanError[ScanError["InvalidUnicode"] = 4] = "InvalidUnicode"; + ScanError[ScanError["InvalidEscapeCharacter"] = 5] = "InvalidEscapeCharacter"; + ScanError[ScanError["InvalidCharacter"] = 6] = "InvalidCharacter"; +})(ScanError || (ScanError = {})); +var SyntaxKind; +(function (SyntaxKind) { + SyntaxKind[SyntaxKind["OpenBraceToken"] = 1] = "OpenBraceToken"; + SyntaxKind[SyntaxKind["CloseBraceToken"] = 2] = "CloseBraceToken"; + SyntaxKind[SyntaxKind["OpenBracketToken"] = 3] = "OpenBracketToken"; + SyntaxKind[SyntaxKind["CloseBracketToken"] = 4] = "CloseBracketToken"; + SyntaxKind[SyntaxKind["CommaToken"] = 5] = "CommaToken"; + SyntaxKind[SyntaxKind["ColonToken"] = 6] = "ColonToken"; + SyntaxKind[SyntaxKind["NullKeyword"] = 7] = "NullKeyword"; + SyntaxKind[SyntaxKind["TrueKeyword"] = 8] = "TrueKeyword"; + SyntaxKind[SyntaxKind["FalseKeyword"] = 9] = "FalseKeyword"; + SyntaxKind[SyntaxKind["StringLiteral"] = 10] = "StringLiteral"; + SyntaxKind[SyntaxKind["NumericLiteral"] = 11] = "NumericLiteral"; + SyntaxKind[SyntaxKind["LineCommentTrivia"] = 12] = "LineCommentTrivia"; + SyntaxKind[SyntaxKind["BlockCommentTrivia"] = 13] = "BlockCommentTrivia"; + SyntaxKind[SyntaxKind["LineBreakTrivia"] = 14] = "LineBreakTrivia"; + SyntaxKind[SyntaxKind["Trivia"] = 15] = "Trivia"; + SyntaxKind[SyntaxKind["Unknown"] = 16] = "Unknown"; + SyntaxKind[SyntaxKind["EOF"] = 17] = "EOF"; +})(SyntaxKind || (SyntaxKind = {})); +/** + * For a given offset, evaluate the location in the JSON document. Each segment in the location path is either a property name or an array index. + */ +const getLocation = getLocation$1; +/** + * Parses the given text and returns the object the JSON content represents. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result. + * Therefore, always check the errors list to find out if the input was valid. + */ +const parse$4 = parse$5; +/** + * Parses the given text and returns a tree representation the JSON content. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result. + */ +const parseTree = parseTree$1; +/** + * Finds the node at the given path in a JSON DOM. + */ +const findNodeAtLocation = findNodeAtLocation$1; +/** + * Finds the innermost node at the given offset. If includeRightBound is set, also finds nodes that end at the given offset. + */ +const findNodeAtOffset = findNodeAtOffset$1; +/** + * Gets the JSON path of the given JSON DOM node + */ +const getNodePath = getNodePath$1; +/** + * Evaluates the JavaScript object of the given JSON DOM node + */ +const getNodeValue = getNodeValue$1; +/** + * Parses the given text and invokes the visitor functions for each object, array and literal reached. + */ +const visit$1 = visit$2; +/** + * Takes JSON with JavaScript-style comments and remove + * them. Optionally replaces every none-newline character + * of comments with a replaceCharacter + */ +const stripComments = stripComments$1; +var ParseErrorCode; +(function (ParseErrorCode) { + ParseErrorCode[ParseErrorCode["InvalidSymbol"] = 1] = "InvalidSymbol"; + ParseErrorCode[ParseErrorCode["InvalidNumberFormat"] = 2] = "InvalidNumberFormat"; + ParseErrorCode[ParseErrorCode["PropertyNameExpected"] = 3] = "PropertyNameExpected"; + ParseErrorCode[ParseErrorCode["ValueExpected"] = 4] = "ValueExpected"; + ParseErrorCode[ParseErrorCode["ColonExpected"] = 5] = "ColonExpected"; + ParseErrorCode[ParseErrorCode["CommaExpected"] = 6] = "CommaExpected"; + ParseErrorCode[ParseErrorCode["CloseBraceExpected"] = 7] = "CloseBraceExpected"; + ParseErrorCode[ParseErrorCode["CloseBracketExpected"] = 8] = "CloseBracketExpected"; + ParseErrorCode[ParseErrorCode["EndOfFileExpected"] = 9] = "EndOfFileExpected"; + ParseErrorCode[ParseErrorCode["InvalidCommentToken"] = 10] = "InvalidCommentToken"; + ParseErrorCode[ParseErrorCode["UnexpectedEndOfComment"] = 11] = "UnexpectedEndOfComment"; + ParseErrorCode[ParseErrorCode["UnexpectedEndOfString"] = 12] = "UnexpectedEndOfString"; + ParseErrorCode[ParseErrorCode["UnexpectedEndOfNumber"] = 13] = "UnexpectedEndOfNumber"; + ParseErrorCode[ParseErrorCode["InvalidUnicode"] = 14] = "InvalidUnicode"; + ParseErrorCode[ParseErrorCode["InvalidEscapeCharacter"] = 15] = "InvalidEscapeCharacter"; + ParseErrorCode[ParseErrorCode["InvalidCharacter"] = 16] = "InvalidCharacter"; +})(ParseErrorCode || (ParseErrorCode = {})); +function printParseErrorCode(code) { + switch (code) { + case 1 /* ParseErrorCode.InvalidSymbol */: return 'InvalidSymbol'; + case 2 /* ParseErrorCode.InvalidNumberFormat */: return 'InvalidNumberFormat'; + case 3 /* ParseErrorCode.PropertyNameExpected */: return 'PropertyNameExpected'; + case 4 /* ParseErrorCode.ValueExpected */: return 'ValueExpected'; + case 5 /* ParseErrorCode.ColonExpected */: return 'ColonExpected'; + case 6 /* ParseErrorCode.CommaExpected */: return 'CommaExpected'; + case 7 /* ParseErrorCode.CloseBraceExpected */: return 'CloseBraceExpected'; + case 8 /* ParseErrorCode.CloseBracketExpected */: return 'CloseBracketExpected'; + case 9 /* ParseErrorCode.EndOfFileExpected */: return 'EndOfFileExpected'; + case 10 /* ParseErrorCode.InvalidCommentToken */: return 'InvalidCommentToken'; + case 11 /* ParseErrorCode.UnexpectedEndOfComment */: return 'UnexpectedEndOfComment'; + case 12 /* ParseErrorCode.UnexpectedEndOfString */: return 'UnexpectedEndOfString'; + case 13 /* ParseErrorCode.UnexpectedEndOfNumber */: return 'UnexpectedEndOfNumber'; + case 14 /* ParseErrorCode.InvalidUnicode */: return 'InvalidUnicode'; + case 15 /* ParseErrorCode.InvalidEscapeCharacter */: return 'InvalidEscapeCharacter'; + case 16 /* ParseErrorCode.InvalidCharacter */: return 'InvalidCharacter'; + } + return '<unknown ParseErrorCode>'; +} +/** + * Computes the edit operations needed to format a JSON document. + * + * @param documentText The input text + * @param range The range to format or `undefined` to format the full content + * @param options The formatting options + * @returns The edit operations describing the formatting changes to the original document following the format described in {@linkcode EditResult}. + * To apply the edit operations to the input, use {@linkcode applyEdits}. + */ +function format(documentText, range, options) { + return format$1(documentText, range, options); +} +/** + * Computes the edit operations needed to modify a value in the JSON document. + * + * @param documentText The input text + * @param path The path of the value to change. The path represents either to the document root, a property or an array item. + * If the path points to an non-existing property or item, it will be created. + * @param value The new value for the specified property or item. If the value is undefined, + * the property or item will be removed. + * @param options Options + * @returns The edit operations describing the changes to the original document, following the format described in {@linkcode EditResult}. + * To apply the edit operations to the input, use {@linkcode applyEdits}. + */ +function modify(text, path, value, options) { + return setProperty(text, path, value, options); +} +/** + * Applies edits to an input string. + * @param text The input text + * @param edits Edit operations following the format described in {@linkcode EditResult}. + * @returns The text with the applied edits. + * @throws An error if the edit operations are not well-formed as described in {@linkcode EditResult}. + */ +function applyEdits(text, edits) { + let sortedEdits = edits.slice(0).sort((a, b) => { + const diff = a.offset - b.offset; + if (diff === 0) { + return a.length - b.length; + } + return diff; + }); + let lastModifiedOffset = text.length; + for (let i = sortedEdits.length - 1; i >= 0; i--) { + let e = sortedEdits[i]; + if (e.offset + e.length <= lastModifiedOffset) { + text = applyEdit(text, e); + } + else { + throw new Error('Overlapping edit'); + } + lastModifiedOffset = e.offset; + } + return text; +} + +var main$3 = /*#__PURE__*/Object.freeze({ + __proto__: null, + get ParseErrorCode () { return ParseErrorCode; }, + get ScanError () { return ScanError; }, + get SyntaxKind () { return SyntaxKind; }, + applyEdits: applyEdits, + createScanner: createScanner, + findNodeAtLocation: findNodeAtLocation, + findNodeAtOffset: findNodeAtOffset, + format: format, + getLocation: getLocation, + getNodePath: getNodePath, + getNodeValue: getNodeValue, + modify: modify, + parse: parse$4, + parseTree: parseTree, + printParseErrorCode: printParseErrorCode, + stripComments: stripComments, + visit: visit$1 +}); + +var require$$3 = /*@__PURE__*/getAugmentedNamespace(main$3); + +var marked$1 = {}; + +/** + * marked v4.3.0 - a markdown parser + * Copyright (c) 2011-2023, Christopher Jeffrey. (MIT Licensed) + * https://github.com/markedjs/marked + */ + +(function (exports) { + + function _defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ("value" in descriptor) descriptor.writable = true; + Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); + } + } + function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + Object.defineProperty(Constructor, "prototype", { + writable: false + }); + return Constructor; + } + function _extends() { + _extends = Object.assign ? Object.assign.bind() : function (target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i]; + for (var key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + target[key] = source[key]; + } + } + } + return target; + }; + return _extends.apply(this, arguments); + } + 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 _createForOfIteratorHelperLoose(o, allowArrayLike) { + var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; + if (it) return (it = it.call(o)).next.bind(it); + if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { + if (it) o = it; + var i = 0; + return function () { + if (i >= o.length) return { + done: true + }; + return { + done: false, + value: o[i++] + }; + }; + } + throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); + } + function _toPrimitive(input, hint) { + if (typeof input !== "object" || input === null) return input; + var prim = input[Symbol.toPrimitive]; + if (prim !== undefined) { + var res = prim.call(input, hint || "default"); + if (typeof res !== "object") return res; + throw new TypeError("@@toPrimitive must return a primitive value."); + } + return (hint === "string" ? String : Number)(input); + } + function _toPropertyKey(arg) { + var key = _toPrimitive(arg, "string"); + return typeof key === "symbol" ? key : String(key); + } + + function getDefaults() { + return { + async: false, + baseUrl: null, + breaks: false, + extensions: null, + gfm: true, + headerIds: true, + headerPrefix: '', + highlight: null, + hooks: null, + langPrefix: 'language-', + mangle: true, + pedantic: false, + renderer: null, + sanitize: false, + sanitizer: null, + silent: false, + smartypants: false, + tokenizer: null, + walkTokens: null, + xhtml: false + }; + } + exports.defaults = getDefaults(); + function changeDefaults(newDefaults) { + exports.defaults = newDefaults; + } + + /** + * Helpers + */ + var escapeTest = /[&<>"']/; + var escapeReplace = new RegExp(escapeTest.source, 'g'); + var escapeTestNoEncode = /[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/; + var escapeReplaceNoEncode = new RegExp(escapeTestNoEncode.source, 'g'); + var escapeReplacements = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''' + }; + var getEscapeReplacement = function getEscapeReplacement(ch) { + return escapeReplacements[ch]; + }; + function escape(html, encode) { + if (encode) { + if (escapeTest.test(html)) { + return html.replace(escapeReplace, getEscapeReplacement); + } + } else { + if (escapeTestNoEncode.test(html)) { + return html.replace(escapeReplaceNoEncode, getEscapeReplacement); + } + } + return html; + } + var unescapeTest = /&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig; + + /** + * @param {string} html + */ + function unescape(html) { + // explicitly match decimal, hex, and named HTML entities + return html.replace(unescapeTest, function (_, n) { + n = n.toLowerCase(); + if (n === 'colon') return ':'; + if (n.charAt(0) === '#') { + return n.charAt(1) === 'x' ? String.fromCharCode(parseInt(n.substring(2), 16)) : String.fromCharCode(+n.substring(1)); + } + return ''; + }); + } + var caret = /(^|[^\[])\^/g; + + /** + * @param {string | RegExp} regex + * @param {string} opt + */ + function edit(regex, opt) { + regex = typeof regex === 'string' ? regex : regex.source; + opt = opt || ''; + var obj = { + replace: function replace(name, val) { + val = val.source || val; + val = val.replace(caret, '$1'); + regex = regex.replace(name, val); + return obj; + }, + getRegex: function getRegex() { + return new RegExp(regex, opt); + } + }; + return obj; + } + var nonWordAndColonTest = /[^\w:]/g; + var originIndependentUrl = /^$|^[a-z][a-z0-9+.-]*:|^[?#]/i; + + /** + * @param {boolean} sanitize + * @param {string} base + * @param {string} href + */ + function cleanUrl(sanitize, base, href) { + if (sanitize) { + var prot; + try { + prot = decodeURIComponent(unescape(href)).replace(nonWordAndColonTest, '').toLowerCase(); + } catch (e) { + return null; + } + if (prot.indexOf('javascript:') === 0 || prot.indexOf('vbscript:') === 0 || prot.indexOf('data:') === 0) { + return null; + } + } + if (base && !originIndependentUrl.test(href)) { + href = resolveUrl(base, href); + } + try { + href = encodeURI(href).replace(/%25/g, '%'); + } catch (e) { + return null; + } + return href; + } + var baseUrls = {}; + var justDomain = /^[^:]+:\/*[^/]*$/; + var protocol = /^([^:]+:)[\s\S]*$/; + var domain = /^([^:]+:\/*[^/]*)[\s\S]*$/; + + /** + * @param {string} base + * @param {string} href + */ + function resolveUrl(base, href) { + if (!baseUrls[' ' + base]) { + // we can ignore everything in base after the last slash of its path component, + // but we might need to add _that_ + // https://tools.ietf.org/html/rfc3986#section-3 + if (justDomain.test(base)) { + baseUrls[' ' + base] = base + '/'; + } else { + baseUrls[' ' + base] = rtrim(base, '/', true); + } + } + base = baseUrls[' ' + base]; + var relativeBase = base.indexOf(':') === -1; + if (href.substring(0, 2) === '//') { + if (relativeBase) { + return href; + } + return base.replace(protocol, '$1') + href; + } else if (href.charAt(0) === '/') { + if (relativeBase) { + return href; + } + return base.replace(domain, '$1') + href; + } else { + return base + href; + } + } + var noopTest = { + exec: function noopTest() {} + }; + function splitCells(tableRow, count) { + // ensure that every cell-delimiting pipe has a space + // before it to distinguish it from an escaped pipe + var row = tableRow.replace(/\|/g, function (match, offset, str) { + var escaped = false, + curr = offset; + while (--curr >= 0 && str[curr] === '\\') { + escaped = !escaped; + } + if (escaped) { + // odd number of slashes means | is escaped + // so we leave it alone + return '|'; + } else { + // add space before unescaped | + return ' |'; + } + }), + cells = row.split(/ \|/); + var i = 0; + + // First/last cell in a row cannot be empty if it has no leading/trailing pipe + if (!cells[0].trim()) { + cells.shift(); + } + if (cells.length > 0 && !cells[cells.length - 1].trim()) { + cells.pop(); + } + if (cells.length > count) { + cells.splice(count); + } else { + while (cells.length < count) { + cells.push(''); + } + } + for (; i < cells.length; i++) { + // leading or trailing whitespace is ignored per the gfm spec + cells[i] = cells[i].trim().replace(/\\\|/g, '|'); + } + return cells; + } + + /** + * Remove trailing 'c's. Equivalent to str.replace(/c*$/, ''). + * /c*$/ is vulnerable to REDOS. + * + * @param {string} str + * @param {string} c + * @param {boolean} invert Remove suffix of non-c chars instead. Default falsey. + */ + function rtrim(str, c, invert) { + var l = str.length; + if (l === 0) { + return ''; + } + + // Length of suffix matching the invert condition. + var suffLen = 0; + + // Step left until we fail to match the invert condition. + while (suffLen < l) { + var currChar = str.charAt(l - suffLen - 1); + if (currChar === c && !invert) { + suffLen++; + } else if (currChar !== c && invert) { + suffLen++; + } else { + break; + } + } + return str.slice(0, l - suffLen); + } + function findClosingBracket(str, b) { + if (str.indexOf(b[1]) === -1) { + return -1; + } + var l = str.length; + var level = 0, + i = 0; + for (; i < l; i++) { + if (str[i] === '\\') { + i++; + } else if (str[i] === b[0]) { + level++; + } else if (str[i] === b[1]) { + level--; + if (level < 0) { + return i; + } + } + } + return -1; + } + function checkSanitizeDeprecation(opt) { + if (opt && opt.sanitize && !opt.silent) { + console.warn('marked(): sanitize and sanitizer parameters are deprecated since version 0.7.0, should not be used and will be removed in the future. Read more here: https://marked.js.org/#/USING_ADVANCED.md#options'); + } + } + + // copied from https://stackoverflow.com/a/5450113/806777 + /** + * @param {string} pattern + * @param {number} count + */ + function repeatString(pattern, count) { + if (count < 1) { + return ''; + } + var result = ''; + while (count > 1) { + if (count & 1) { + result += pattern; + } + count >>= 1; + pattern += pattern; + } + return result + pattern; + } + + function outputLink(cap, link, raw, lexer) { + var href = link.href; + var title = link.title ? escape(link.title) : null; + var text = cap[1].replace(/\\([\[\]])/g, '$1'); + if (cap[0].charAt(0) !== '!') { + lexer.state.inLink = true; + var token = { + type: 'link', + raw: raw, + href: href, + title: title, + text: text, + tokens: lexer.inlineTokens(text) + }; + lexer.state.inLink = false; + return token; + } + return { + type: 'image', + raw: raw, + href: href, + title: title, + text: escape(text) + }; + } + function indentCodeCompensation(raw, text) { + var matchIndentToCode = raw.match(/^(\s+)(?:```)/); + if (matchIndentToCode === null) { + return text; + } + var indentToCode = matchIndentToCode[1]; + return text.split('\n').map(function (node) { + var matchIndentInNode = node.match(/^\s+/); + if (matchIndentInNode === null) { + return node; + } + var indentInNode = matchIndentInNode[0]; + if (indentInNode.length >= indentToCode.length) { + return node.slice(indentToCode.length); + } + return node; + }).join('\n'); + } + + /** + * Tokenizer + */ + var Tokenizer = /*#__PURE__*/function () { + function Tokenizer(options) { + this.options = options || exports.defaults; + } + var _proto = Tokenizer.prototype; + _proto.space = function space(src) { + var cap = this.rules.block.newline.exec(src); + if (cap && cap[0].length > 0) { + return { + type: 'space', + raw: cap[0] + }; + } + }; + _proto.code = function code(src) { + var cap = this.rules.block.code.exec(src); + if (cap) { + var text = cap[0].replace(/^ {1,4}/gm, ''); + return { + type: 'code', + raw: cap[0], + codeBlockStyle: 'indented', + text: !this.options.pedantic ? rtrim(text, '\n') : text + }; + } + }; + _proto.fences = function fences(src) { + var cap = this.rules.block.fences.exec(src); + if (cap) { + var raw = cap[0]; + var text = indentCodeCompensation(raw, cap[3] || ''); + return { + type: 'code', + raw: raw, + lang: cap[2] ? cap[2].trim().replace(this.rules.inline._escapes, '$1') : cap[2], + text: text + }; + } + }; + _proto.heading = function heading(src) { + var cap = this.rules.block.heading.exec(src); + if (cap) { + var text = cap[2].trim(); + + // remove trailing #s + if (/#$/.test(text)) { + var trimmed = rtrim(text, '#'); + if (this.options.pedantic) { + text = trimmed.trim(); + } else if (!trimmed || / $/.test(trimmed)) { + // CommonMark requires space before trailing #s + text = trimmed.trim(); + } + } + return { + type: 'heading', + raw: cap[0], + depth: cap[1].length, + text: text, + tokens: this.lexer.inline(text) + }; + } + }; + _proto.hr = function hr(src) { + var cap = this.rules.block.hr.exec(src); + if (cap) { + return { + type: 'hr', + raw: cap[0] + }; + } + }; + _proto.blockquote = function blockquote(src) { + var cap = this.rules.block.blockquote.exec(src); + if (cap) { + var text = cap[0].replace(/^ *>[ \t]?/gm, ''); + var top = this.lexer.state.top; + this.lexer.state.top = true; + var tokens = this.lexer.blockTokens(text); + this.lexer.state.top = top; + return { + type: 'blockquote', + raw: cap[0], + tokens: tokens, + text: text + }; + } + }; + _proto.list = function list(src) { + var cap = this.rules.block.list.exec(src); + if (cap) { + var raw, istask, ischecked, indent, i, blankLine, endsWithBlankLine, line, nextLine, rawLine, itemContents, endEarly; + var bull = cap[1].trim(); + var isordered = bull.length > 1; + var list = { + type: 'list', + raw: '', + ordered: isordered, + start: isordered ? +bull.slice(0, -1) : '', + loose: false, + items: [] + }; + bull = isordered ? "\\d{1,9}\\" + bull.slice(-1) : "\\" + bull; + if (this.options.pedantic) { + bull = isordered ? bull : '[*+-]'; + } + + // Get next list item + var itemRegex = new RegExp("^( {0,3}" + bull + ")((?:[\t ][^\\n]*)?(?:\\n|$))"); + + // Check if current bullet point can start a new List Item + while (src) { + endEarly = false; + if (!(cap = itemRegex.exec(src))) { + break; + } + if (this.rules.block.hr.test(src)) { + // End list if bullet was actually HR (possibly move into itemRegex?) + break; + } + raw = cap[0]; + src = src.substring(raw.length); + line = cap[2].split('\n', 1)[0].replace(/^\t+/, function (t) { + return ' '.repeat(3 * t.length); + }); + nextLine = src.split('\n', 1)[0]; + if (this.options.pedantic) { + indent = 2; + itemContents = line.trimLeft(); + } else { + indent = cap[2].search(/[^ ]/); // Find first non-space char + indent = indent > 4 ? 1 : indent; // Treat indented code blocks (> 4 spaces) as having only 1 indent + itemContents = line.slice(indent); + indent += cap[1].length; + } + blankLine = false; + if (!line && /^ *$/.test(nextLine)) { + // Items begin with at most one blank line + raw += nextLine + '\n'; + src = src.substring(nextLine.length + 1); + endEarly = true; + } + if (!endEarly) { + var nextBulletRegex = new RegExp("^ {0," + Math.min(3, indent - 1) + "}(?:[*+-]|\\d{1,9}[.)])((?:[ \t][^\\n]*)?(?:\\n|$))"); + var hrRegex = new RegExp("^ {0," + Math.min(3, indent - 1) + "}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)"); + var fencesBeginRegex = new RegExp("^ {0," + Math.min(3, indent - 1) + "}(?:```|~~~)"); + var headingBeginRegex = new RegExp("^ {0," + Math.min(3, indent - 1) + "}#"); + + // Check if following lines should be included in List Item + while (src) { + rawLine = src.split('\n', 1)[0]; + nextLine = rawLine; + + // Re-align to follow commonmark nesting rules + if (this.options.pedantic) { + nextLine = nextLine.replace(/^ {1,4}(?=( {4})*[^ ])/g, ' '); + } + + // End list item if found code fences + if (fencesBeginRegex.test(nextLine)) { + break; + } + + // End list item if found start of new heading + if (headingBeginRegex.test(nextLine)) { + break; + } + + // End list item if found start of new bullet + if (nextBulletRegex.test(nextLine)) { + break; + } + + // Horizontal rule found + if (hrRegex.test(src)) { + break; + } + if (nextLine.search(/[^ ]/) >= indent || !nextLine.trim()) { + // Dedent if possible + itemContents += '\n' + nextLine.slice(indent); + } else { + // not enough indentation + if (blankLine) { + break; + } + + // paragraph continuation unless last line was a different block level element + if (line.search(/[^ ]/) >= 4) { + // indented code block + break; + } + if (fencesBeginRegex.test(line)) { + break; + } + if (headingBeginRegex.test(line)) { + break; + } + if (hrRegex.test(line)) { + break; + } + itemContents += '\n' + nextLine; + } + if (!blankLine && !nextLine.trim()) { + // Check if current line is blank + blankLine = true; + } + raw += rawLine + '\n'; + src = src.substring(rawLine.length + 1); + line = nextLine.slice(indent); + } + } + if (!list.loose) { + // If the previous item ended with a blank line, the list is loose + if (endsWithBlankLine) { + list.loose = true; + } else if (/\n *\n *$/.test(raw)) { + endsWithBlankLine = true; + } + } + + // Check for task list items + if (this.options.gfm) { + istask = /^\[[ xX]\] /.exec(itemContents); + if (istask) { + ischecked = istask[0] !== '[ ] '; + itemContents = itemContents.replace(/^\[[ xX]\] +/, ''); + } + } + list.items.push({ + type: 'list_item', + raw: raw, + task: !!istask, + checked: ischecked, + loose: false, + text: itemContents + }); + list.raw += raw; + } + + // Do not consume newlines at end of final item. Alternatively, make itemRegex *start* with any newlines to simplify/speed up endsWithBlankLine logic + list.items[list.items.length - 1].raw = raw.trimRight(); + list.items[list.items.length - 1].text = itemContents.trimRight(); + list.raw = list.raw.trimRight(); + var l = list.items.length; + + // Item child tokens handled here at end because we needed to have the final item to trim it first + for (i = 0; i < l; i++) { + this.lexer.state.top = false; + list.items[i].tokens = this.lexer.blockTokens(list.items[i].text, []); + if (!list.loose) { + // Check if list should be loose + var spacers = list.items[i].tokens.filter(function (t) { + return t.type === 'space'; + }); + var hasMultipleLineBreaks = spacers.length > 0 && spacers.some(function (t) { + return /\n.*\n/.test(t.raw); + }); + list.loose = hasMultipleLineBreaks; + } + } + + // Set all items to loose if list is loose + if (list.loose) { + for (i = 0; i < l; i++) { + list.items[i].loose = true; + } + } + return list; + } + }; + _proto.html = function html(src) { + var cap = this.rules.block.html.exec(src); + if (cap) { + var token = { + type: 'html', + raw: cap[0], + pre: !this.options.sanitizer && (cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style'), + text: cap[0] + }; + if (this.options.sanitize) { + var text = this.options.sanitizer ? this.options.sanitizer(cap[0]) : escape(cap[0]); + token.type = 'paragraph'; + token.text = text; + token.tokens = this.lexer.inline(text); + } + return token; + } + }; + _proto.def = function def(src) { + var cap = this.rules.block.def.exec(src); + if (cap) { + var tag = cap[1].toLowerCase().replace(/\s+/g, ' '); + var href = cap[2] ? cap[2].replace(/^<(.*)>$/, '$1').replace(this.rules.inline._escapes, '$1') : ''; + var title = cap[3] ? cap[3].substring(1, cap[3].length - 1).replace(this.rules.inline._escapes, '$1') : cap[3]; + return { + type: 'def', + tag: tag, + raw: cap[0], + href: href, + title: title + }; + } + }; + _proto.table = function table(src) { + var cap = this.rules.block.table.exec(src); + if (cap) { + var item = { + type: 'table', + header: splitCells(cap[1]).map(function (c) { + return { + text: c + }; + }), + align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */), + rows: cap[3] && cap[3].trim() ? cap[3].replace(/\n[ \t]*$/, '').split('\n') : [] + }; + if (item.header.length === item.align.length) { + item.raw = cap[0]; + var l = item.align.length; + var i, j, k, row; + for (i = 0; i < l; i++) { + if (/^ *-+: *$/.test(item.align[i])) { + item.align[i] = 'right'; + } else if (/^ *:-+: *$/.test(item.align[i])) { + item.align[i] = 'center'; + } else if (/^ *:-+ *$/.test(item.align[i])) { + item.align[i] = 'left'; + } else { + item.align[i] = null; + } + } + l = item.rows.length; + for (i = 0; i < l; i++) { + item.rows[i] = splitCells(item.rows[i], item.header.length).map(function (c) { + return { + text: c + }; + }); + } + + // parse child tokens inside headers and cells + + // header child tokens + l = item.header.length; + for (j = 0; j < l; j++) { + item.header[j].tokens = this.lexer.inline(item.header[j].text); + } + + // cell child tokens + l = item.rows.length; + for (j = 0; j < l; j++) { + row = item.rows[j]; + for (k = 0; k < row.length; k++) { + row[k].tokens = this.lexer.inline(row[k].text); + } + } + return item; + } + } + }; + _proto.lheading = function lheading(src) { + var cap = this.rules.block.lheading.exec(src); + if (cap) { + return { + type: 'heading', + raw: cap[0], + depth: cap[2].charAt(0) === '=' ? 1 : 2, + text: cap[1], + tokens: this.lexer.inline(cap[1]) + }; + } + }; + _proto.paragraph = function paragraph(src) { + var cap = this.rules.block.paragraph.exec(src); + if (cap) { + var text = cap[1].charAt(cap[1].length - 1) === '\n' ? cap[1].slice(0, -1) : cap[1]; + return { + type: 'paragraph', + raw: cap[0], + text: text, + tokens: this.lexer.inline(text) + }; + } + }; + _proto.text = function text(src) { + var cap = this.rules.block.text.exec(src); + if (cap) { + return { + type: 'text', + raw: cap[0], + text: cap[0], + tokens: this.lexer.inline(cap[0]) + }; + } + }; + _proto.escape = function escape$1(src) { + var cap = this.rules.inline.escape.exec(src); + if (cap) { + return { + type: 'escape', + raw: cap[0], + text: escape(cap[1]) + }; + } + }; + _proto.tag = function tag(src) { + var cap = this.rules.inline.tag.exec(src); + if (cap) { + if (!this.lexer.state.inLink && /^<a /i.test(cap[0])) { + this.lexer.state.inLink = true; + } else if (this.lexer.state.inLink && /^<\/a>/i.test(cap[0])) { + this.lexer.state.inLink = false; + } + if (!this.lexer.state.inRawBlock && /^<(pre|code|kbd|script)(\s|>)/i.test(cap[0])) { + this.lexer.state.inRawBlock = true; + } else if (this.lexer.state.inRawBlock && /^<\/(pre|code|kbd|script)(\s|>)/i.test(cap[0])) { + this.lexer.state.inRawBlock = false; + } + return { + type: this.options.sanitize ? 'text' : 'html', + raw: cap[0], + inLink: this.lexer.state.inLink, + inRawBlock: this.lexer.state.inRawBlock, + text: this.options.sanitize ? this.options.sanitizer ? this.options.sanitizer(cap[0]) : escape(cap[0]) : cap[0] + }; + } + }; + _proto.link = function link(src) { + var cap = this.rules.inline.link.exec(src); + if (cap) { + var trimmedUrl = cap[2].trim(); + if (!this.options.pedantic && /^</.test(trimmedUrl)) { + // commonmark requires matching angle brackets + if (!/>$/.test(trimmedUrl)) { + return; + } + + // ending angle bracket cannot be escaped + var rtrimSlash = rtrim(trimmedUrl.slice(0, -1), '\\'); + if ((trimmedUrl.length - rtrimSlash.length) % 2 === 0) { + return; + } + } else { + // find closing parenthesis + var lastParenIndex = findClosingBracket(cap[2], '()'); + if (lastParenIndex > -1) { + var start = cap[0].indexOf('!') === 0 ? 5 : 4; + var linkLen = start + cap[1].length + lastParenIndex; + cap[2] = cap[2].substring(0, lastParenIndex); + cap[0] = cap[0].substring(0, linkLen).trim(); + cap[3] = ''; + } + } + var href = cap[2]; + var title = ''; + if (this.options.pedantic) { + // split pedantic href and title + var link = /^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(href); + if (link) { + href = link[1]; + title = link[3]; + } + } else { + title = cap[3] ? cap[3].slice(1, -1) : ''; + } + href = href.trim(); + if (/^</.test(href)) { + if (this.options.pedantic && !/>$/.test(trimmedUrl)) { + // pedantic allows starting angle bracket without ending angle bracket + href = href.slice(1); + } else { + href = href.slice(1, -1); + } + } + return outputLink(cap, { + href: href ? href.replace(this.rules.inline._escapes, '$1') : href, + title: title ? title.replace(this.rules.inline._escapes, '$1') : title + }, cap[0], this.lexer); + } + }; + _proto.reflink = function reflink(src, links) { + var cap; + if ((cap = this.rules.inline.reflink.exec(src)) || (cap = this.rules.inline.nolink.exec(src))) { + var link = (cap[2] || cap[1]).replace(/\s+/g, ' '); + link = links[link.toLowerCase()]; + if (!link) { + var text = cap[0].charAt(0); + return { + type: 'text', + raw: text, + text: text + }; + } + return outputLink(cap, link, cap[0], this.lexer); + } + }; + _proto.emStrong = function emStrong(src, maskedSrc, prevChar) { + if (prevChar === void 0) { + prevChar = ''; + } + var match = this.rules.inline.emStrong.lDelim.exec(src); + if (!match) return; + + // _ can't be between two alphanumerics. \p{L}\p{N} includes non-english alphabet/numbers as well + if (match[3] && prevChar.match(/(?:[0-9A-Za-z\xAA\xB2\xB3\xB5\xB9\xBA\xBC-\xBE\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0560-\u0588\u05D0-\u05EA\u05EF-\u05F2\u0620-\u064A\u0660-\u0669\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07C0-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u0870-\u0887\u0889-\u088E\u08A0-\u08C9\u0904-\u0939\u093D\u0950\u0958-\u0961\u0966-\u096F\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09E6-\u09F1\u09F4-\u09F9\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A66-\u0A6F\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AE6-\u0AEF\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B66-\u0B6F\u0B71-\u0B77\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0BE6-\u0BF2\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C5D\u0C60\u0C61\u0C66-\u0C6F\u0C78-\u0C7E\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDD\u0CDE\u0CE0\u0CE1\u0CE6-\u0CEF\u0CF1\u0CF2\u0D04-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D58-\u0D61\u0D66-\u0D78\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DE6-\u0DEF\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F20-\u0F33\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F-\u1049\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u1090-\u1099\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1369-\u137C\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u1711\u171F-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u17E0-\u17E9\u17F0-\u17F9\u1810-\u1819\u1820-\u1878\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A16\u1A20-\u1A54\u1A80-\u1A89\u1A90-\u1A99\u1AA7\u1B05-\u1B33\u1B45-\u1B4C\u1B50-\u1B59\u1B83-\u1BA0\u1BAE-\u1BE5\u1C00-\u1C23\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1C90-\u1CBA\u1CBD-\u1CBF\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5\u1CF6\u1CFA\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2070\u2071\u2074-\u2079\u207F-\u2089\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2150-\u2189\u2460-\u249B\u24EA-\u24FF\u2776-\u2793\u2C00-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2CFD\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u3192-\u3195\u31A0-\u31BF\u31F0-\u31FF\u3220-\u3229\u3248-\u324F\u3251-\u325F\u3280-\u3289\u32B1-\u32BF\u3400-\u4DBF\u4E00-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7CA\uA7D0\uA7D1\uA7D3\uA7D5-\uA7D9\uA7F2-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA830-\uA835\uA840-\uA873\uA882-\uA8B3\uA8D0-\uA8D9\uA8F2-\uA8F7\uA8FB\uA8FD\uA8FE\uA900-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF-\uA9D9\uA9E0-\uA9E4\uA9E6-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA50-\uAA59\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB69\uAB70-\uABE2\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD07-\uDD33\uDD40-\uDD78\uDD8A\uDD8B\uDE80-\uDE9C\uDEA0-\uDED0\uDEE1-\uDEFB\uDF00-\uDF23\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDD70-\uDD7A\uDD7C-\uDD8A\uDD8C-\uDD92\uDD94\uDD95\uDD97-\uDDA1\uDDA3-\uDDB1\uDDB3-\uDDB9\uDDBB\uDDBC\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67\uDF80-\uDF85\uDF87-\uDFB0\uDFB2-\uDFBA]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC58-\uDC76\uDC79-\uDC9E\uDCA7-\uDCAF\uDCE0-\uDCF2\uDCF4\uDCF5\uDCFB-\uDD1B\uDD20-\uDD39\uDD80-\uDDB7\uDDBC-\uDDCF\uDDD2-\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE35\uDE40-\uDE48\uDE60-\uDE7E\uDE80-\uDE9F\uDEC0-\uDEC7\uDEC9-\uDEE4\uDEEB-\uDEEF\uDF00-\uDF35\uDF40-\uDF55\uDF58-\uDF72\uDF78-\uDF91\uDFA9-\uDFAF]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2\uDCFA-\uDD23\uDD30-\uDD39\uDE60-\uDE7E\uDE80-\uDEA9\uDEB0\uDEB1\uDF00-\uDF27\uDF30-\uDF45\uDF51-\uDF54\uDF70-\uDF81\uDFB0-\uDFCB\uDFE0-\uDFF6]|\uD804[\uDC03-\uDC37\uDC52-\uDC6F\uDC71\uDC72\uDC75\uDC83-\uDCAF\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD03-\uDD26\uDD36-\uDD3F\uDD44\uDD47\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDD0-\uDDDA\uDDDC\uDDE1-\uDDF4\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDEF0-\uDEF9\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC50-\uDC59\uDC5F-\uDC61\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE50-\uDE59\uDE80-\uDEAA\uDEB8\uDEC0-\uDEC9\uDF00-\uDF1A\uDF30-\uDF3B\uDF40-\uDF46]|\uD806[\uDC00-\uDC2B\uDCA0-\uDCF2\uDCFF-\uDD06\uDD09\uDD0C-\uDD13\uDD15\uDD16\uDD18-\uDD2F\uDD3F\uDD41\uDD50-\uDD59\uDDA0-\uDDA7\uDDAA-\uDDD0\uDDE1\uDDE3\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE89\uDE9D\uDEB0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC50-\uDC6C\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46\uDD50-\uDD59\uDD60-\uDD65\uDD67\uDD68\uDD6A-\uDD89\uDD98\uDDA0-\uDDA9\uDEE0-\uDEF2\uDFB0\uDFC0-\uDFD4]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|\uD80B[\uDF90-\uDFF0]|[\uD80C\uD81C-\uD820\uD822\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879\uD880-\uD883][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDE70-\uDEBE\uDEC0-\uDEC9\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF50-\uDF59\uDF5B-\uDF61\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDE40-\uDE96\uDF00-\uDF4A\uDF50\uDF93-\uDF9F\uDFE0\uDFE1\uDFE3]|\uD821[\uDC00-\uDFF7]|\uD823[\uDC00-\uDCD5\uDD00-\uDD08]|\uD82B[\uDFF0-\uDFF3\uDFF5-\uDFFB\uDFFD\uDFFE]|\uD82C[\uDC00-\uDD22\uDD50-\uDD52\uDD64-\uDD67\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD834[\uDEE0-\uDEF3\uDF60-\uDF78]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD837[\uDF00-\uDF1E]|\uD838[\uDD00-\uDD2C\uDD37-\uDD3D\uDD40-\uDD49\uDD4E\uDE90-\uDEAD\uDEC0-\uDEEB\uDEF0-\uDEF9]|\uD839[\uDFE0-\uDFE6\uDFE8-\uDFEB\uDFED\uDFEE\uDFF0-\uDFFE]|\uD83A[\uDC00-\uDCC4\uDCC7-\uDCCF\uDD00-\uDD43\uDD4B\uDD50-\uDD59]|\uD83B[\uDC71-\uDCAB\uDCAD-\uDCAF\uDCB1-\uDCB4\uDD01-\uDD2D\uDD2F-\uDD3D\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD83C[\uDD00-\uDD0C]|\uD83E[\uDFF0-\uDFF9]|\uD869[\uDC00-\uDEDF\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF38\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uD884[\uDC00-\uDF4A])/)) return; + var nextChar = match[1] || match[2] || ''; + if (!nextChar || nextChar && (prevChar === '' || this.rules.inline.punctuation.exec(prevChar))) { + var lLength = match[0].length - 1; + var rDelim, + rLength, + delimTotal = lLength, + midDelimTotal = 0; + var endReg = match[0][0] === '*' ? this.rules.inline.emStrong.rDelimAst : this.rules.inline.emStrong.rDelimUnd; + endReg.lastIndex = 0; + + // Clip maskedSrc to same section of string as src (move to lexer?) + maskedSrc = maskedSrc.slice(-1 * src.length + lLength); + while ((match = endReg.exec(maskedSrc)) != null) { + rDelim = match[1] || match[2] || match[3] || match[4] || match[5] || match[6]; + if (!rDelim) continue; // skip single * in __abc*abc__ + + rLength = rDelim.length; + if (match[3] || match[4]) { + // found another Left Delim + delimTotal += rLength; + continue; + } else if (match[5] || match[6]) { + // either Left or Right Delim + if (lLength % 3 && !((lLength + rLength) % 3)) { + midDelimTotal += rLength; + continue; // CommonMark Emphasis Rules 9-10 + } + } + + delimTotal -= rLength; + if (delimTotal > 0) continue; // Haven't found enough closing delimiters + + // Remove extra characters. *a*** -> *a* + rLength = Math.min(rLength, rLength + delimTotal + midDelimTotal); + var raw = src.slice(0, lLength + match.index + (match[0].length - rDelim.length) + rLength); + + // Create `em` if smallest delimiter has odd char count. *a*** + if (Math.min(lLength, rLength) % 2) { + var _text = raw.slice(1, -1); + return { + type: 'em', + raw: raw, + text: _text, + tokens: this.lexer.inlineTokens(_text) + }; + } + + // Create 'strong' if smallest delimiter has even char count. **a*** + var text = raw.slice(2, -2); + return { + type: 'strong', + raw: raw, + text: text, + tokens: this.lexer.inlineTokens(text) + }; + } + } + }; + _proto.codespan = function codespan(src) { + var cap = this.rules.inline.code.exec(src); + if (cap) { + var text = cap[2].replace(/\n/g, ' '); + var hasNonSpaceChars = /[^ ]/.test(text); + var hasSpaceCharsOnBothEnds = /^ /.test(text) && / $/.test(text); + if (hasNonSpaceChars && hasSpaceCharsOnBothEnds) { + text = text.substring(1, text.length - 1); + } + text = escape(text, true); + return { + type: 'codespan', + raw: cap[0], + text: text + }; + } + }; + _proto.br = function br(src) { + var cap = this.rules.inline.br.exec(src); + if (cap) { + return { + type: 'br', + raw: cap[0] + }; + } + }; + _proto.del = function del(src) { + var cap = this.rules.inline.del.exec(src); + if (cap) { + return { + type: 'del', + raw: cap[0], + text: cap[2], + tokens: this.lexer.inlineTokens(cap[2]) + }; + } + }; + _proto.autolink = function autolink(src, mangle) { + var cap = this.rules.inline.autolink.exec(src); + if (cap) { + var text, href; + if (cap[2] === '@') { + text = escape(this.options.mangle ? mangle(cap[1]) : cap[1]); + href = 'mailto:' + text; + } else { + text = escape(cap[1]); + href = text; + } + return { + type: 'link', + raw: cap[0], + text: text, + href: href, + tokens: [{ + type: 'text', + raw: text, + text: text + }] + }; + } + }; + _proto.url = function url(src, mangle) { + var cap; + if (cap = this.rules.inline.url.exec(src)) { + var text, href; + if (cap[2] === '@') { + text = escape(this.options.mangle ? mangle(cap[0]) : cap[0]); + href = 'mailto:' + text; + } else { + // do extended autolink path validation + var prevCapZero; + do { + prevCapZero = cap[0]; + cap[0] = this.rules.inline._backpedal.exec(cap[0])[0]; + } while (prevCapZero !== cap[0]); + text = escape(cap[0]); + if (cap[1] === 'www.') { + href = 'http://' + cap[0]; + } else { + href = cap[0]; + } + } + return { + type: 'link', + raw: cap[0], + text: text, + href: href, + tokens: [{ + type: 'text', + raw: text, + text: text + }] + }; + } + }; + _proto.inlineText = function inlineText(src, smartypants) { + var cap = this.rules.inline.text.exec(src); + if (cap) { + var text; + if (this.lexer.state.inRawBlock) { + text = this.options.sanitize ? this.options.sanitizer ? this.options.sanitizer(cap[0]) : escape(cap[0]) : cap[0]; + } else { + text = escape(this.options.smartypants ? smartypants(cap[0]) : cap[0]); + } + return { + type: 'text', + raw: cap[0], + text: text + }; + } + }; + return Tokenizer; + }(); + + /** + * Block-Level Grammar + */ + var block = { + newline: /^(?: *(?:\n|$))+/, + code: /^( {4}[^\n]+(?:\n(?: *(?:\n|$))*)?)+/, + fences: /^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/, + hr: /^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/, + heading: /^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/, + blockquote: /^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/, + list: /^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/, + html: '^ {0,3}(?:' // optional indentation + + '<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)' // (1) + + '|comment[^\\n]*(\\n+|$)' // (2) + + '|<\\?[\\s\\S]*?(?:\\?>\\n*|$)' // (3) + + '|<![A-Z][\\s\\S]*?(?:>\\n*|$)' // (4) + + '|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)' // (5) + + '|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n *)+\\n|$)' // (6) + + '|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$)' // (7) open tag + + '|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$)' // (7) closing tag + + ')', + def: /^ {0,3}\[(label)\]: *(?:\n *)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n *)?| *\n *)(title))? *(?:\n+|$)/, + table: noopTest, + lheading: /^((?:.|\n(?!\n))+?)\n {0,3}(=+|-+) *(?:\n+|$)/, + // regex template, placeholders will be replaced according to different paragraph + // interruption rules of commonmark and the original markdown spec: + _paragraph: /^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/, + text: /^[^\n]+/ + }; + block._label = /(?!\s*\])(?:\\.|[^\[\]\\])+/; + block._title = /(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/; + block.def = edit(block.def).replace('label', block._label).replace('title', block._title).getRegex(); + block.bullet = /(?:[*+-]|\d{1,9}[.)])/; + block.listItemStart = edit(/^( *)(bull) */).replace('bull', block.bullet).getRegex(); + block.list = edit(block.list).replace(/bull/g, block.bullet).replace('hr', '\\n+(?=\\1?(?:(?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$))').replace('def', '\\n+(?=' + block.def.source + ')').getRegex(); + block._tag = 'address|article|aside|base|basefont|blockquote|body|caption' + '|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption' + '|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe' + '|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option' + '|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr' + '|track|ul'; + block._comment = /<!--(?!-?>)[\s\S]*?(?:-->|$)/; + block.html = edit(block.html, 'i').replace('comment', block._comment).replace('tag', block._tag).replace('attribute', / +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(); + block.paragraph = edit(block._paragraph).replace('hr', block.hr).replace('heading', ' {0,3}#{1,6} ').replace('|lheading', '') // setex headings don't interrupt commonmark paragraphs + .replace('|table', '').replace('blockquote', ' {0,3}>').replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n').replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt + .replace('html', '</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)').replace('tag', block._tag) // pars can be interrupted by type (6) html blocks + .getRegex(); + block.blockquote = edit(block.blockquote).replace('paragraph', block.paragraph).getRegex(); + + /** + * Normal Block Grammar + */ + + block.normal = _extends({}, block); + + /** + * GFM Block Grammar + */ + + block.gfm = _extends({}, block.normal, { + table: '^ *([^\\n ].*\\|.*)\\n' // Header + + ' {0,3}(?:\\| *)?(:?-+:? *(?:\\| *:?-+:? *)*)(?:\\| *)?' // Align + + '(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)' // Cells + }); + + block.gfm.table = edit(block.gfm.table).replace('hr', block.hr).replace('heading', ' {0,3}#{1,6} ').replace('blockquote', ' {0,3}>').replace('code', ' {4}[^\\n]').replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n').replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt + .replace('html', '</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)').replace('tag', block._tag) // tables can be interrupted by type (6) html blocks + .getRegex(); + block.gfm.paragraph = edit(block._paragraph).replace('hr', block.hr).replace('heading', ' {0,3}#{1,6} ').replace('|lheading', '') // setex headings don't interrupt commonmark paragraphs + .replace('table', block.gfm.table) // interrupt paragraphs with table + .replace('blockquote', ' {0,3}>').replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n').replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt + .replace('html', '</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)').replace('tag', block._tag) // pars can be interrupted by type (6) html blocks + .getRegex(); + /** + * Pedantic grammar (original John Gruber's loose markdown specification) + */ + + block.pedantic = _extends({}, block.normal, { + html: edit('^ *(?:comment *(?:\\n|\\s*$)' + '|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)' // closed tag + + '|<tag(?:"[^"]*"|\'[^\']*\'|\\s[^\'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))').replace('comment', block._comment).replace(/tag/g, '(?!(?:' + 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub' + '|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)' + '\\b)\\w+(?!:|[^\\w\\s@]*@)\\b').getRegex(), + def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/, + heading: /^(#{1,6})(.*)(?:\n+|$)/, + fences: noopTest, + // fences not supported + lheading: /^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/, + paragraph: edit(block.normal._paragraph).replace('hr', block.hr).replace('heading', ' *#{1,6} *[^\n]').replace('lheading', block.lheading).replace('blockquote', ' {0,3}>').replace('|fences', '').replace('|list', '').replace('|html', '').getRegex() + }); + + /** + * Inline-Level Grammar + */ + var inline = { + escape: /^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/, + autolink: /^<(scheme:[^\s\x00-\x1f<>]*|email)>/, + url: noopTest, + tag: '^comment' + '|^</[a-zA-Z][\\w:-]*\\s*>' // self-closing tag + + '|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>' // open tag + + '|^<\\?[\\s\\S]*?\\?>' // processing instruction, e.g. <?php ?> + + '|^<![a-zA-Z]+\\s[\\s\\S]*?>' // declaration, e.g. <!DOCTYPE html> + + '|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>', + // CDATA section + link: /^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/, + reflink: /^!?\[(label)\]\[(ref)\]/, + nolink: /^!?\[(ref)\](?:\[\])?/, + reflinkSearch: 'reflink|nolink(?!\\()', + emStrong: { + lDelim: /^(?:\*+(?:([punct_])|[^\s*]))|^_+(?:([punct*])|([^\s_]))/, + // (1) and (2) can only be a Right Delimiter. (3) and (4) can only be Left. (5) and (6) can be either Left or Right. + // () Skip orphan inside strong () Consume to delim (1) #*** (2) a***#, a*** (3) #***a, ***a (4) ***# (5) #***# (6) a***a + rDelimAst: /^(?:[^_*\\]|\\.)*?\_\_(?:[^_*\\]|\\.)*?\*(?:[^_*\\]|\\.)*?(?=\_\_)|(?:[^*\\]|\\.)+(?=[^*])|[punct_](\*+)(?=[\s]|$)|(?:[^punct*_\s\\]|\\.)(\*+)(?=[punct_\s]|$)|[punct_\s](\*+)(?=[^punct*_\s])|[\s](\*+)(?=[punct_])|[punct_](\*+)(?=[punct_])|(?:[^punct*_\s\\]|\\.)(\*+)(?=[^punct*_\s])/, + rDelimUnd: /^(?:[^_*\\]|\\.)*?\*\*(?:[^_*\\]|\\.)*?\_(?:[^_*\\]|\\.)*?(?=\*\*)|(?:[^_\\]|\\.)+(?=[^_])|[punct*](\_+)(?=[\s]|$)|(?:[^punct*_\s\\]|\\.)(\_+)(?=[punct*\s]|$)|[punct*\s](\_+)(?=[^punct*_\s])|[\s](\_+)(?=[punct*])|[punct*](\_+)(?=[punct*])/ // ^- Not allowed for _ + }, + + code: /^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/, + br: /^( {2,}|\\)\n(?!\s*$)/, + del: noopTest, + text: /^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/, + punctuation: /^([\spunctuation])/ + }; + + // list of punctuation marks from CommonMark spec + // without * and _ to handle the different emphasis markers * and _ + inline._punctuation = '!"#$%&\'()+\\-.,/:;<=>?@\\[\\]`^{|}~'; + inline.punctuation = edit(inline.punctuation).replace(/punctuation/g, inline._punctuation).getRegex(); + + // sequences em should skip over [title](link), `code`, <html> + inline.blockSkip = /\[[^\]]*?\]\([^\)]*?\)|`[^`]*?`|<[^>]*?>/g; + // lookbehind is not available on Safari as of version 16 + // inline.escapedEmSt = /(?<=(?:^|[^\\)(?:\\[^])*)\\[*_]/g; + inline.escapedEmSt = /(?:^|[^\\])(?:\\\\)*\\[*_]/g; + inline._comment = edit(block._comment).replace('(?:-->|$)', '-->').getRegex(); + inline.emStrong.lDelim = edit(inline.emStrong.lDelim).replace(/punct/g, inline._punctuation).getRegex(); + inline.emStrong.rDelimAst = edit(inline.emStrong.rDelimAst, 'g').replace(/punct/g, inline._punctuation).getRegex(); + inline.emStrong.rDelimUnd = edit(inline.emStrong.rDelimUnd, 'g').replace(/punct/g, inline._punctuation).getRegex(); + inline._escapes = /\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/g; + inline._scheme = /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/; + inline._email = /[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/; + inline.autolink = edit(inline.autolink).replace('scheme', inline._scheme).replace('email', inline._email).getRegex(); + inline._attribute = /\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/; + inline.tag = edit(inline.tag).replace('comment', inline._comment).replace('attribute', inline._attribute).getRegex(); + inline._label = /(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/; + inline._href = /<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/; + inline._title = /"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/; + inline.link = edit(inline.link).replace('label', inline._label).replace('href', inline._href).replace('title', inline._title).getRegex(); + inline.reflink = edit(inline.reflink).replace('label', inline._label).replace('ref', block._label).getRegex(); + inline.nolink = edit(inline.nolink).replace('ref', block._label).getRegex(); + inline.reflinkSearch = edit(inline.reflinkSearch, 'g').replace('reflink', inline.reflink).replace('nolink', inline.nolink).getRegex(); + + /** + * Normal Inline Grammar + */ + + inline.normal = _extends({}, inline); + + /** + * Pedantic Inline Grammar + */ + + inline.pedantic = _extends({}, inline.normal, { + strong: { + start: /^__|\*\*/, + middle: /^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/, + endAst: /\*\*(?!\*)/g, + endUnd: /__(?!_)/g + }, + em: { + start: /^_|\*/, + middle: /^()\*(?=\S)([\s\S]*?\S)\*(?!\*)|^_(?=\S)([\s\S]*?\S)_(?!_)/, + endAst: /\*(?!\*)/g, + endUnd: /_(?!_)/g + }, + link: edit(/^!?\[(label)\]\((.*?)\)/).replace('label', inline._label).getRegex(), + reflink: edit(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace('label', inline._label).getRegex() + }); + + /** + * GFM Inline Grammar + */ + + inline.gfm = _extends({}, inline.normal, { + escape: edit(inline.escape).replace('])', '~|])').getRegex(), + _extended_email: /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/, + url: /^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/, + _backpedal: /(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/, + del: /^(~~?)(?=[^\s~])([\s\S]*?[^\s~])\1(?=[^~]|$)/, + text: /^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/ + }); + inline.gfm.url = edit(inline.gfm.url, 'i').replace('email', inline.gfm._extended_email).getRegex(); + /** + * GFM + Line Breaks Inline Grammar + */ + + inline.breaks = _extends({}, inline.gfm, { + br: edit(inline.br).replace('{2,}', '*').getRegex(), + text: edit(inline.gfm.text).replace('\\b_', '\\b_| {2,}\\n').replace(/\{2,\}/g, '*').getRegex() + }); + + /** + * smartypants text replacement + * @param {string} text + */ + function smartypants(text) { + return text + // em-dashes + .replace(/---/g, "\u2014") + // en-dashes + .replace(/--/g, "\u2013") + // opening singles + .replace(/(^|[-\u2014/(\[{"\s])'/g, "$1\u2018") + // closing singles & apostrophes + .replace(/'/g, "\u2019") + // opening doubles + .replace(/(^|[-\u2014/(\[{\u2018\s])"/g, "$1\u201C") + // closing doubles + .replace(/"/g, "\u201D") + // ellipses + .replace(/\.{3}/g, "\u2026"); + } + + /** + * mangle email addresses + * @param {string} text + */ + function mangle(text) { + var out = '', + i, + ch; + var l = text.length; + for (i = 0; i < l; i++) { + ch = text.charCodeAt(i); + if (Math.random() > 0.5) { + ch = 'x' + ch.toString(16); + } + out += '&#' + ch + ';'; + } + return out; + } + + /** + * Block Lexer + */ + var Lexer = /*#__PURE__*/function () { + function Lexer(options) { + this.tokens = []; + this.tokens.links = Object.create(null); + this.options = options || exports.defaults; + this.options.tokenizer = this.options.tokenizer || new Tokenizer(); + this.tokenizer = this.options.tokenizer; + this.tokenizer.options = this.options; + this.tokenizer.lexer = this; + this.inlineQueue = []; + this.state = { + inLink: false, + inRawBlock: false, + top: true + }; + var rules = { + block: block.normal, + inline: inline.normal + }; + if (this.options.pedantic) { + rules.block = block.pedantic; + rules.inline = inline.pedantic; + } else if (this.options.gfm) { + rules.block = block.gfm; + if (this.options.breaks) { + rules.inline = inline.breaks; + } else { + rules.inline = inline.gfm; + } + } + this.tokenizer.rules = rules; + } + + /** + * Expose Rules + */ + /** + * Static Lex Method + */ + Lexer.lex = function lex(src, options) { + var lexer = new Lexer(options); + return lexer.lex(src); + } + + /** + * Static Lex Inline Method + */; + Lexer.lexInline = function lexInline(src, options) { + var lexer = new Lexer(options); + return lexer.inlineTokens(src); + } + + /** + * Preprocessing + */; + var _proto = Lexer.prototype; + _proto.lex = function lex(src) { + src = src.replace(/\r\n|\r/g, '\n'); + this.blockTokens(src, this.tokens); + var next; + while (next = this.inlineQueue.shift()) { + this.inlineTokens(next.src, next.tokens); + } + return this.tokens; + } + + /** + * Lexing + */; + _proto.blockTokens = function blockTokens(src, tokens) { + var _this = this; + if (tokens === void 0) { + tokens = []; + } + if (this.options.pedantic) { + src = src.replace(/\t/g, ' ').replace(/^ +$/gm, ''); + } else { + src = src.replace(/^( *)(\t+)/gm, function (_, leading, tabs) { + return leading + ' '.repeat(tabs.length); + }); + } + var token, lastToken, cutSrc, lastParagraphClipped; + while (src) { + if (this.options.extensions && this.options.extensions.block && this.options.extensions.block.some(function (extTokenizer) { + if (token = extTokenizer.call({ + lexer: _this + }, src, tokens)) { + src = src.substring(token.raw.length); + tokens.push(token); + return true; + } + return false; + })) { + continue; + } + + // newline + if (token = this.tokenizer.space(src)) { + src = src.substring(token.raw.length); + if (token.raw.length === 1 && tokens.length > 0) { + // if there's a single \n as a spacer, it's terminating the last line, + // so move it there so that we don't get unecessary paragraph tags + tokens[tokens.length - 1].raw += '\n'; + } else { + tokens.push(token); + } + continue; + } + + // code + if (token = this.tokenizer.code(src)) { + src = src.substring(token.raw.length); + lastToken = tokens[tokens.length - 1]; + // An indented code block cannot interrupt a paragraph. + if (lastToken && (lastToken.type === 'paragraph' || lastToken.type === 'text')) { + lastToken.raw += '\n' + token.raw; + lastToken.text += '\n' + token.text; + this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text; + } else { + tokens.push(token); + } + continue; + } + + // fences + if (token = this.tokenizer.fences(src)) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } + + // heading + if (token = this.tokenizer.heading(src)) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } + + // hr + if (token = this.tokenizer.hr(src)) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } + + // blockquote + if (token = this.tokenizer.blockquote(src)) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } + + // list + if (token = this.tokenizer.list(src)) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } + + // html + if (token = this.tokenizer.html(src)) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } + + // def + if (token = this.tokenizer.def(src)) { + src = src.substring(token.raw.length); + lastToken = tokens[tokens.length - 1]; + if (lastToken && (lastToken.type === 'paragraph' || lastToken.type === 'text')) { + lastToken.raw += '\n' + token.raw; + lastToken.text += '\n' + token.raw; + this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text; + } else if (!this.tokens.links[token.tag]) { + this.tokens.links[token.tag] = { + href: token.href, + title: token.title + }; + } + continue; + } + + // table (gfm) + if (token = this.tokenizer.table(src)) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } + + // lheading + if (token = this.tokenizer.lheading(src)) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } + + // top-level paragraph + // prevent paragraph consuming extensions by clipping 'src' to extension start + cutSrc = src; + if (this.options.extensions && this.options.extensions.startBlock) { + (function () { + var startIndex = Infinity; + var tempSrc = src.slice(1); + var tempStart = void 0; + _this.options.extensions.startBlock.forEach(function (getStartIndex) { + tempStart = getStartIndex.call({ + lexer: this + }, tempSrc); + if (typeof tempStart === 'number' && tempStart >= 0) { + startIndex = Math.min(startIndex, tempStart); + } + }); + if (startIndex < Infinity && startIndex >= 0) { + cutSrc = src.substring(0, startIndex + 1); + } + })(); + } + if (this.state.top && (token = this.tokenizer.paragraph(cutSrc))) { + lastToken = tokens[tokens.length - 1]; + if (lastParagraphClipped && lastToken.type === 'paragraph') { + lastToken.raw += '\n' + token.raw; + lastToken.text += '\n' + token.text; + this.inlineQueue.pop(); + this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text; + } else { + tokens.push(token); + } + lastParagraphClipped = cutSrc.length !== src.length; + src = src.substring(token.raw.length); + continue; + } + + // text + if (token = this.tokenizer.text(src)) { + src = src.substring(token.raw.length); + lastToken = tokens[tokens.length - 1]; + if (lastToken && lastToken.type === 'text') { + lastToken.raw += '\n' + token.raw; + lastToken.text += '\n' + token.text; + this.inlineQueue.pop(); + this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text; + } else { + tokens.push(token); + } + continue; + } + if (src) { + var errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0); + if (this.options.silent) { + console.error(errMsg); + break; + } else { + throw new Error(errMsg); + } + } + } + this.state.top = true; + return tokens; + }; + _proto.inline = function inline(src, tokens) { + if (tokens === void 0) { + tokens = []; + } + this.inlineQueue.push({ + src: src, + tokens: tokens + }); + return tokens; + } + + /** + * Lexing/Compiling + */; + _proto.inlineTokens = function inlineTokens(src, tokens) { + var _this2 = this; + if (tokens === void 0) { + tokens = []; + } + var token, lastToken, cutSrc; + + // String with links masked to avoid interference with em and strong + var maskedSrc = src; + var match; + var keepPrevChar, prevChar; + + // Mask out reflinks + if (this.tokens.links) { + var links = Object.keys(this.tokens.links); + if (links.length > 0) { + while ((match = this.tokenizer.rules.inline.reflinkSearch.exec(maskedSrc)) != null) { + if (links.includes(match[0].slice(match[0].lastIndexOf('[') + 1, -1))) { + maskedSrc = maskedSrc.slice(0, match.index) + '[' + repeatString('a', match[0].length - 2) + ']' + maskedSrc.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex); + } + } + } + } + // Mask out other blocks + while ((match = this.tokenizer.rules.inline.blockSkip.exec(maskedSrc)) != null) { + maskedSrc = maskedSrc.slice(0, match.index) + '[' + repeatString('a', match[0].length - 2) + ']' + maskedSrc.slice(this.tokenizer.rules.inline.blockSkip.lastIndex); + } + + // Mask out escaped em & strong delimiters + while ((match = this.tokenizer.rules.inline.escapedEmSt.exec(maskedSrc)) != null) { + maskedSrc = maskedSrc.slice(0, match.index + match[0].length - 2) + '++' + maskedSrc.slice(this.tokenizer.rules.inline.escapedEmSt.lastIndex); + this.tokenizer.rules.inline.escapedEmSt.lastIndex--; + } + while (src) { + if (!keepPrevChar) { + prevChar = ''; + } + keepPrevChar = false; + + // extensions + if (this.options.extensions && this.options.extensions.inline && this.options.extensions.inline.some(function (extTokenizer) { + if (token = extTokenizer.call({ + lexer: _this2 + }, src, tokens)) { + src = src.substring(token.raw.length); + tokens.push(token); + return true; + } + return false; + })) { + continue; + } + + // escape + if (token = this.tokenizer.escape(src)) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } + + // tag + if (token = this.tokenizer.tag(src)) { + src = src.substring(token.raw.length); + lastToken = tokens[tokens.length - 1]; + if (lastToken && token.type === 'text' && lastToken.type === 'text') { + lastToken.raw += token.raw; + lastToken.text += token.text; + } else { + tokens.push(token); + } + continue; + } + + // link + if (token = this.tokenizer.link(src)) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } + + // reflink, nolink + if (token = this.tokenizer.reflink(src, this.tokens.links)) { + src = src.substring(token.raw.length); + lastToken = tokens[tokens.length - 1]; + if (lastToken && token.type === 'text' && lastToken.type === 'text') { + lastToken.raw += token.raw; + lastToken.text += token.text; + } else { + tokens.push(token); + } + continue; + } + + // em & strong + if (token = this.tokenizer.emStrong(src, maskedSrc, prevChar)) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } + + // code + if (token = this.tokenizer.codespan(src)) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } + + // br + if (token = this.tokenizer.br(src)) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } + + // del (gfm) + if (token = this.tokenizer.del(src)) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } + + // autolink + if (token = this.tokenizer.autolink(src, mangle)) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } + + // url (gfm) + if (!this.state.inLink && (token = this.tokenizer.url(src, mangle))) { + src = src.substring(token.raw.length); + tokens.push(token); + continue; + } + + // text + // prevent inlineText consuming extensions by clipping 'src' to extension start + cutSrc = src; + if (this.options.extensions && this.options.extensions.startInline) { + (function () { + var startIndex = Infinity; + var tempSrc = src.slice(1); + var tempStart = void 0; + _this2.options.extensions.startInline.forEach(function (getStartIndex) { + tempStart = getStartIndex.call({ + lexer: this + }, tempSrc); + if (typeof tempStart === 'number' && tempStart >= 0) { + startIndex = Math.min(startIndex, tempStart); + } + }); + if (startIndex < Infinity && startIndex >= 0) { + cutSrc = src.substring(0, startIndex + 1); + } + })(); + } + if (token = this.tokenizer.inlineText(cutSrc, smartypants)) { + src = src.substring(token.raw.length); + if (token.raw.slice(-1) !== '_') { + // Track prevChar before string of ____ started + prevChar = token.raw.slice(-1); + } + keepPrevChar = true; + lastToken = tokens[tokens.length - 1]; + if (lastToken && lastToken.type === 'text') { + lastToken.raw += token.raw; + lastToken.text += token.text; + } else { + tokens.push(token); + } + continue; + } + if (src) { + var errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0); + if (this.options.silent) { + console.error(errMsg); + break; + } else { + throw new Error(errMsg); + } + } + } + return tokens; + }; + _createClass(Lexer, null, [{ + key: "rules", + get: function get() { + return { + block: block, + inline: inline + }; + } + }]); + return Lexer; + }(); + + /** + * Renderer + */ + var Renderer = /*#__PURE__*/function () { + function Renderer(options) { + this.options = options || exports.defaults; + } + var _proto = Renderer.prototype; + _proto.code = function code(_code, infostring, escaped) { + var lang = (infostring || '').match(/\S*/)[0]; + if (this.options.highlight) { + var out = this.options.highlight(_code, lang); + if (out != null && out !== _code) { + escaped = true; + _code = out; + } + } + _code = _code.replace(/\n$/, '') + '\n'; + if (!lang) { + return '<pre><code>' + (escaped ? _code : escape(_code, true)) + '</code></pre>\n'; + } + return '<pre><code class="' + this.options.langPrefix + escape(lang) + '">' + (escaped ? _code : escape(_code, true)) + '</code></pre>\n'; + } + + /** + * @param {string} quote + */; + _proto.blockquote = function blockquote(quote) { + return "<blockquote>\n" + quote + "</blockquote>\n"; + }; + _proto.html = function html(_html) { + return _html; + } + + /** + * @param {string} text + * @param {string} level + * @param {string} raw + * @param {any} slugger + */; + _proto.heading = function heading(text, level, raw, slugger) { + if (this.options.headerIds) { + var id = this.options.headerPrefix + slugger.slug(raw); + return "<h" + level + " id=\"" + id + "\">" + text + "</h" + level + ">\n"; + } + + // ignore IDs + return "<h" + level + ">" + text + "</h" + level + ">\n"; + }; + _proto.hr = function hr() { + return this.options.xhtml ? '<hr/>\n' : '<hr>\n'; + }; + _proto.list = function list(body, ordered, start) { + var type = ordered ? 'ol' : 'ul', + startatt = ordered && start !== 1 ? ' start="' + start + '"' : ''; + return '<' + type + startatt + '>\n' + body + '</' + type + '>\n'; + } + + /** + * @param {string} text + */; + _proto.listitem = function listitem(text) { + return "<li>" + text + "</li>\n"; + }; + _proto.checkbox = function checkbox(checked) { + return '<input ' + (checked ? 'checked="" ' : '') + 'disabled="" type="checkbox"' + (this.options.xhtml ? ' /' : '') + '> '; + } + + /** + * @param {string} text + */; + _proto.paragraph = function paragraph(text) { + return "<p>" + text + "</p>\n"; + } + + /** + * @param {string} header + * @param {string} body + */; + _proto.table = function table(header, body) { + if (body) body = "<tbody>" + body + "</tbody>"; + return '<table>\n' + '<thead>\n' + header + '</thead>\n' + body + '</table>\n'; + } + + /** + * @param {string} content + */; + _proto.tablerow = function tablerow(content) { + return "<tr>\n" + content + "</tr>\n"; + }; + _proto.tablecell = function tablecell(content, flags) { + var type = flags.header ? 'th' : 'td'; + var tag = flags.align ? "<" + type + " align=\"" + flags.align + "\">" : "<" + type + ">"; + return tag + content + ("</" + type + ">\n"); + } + + /** + * span level renderer + * @param {string} text + */; + _proto.strong = function strong(text) { + return "<strong>" + text + "</strong>"; + } + + /** + * @param {string} text + */; + _proto.em = function em(text) { + return "<em>" + text + "</em>"; + } + + /** + * @param {string} text + */; + _proto.codespan = function codespan(text) { + return "<code>" + text + "</code>"; + }; + _proto.br = function br() { + return this.options.xhtml ? '<br/>' : '<br>'; + } + + /** + * @param {string} text + */; + _proto.del = function del(text) { + return "<del>" + text + "</del>"; + } + + /** + * @param {string} href + * @param {string} title + * @param {string} text + */; + _proto.link = function link(href, title, text) { + href = cleanUrl(this.options.sanitize, this.options.baseUrl, href); + if (href === null) { + return text; + } + var out = '<a href="' + href + '"'; + if (title) { + out += ' title="' + title + '"'; + } + out += '>' + text + '</a>'; + return out; + } + + /** + * @param {string} href + * @param {string} title + * @param {string} text + */; + _proto.image = function image(href, title, text) { + href = cleanUrl(this.options.sanitize, this.options.baseUrl, href); + if (href === null) { + return text; + } + var out = "<img src=\"" + href + "\" alt=\"" + text + "\""; + if (title) { + out += " title=\"" + title + "\""; + } + out += this.options.xhtml ? '/>' : '>'; + return out; + }; + _proto.text = function text(_text) { + return _text; + }; + return Renderer; + }(); + + /** + * TextRenderer + * returns only the textual part of the token + */ + var TextRenderer = /*#__PURE__*/function () { + function TextRenderer() {} + var _proto = TextRenderer.prototype; + // no need for block level renderers + _proto.strong = function strong(text) { + return text; + }; + _proto.em = function em(text) { + return text; + }; + _proto.codespan = function codespan(text) { + return text; + }; + _proto.del = function del(text) { + return text; + }; + _proto.html = function html(text) { + return text; + }; + _proto.text = function text(_text) { + return _text; + }; + _proto.link = function link(href, title, text) { + return '' + text; + }; + _proto.image = function image(href, title, text) { + return '' + text; + }; + _proto.br = function br() { + return ''; + }; + return TextRenderer; + }(); + + /** + * Slugger generates header id + */ + var Slugger = /*#__PURE__*/function () { + function Slugger() { + this.seen = {}; + } + + /** + * @param {string} value + */ + var _proto = Slugger.prototype; + _proto.serialize = function serialize(value) { + return value.toLowerCase().trim() + // remove html tags + .replace(/<[!\/a-z].*?>/ig, '') + // remove unwanted chars + .replace(/[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,./:;<=>?@[\]^`{|}~]/g, '').replace(/\s/g, '-'); + } + + /** + * Finds the next safe (unique) slug to use + * @param {string} originalSlug + * @param {boolean} isDryRun + */; + _proto.getNextSafeSlug = function getNextSafeSlug(originalSlug, isDryRun) { + var slug = originalSlug; + var occurenceAccumulator = 0; + if (this.seen.hasOwnProperty(slug)) { + occurenceAccumulator = this.seen[originalSlug]; + do { + occurenceAccumulator++; + slug = originalSlug + '-' + occurenceAccumulator; + } while (this.seen.hasOwnProperty(slug)); + } + if (!isDryRun) { + this.seen[originalSlug] = occurenceAccumulator; + this.seen[slug] = 0; + } + return slug; + } + + /** + * Convert string to unique id + * @param {object} [options] + * @param {boolean} [options.dryrun] Generates the next unique slug without + * updating the internal accumulator. + */; + _proto.slug = function slug(value, options) { + if (options === void 0) { + options = {}; + } + var slug = this.serialize(value); + return this.getNextSafeSlug(slug, options.dryrun); + }; + return Slugger; + }(); + + /** + * Parsing & Compiling + */ + var Parser = /*#__PURE__*/function () { + function Parser(options) { + this.options = options || exports.defaults; + this.options.renderer = this.options.renderer || new Renderer(); + this.renderer = this.options.renderer; + this.renderer.options = this.options; + this.textRenderer = new TextRenderer(); + this.slugger = new Slugger(); + } + + /** + * Static Parse Method + */ + Parser.parse = function parse(tokens, options) { + var parser = new Parser(options); + return parser.parse(tokens); + } + + /** + * Static Parse Inline Method + */; + Parser.parseInline = function parseInline(tokens, options) { + var parser = new Parser(options); + return parser.parseInline(tokens); + } + + /** + * Parse Loop + */; + var _proto = Parser.prototype; + _proto.parse = function parse(tokens, top) { + if (top === void 0) { + top = true; + } + var out = '', + i, + j, + k, + l2, + l3, + row, + cell, + header, + body, + token, + ordered, + start, + loose, + itemBody, + item, + checked, + task, + checkbox, + ret; + var l = tokens.length; + for (i = 0; i < l; i++) { + token = tokens[i]; + + // Run any renderer extensions + if (this.options.extensions && this.options.extensions.renderers && this.options.extensions.renderers[token.type]) { + ret = this.options.extensions.renderers[token.type].call({ + parser: this + }, token); + if (ret !== false || !['space', 'hr', 'heading', 'code', 'table', 'blockquote', 'list', 'html', 'paragraph', 'text'].includes(token.type)) { + out += ret || ''; + continue; + } + } + switch (token.type) { + case 'space': + { + continue; + } + case 'hr': + { + out += this.renderer.hr(); + continue; + } + case 'heading': + { + out += this.renderer.heading(this.parseInline(token.tokens), token.depth, unescape(this.parseInline(token.tokens, this.textRenderer)), this.slugger); + continue; + } + case 'code': + { + out += this.renderer.code(token.text, token.lang, token.escaped); + continue; + } + case 'table': + { + header = ''; + + // header + cell = ''; + l2 = token.header.length; + for (j = 0; j < l2; j++) { + cell += this.renderer.tablecell(this.parseInline(token.header[j].tokens), { + header: true, + align: token.align[j] + }); + } + header += this.renderer.tablerow(cell); + body = ''; + l2 = token.rows.length; + for (j = 0; j < l2; j++) { + row = token.rows[j]; + cell = ''; + l3 = row.length; + for (k = 0; k < l3; k++) { + cell += this.renderer.tablecell(this.parseInline(row[k].tokens), { + header: false, + align: token.align[k] + }); + } + body += this.renderer.tablerow(cell); + } + out += this.renderer.table(header, body); + continue; + } + case 'blockquote': + { + body = this.parse(token.tokens); + out += this.renderer.blockquote(body); + continue; + } + case 'list': + { + ordered = token.ordered; + start = token.start; + loose = token.loose; + l2 = token.items.length; + body = ''; + for (j = 0; j < l2; j++) { + item = token.items[j]; + checked = item.checked; + task = item.task; + itemBody = ''; + if (item.task) { + checkbox = this.renderer.checkbox(checked); + if (loose) { + if (item.tokens.length > 0 && item.tokens[0].type === 'paragraph') { + item.tokens[0].text = checkbox + ' ' + item.tokens[0].text; + if (item.tokens[0].tokens && item.tokens[0].tokens.length > 0 && item.tokens[0].tokens[0].type === 'text') { + item.tokens[0].tokens[0].text = checkbox + ' ' + item.tokens[0].tokens[0].text; + } + } else { + item.tokens.unshift({ + type: 'text', + text: checkbox + }); + } + } else { + itemBody += checkbox; + } + } + itemBody += this.parse(item.tokens, loose); + body += this.renderer.listitem(itemBody, task, checked); + } + out += this.renderer.list(body, ordered, start); + continue; + } + case 'html': + { + // TODO parse inline content if parameter markdown=1 + out += this.renderer.html(token.text); + continue; + } + case 'paragraph': + { + out += this.renderer.paragraph(this.parseInline(token.tokens)); + continue; + } + case 'text': + { + body = token.tokens ? this.parseInline(token.tokens) : token.text; + while (i + 1 < l && tokens[i + 1].type === 'text') { + token = tokens[++i]; + body += '\n' + (token.tokens ? this.parseInline(token.tokens) : token.text); + } + out += top ? this.renderer.paragraph(body) : body; + continue; + } + default: + { + var errMsg = 'Token with "' + token.type + '" type was not found.'; + if (this.options.silent) { + console.error(errMsg); + return; + } else { + throw new Error(errMsg); + } + } + } + } + return out; + } + + /** + * Parse Inline Tokens + */; + _proto.parseInline = function parseInline(tokens, renderer) { + renderer = renderer || this.renderer; + var out = '', + i, + token, + ret; + var l = tokens.length; + for (i = 0; i < l; i++) { + token = tokens[i]; + + // Run any renderer extensions + if (this.options.extensions && this.options.extensions.renderers && this.options.extensions.renderers[token.type]) { + ret = this.options.extensions.renderers[token.type].call({ + parser: this + }, token); + if (ret !== false || !['escape', 'html', 'link', 'image', 'strong', 'em', 'codespan', 'br', 'del', 'text'].includes(token.type)) { + out += ret || ''; + continue; + } + } + switch (token.type) { + case 'escape': + { + out += renderer.text(token.text); + break; + } + case 'html': + { + out += renderer.html(token.text); + break; + } + case 'link': + { + out += renderer.link(token.href, token.title, this.parseInline(token.tokens, renderer)); + break; + } + case 'image': + { + out += renderer.image(token.href, token.title, token.text); + break; + } + case 'strong': + { + out += renderer.strong(this.parseInline(token.tokens, renderer)); + break; + } + case 'em': + { + out += renderer.em(this.parseInline(token.tokens, renderer)); + break; + } + case 'codespan': + { + out += renderer.codespan(token.text); + break; + } + case 'br': + { + out += renderer.br(); + break; + } + case 'del': + { + out += renderer.del(this.parseInline(token.tokens, renderer)); + break; + } + case 'text': + { + out += renderer.text(token.text); + break; + } + default: + { + var errMsg = 'Token with "' + token.type + '" type was not found.'; + if (this.options.silent) { + console.error(errMsg); + return; + } else { + throw new Error(errMsg); + } + } + } + } + return out; + }; + return Parser; + }(); + + var Hooks = /*#__PURE__*/function () { + function Hooks(options) { + this.options = options || exports.defaults; + } + var _proto = Hooks.prototype; + /** + * Process markdown before marked + */ + _proto.preprocess = function preprocess(markdown) { + return markdown; + } + + /** + * Process HTML after marked is finished + */; + _proto.postprocess = function postprocess(html) { + return html; + }; + return Hooks; + }(); + Hooks.passThroughHooks = new Set(['preprocess', 'postprocess']); + + function onError(silent, async, callback) { + return function (e) { + e.message += '\nPlease report this to https://github.com/markedjs/marked.'; + if (silent) { + var msg = '<p>An error occurred:</p><pre>' + escape(e.message + '', true) + '</pre>'; + if (async) { + return Promise.resolve(msg); + } + if (callback) { + callback(null, msg); + return; + } + return msg; + } + if (async) { + return Promise.reject(e); + } + if (callback) { + callback(e); + return; + } + throw e; + }; + } + function parseMarkdown(lexer, parser) { + return function (src, opt, callback) { + if (typeof opt === 'function') { + callback = opt; + opt = null; + } + var origOpt = _extends({}, opt); + opt = _extends({}, marked.defaults, origOpt); + var throwError = onError(opt.silent, opt.async, callback); + + // throw error in case of non string input + if (typeof src === 'undefined' || src === null) { + return throwError(new Error('marked(): input parameter is undefined or null')); + } + if (typeof src !== 'string') { + return throwError(new Error('marked(): input parameter is of type ' + Object.prototype.toString.call(src) + ', string expected')); + } + checkSanitizeDeprecation(opt); + if (opt.hooks) { + opt.hooks.options = opt; + } + if (callback) { + var highlight = opt.highlight; + var tokens; + try { + if (opt.hooks) { + src = opt.hooks.preprocess(src); + } + tokens = lexer(src, opt); + } catch (e) { + return throwError(e); + } + var done = function done(err) { + var out; + if (!err) { + try { + if (opt.walkTokens) { + marked.walkTokens(tokens, opt.walkTokens); + } + out = parser(tokens, opt); + if (opt.hooks) { + out = opt.hooks.postprocess(out); + } + } catch (e) { + err = e; + } + } + opt.highlight = highlight; + return err ? throwError(err) : callback(null, out); + }; + if (!highlight || highlight.length < 3) { + return done(); + } + delete opt.highlight; + if (!tokens.length) return done(); + var pending = 0; + marked.walkTokens(tokens, function (token) { + if (token.type === 'code') { + pending++; + setTimeout(function () { + highlight(token.text, token.lang, function (err, code) { + if (err) { + return done(err); + } + if (code != null && code !== token.text) { + token.text = code; + token.escaped = true; + } + pending--; + if (pending === 0) { + done(); + } + }); + }, 0); + } + }); + if (pending === 0) { + done(); + } + return; + } + if (opt.async) { + return Promise.resolve(opt.hooks ? opt.hooks.preprocess(src) : src).then(function (src) { + return lexer(src, opt); + }).then(function (tokens) { + return opt.walkTokens ? Promise.all(marked.walkTokens(tokens, opt.walkTokens)).then(function () { + return tokens; + }) : tokens; + }).then(function (tokens) { + return parser(tokens, opt); + }).then(function (html) { + return opt.hooks ? opt.hooks.postprocess(html) : html; + })["catch"](throwError); + } + try { + if (opt.hooks) { + src = opt.hooks.preprocess(src); + } + var _tokens = lexer(src, opt); + if (opt.walkTokens) { + marked.walkTokens(_tokens, opt.walkTokens); + } + var html = parser(_tokens, opt); + if (opt.hooks) { + html = opt.hooks.postprocess(html); + } + return html; + } catch (e) { + return throwError(e); + } + }; + } + + /** + * Marked + */ + function marked(src, opt, callback) { + return parseMarkdown(Lexer.lex, Parser.parse)(src, opt, callback); + } + + /** + * Options + */ + + marked.options = marked.setOptions = function (opt) { + marked.defaults = _extends({}, marked.defaults, opt); + changeDefaults(marked.defaults); + return marked; + }; + marked.getDefaults = getDefaults; + marked.defaults = exports.defaults; + + /** + * Use Extension + */ + + marked.use = function () { + var extensions = marked.defaults.extensions || { + renderers: {}, + childTokens: {} + }; + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + args.forEach(function (pack) { + // copy options to new object + var opts = _extends({}, pack); + + // set async to true if it was set to true before + opts.async = marked.defaults.async || opts.async || false; + + // ==-- Parse "addon" extensions --== // + if (pack.extensions) { + pack.extensions.forEach(function (ext) { + if (!ext.name) { + throw new Error('extension name required'); + } + if (ext.renderer) { + // Renderer extensions + var prevRenderer = extensions.renderers[ext.name]; + if (prevRenderer) { + // Replace extension with func to run new extension but fall back if false + extensions.renderers[ext.name] = function () { + for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; + } + var ret = ext.renderer.apply(this, args); + if (ret === false) { + ret = prevRenderer.apply(this, args); + } + return ret; + }; + } else { + extensions.renderers[ext.name] = ext.renderer; + } + } + if (ext.tokenizer) { + // Tokenizer Extensions + if (!ext.level || ext.level !== 'block' && ext.level !== 'inline') { + throw new Error("extension level must be 'block' or 'inline'"); + } + if (extensions[ext.level]) { + extensions[ext.level].unshift(ext.tokenizer); + } else { + extensions[ext.level] = [ext.tokenizer]; + } + if (ext.start) { + // Function to check for start of token + if (ext.level === 'block') { + if (extensions.startBlock) { + extensions.startBlock.push(ext.start); + } else { + extensions.startBlock = [ext.start]; + } + } else if (ext.level === 'inline') { + if (extensions.startInline) { + extensions.startInline.push(ext.start); + } else { + extensions.startInline = [ext.start]; + } + } + } + } + if (ext.childTokens) { + // Child tokens to be visited by walkTokens + extensions.childTokens[ext.name] = ext.childTokens; + } + }); + opts.extensions = extensions; + } + + // ==-- Parse "overwrite" extensions --== // + if (pack.renderer) { + (function () { + var renderer = marked.defaults.renderer || new Renderer(); + var _loop = function _loop(prop) { + var prevRenderer = renderer[prop]; + // Replace renderer with func to run extension, but fall back if false + renderer[prop] = function () { + for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { + args[_key3] = arguments[_key3]; + } + var ret = pack.renderer[prop].apply(renderer, args); + if (ret === false) { + ret = prevRenderer.apply(renderer, args); + } + return ret; + }; + }; + for (var prop in pack.renderer) { + _loop(prop); + } + opts.renderer = renderer; + })(); + } + if (pack.tokenizer) { + (function () { + var tokenizer = marked.defaults.tokenizer || new Tokenizer(); + var _loop2 = function _loop2(prop) { + var prevTokenizer = tokenizer[prop]; + // Replace tokenizer with func to run extension, but fall back if false + tokenizer[prop] = function () { + for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { + args[_key4] = arguments[_key4]; + } + var ret = pack.tokenizer[prop].apply(tokenizer, args); + if (ret === false) { + ret = prevTokenizer.apply(tokenizer, args); + } + return ret; + }; + }; + for (var prop in pack.tokenizer) { + _loop2(prop); + } + opts.tokenizer = tokenizer; + })(); + } + + // ==-- Parse Hooks extensions --== // + if (pack.hooks) { + (function () { + var hooks = marked.defaults.hooks || new Hooks(); + var _loop3 = function _loop3(prop) { + var prevHook = hooks[prop]; + if (Hooks.passThroughHooks.has(prop)) { + hooks[prop] = function (arg) { + if (marked.defaults.async) { + return Promise.resolve(pack.hooks[prop].call(hooks, arg)).then(function (ret) { + return prevHook.call(hooks, ret); + }); + } + var ret = pack.hooks[prop].call(hooks, arg); + return prevHook.call(hooks, ret); + }; + } else { + hooks[prop] = function () { + for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) { + args[_key5] = arguments[_key5]; + } + var ret = pack.hooks[prop].apply(hooks, args); + if (ret === false) { + ret = prevHook.apply(hooks, args); + } + return ret; + }; + } + }; + for (var prop in pack.hooks) { + _loop3(prop); + } + opts.hooks = hooks; + })(); + } + + // ==-- Parse WalkTokens extensions --== // + if (pack.walkTokens) { + var _walkTokens = marked.defaults.walkTokens; + opts.walkTokens = function (token) { + var values = []; + values.push(pack.walkTokens.call(this, token)); + if (_walkTokens) { + values = values.concat(_walkTokens.call(this, token)); + } + return values; + }; + } + marked.setOptions(opts); + }); + }; + + /** + * Run callback for every token + */ + + marked.walkTokens = function (tokens, callback) { + var values = []; + var _loop4 = function _loop4() { + var token = _step.value; + values = values.concat(callback.call(marked, token)); + switch (token.type) { + case 'table': + { + for (var _iterator2 = _createForOfIteratorHelperLoose(token.header), _step2; !(_step2 = _iterator2()).done;) { + var cell = _step2.value; + values = values.concat(marked.walkTokens(cell.tokens, callback)); + } + for (var _iterator3 = _createForOfIteratorHelperLoose(token.rows), _step3; !(_step3 = _iterator3()).done;) { + var row = _step3.value; + for (var _iterator4 = _createForOfIteratorHelperLoose(row), _step4; !(_step4 = _iterator4()).done;) { + var _cell = _step4.value; + values = values.concat(marked.walkTokens(_cell.tokens, callback)); + } + } + break; + } + case 'list': + { + values = values.concat(marked.walkTokens(token.items, callback)); + break; + } + default: + { + if (marked.defaults.extensions && marked.defaults.extensions.childTokens && marked.defaults.extensions.childTokens[token.type]) { + // Walk any extensions + marked.defaults.extensions.childTokens[token.type].forEach(function (childTokens) { + values = values.concat(marked.walkTokens(token[childTokens], callback)); + }); + } else if (token.tokens) { + values = values.concat(marked.walkTokens(token.tokens, callback)); + } + } + } + }; + for (var _iterator = _createForOfIteratorHelperLoose(tokens), _step; !(_step = _iterator()).done;) { + _loop4(); + } + return values; + }; + + /** + * Parse Inline + * @param {string} src + */ + marked.parseInline = parseMarkdown(Lexer.lexInline, Parser.parseInline); + + /** + * Expose + */ + marked.Parser = Parser; + marked.parser = Parser.parse; + marked.Renderer = Renderer; + marked.TextRenderer = TextRenderer; + marked.Lexer = Lexer; + marked.lexer = Lexer.lex; + marked.Tokenizer = Tokenizer; + marked.Slugger = Slugger; + marked.Hooks = Hooks; + marked.parse = marked; + var options = marked.options; + var setOptions = marked.setOptions; + var use = marked.use; + var walkTokens = marked.walkTokens; + var parseInline = marked.parseInline; + var parse = marked; + var parser = Parser.parse; + var lexer = Lexer.lex; + + exports.Hooks = Hooks; + exports.Lexer = Lexer; + exports.Parser = Parser; + exports.Renderer = Renderer; + exports.Slugger = Slugger; + exports.TextRenderer = TextRenderer; + exports.Tokenizer = Tokenizer; + exports.getDefaults = getDefaults; + exports.lexer = lexer; + exports.marked = marked; + exports.options = options; + exports.parse = parse; + exports.parseInline = parseInline; + exports.parser = parser; + exports.setOptions = setOptions; + exports.use = use; + exports.walkTokens = walkTokens; +} (marked$1)); + +const { marked } = marked$1; + +const supHeaders = ['object', 'name', 'description', 'example', 'type', 'required']; + +function parseMdTable$1(md) { + const parsed = marked.lexer(md); + const table = parsed.find(el => el.type === 'table'); + if (table == null) { + return {}; + } + + const { header: rawHeader, rows } = table; + const cells = rows.map(row => row.map(e => e.text)); + const header = rawHeader.map(e => e.text); + if (!header.includes('object') || !header.includes('name')) { + return {}; + } + + const headers = header.map(h => (supHeaders.includes(h) ? h : false)); + const tableObj = cells.reduce((accTable, cell) => { + const cellObj = cell.reduce((accCell, field, index) => { + if (headers[index]) { + // eslint-disable-next-line no-param-reassign + accCell[headers[index]] = field; + } + + return accCell; + }, {}); + + // eslint-disable-next-line no-param-reassign + accTable[cellObj.name] = cellObj; + return accTable; + }, {}); + + return tableObj; +} + +var mdUtils = { parseMdTable: parseMdTable$1 }; + +var mustache = {exports: {}}; + +(function (module, exports) { + (function (global, factory) { + module.exports = factory() ; + }(commonjsGlobal, (function () { + /*! + * mustache.js - Logic-less {{mustache}} templates with JavaScript + * http://github.com/janl/mustache.js + */ + + var objectToString = Object.prototype.toString; + var isArray = Array.isArray || function isArrayPolyfill (object) { + return objectToString.call(object) === '[object Array]'; + }; + + function isFunction (object) { + return typeof object === 'function'; + } + + /** + * More correct typeof string handling array + * which normally returns typeof 'object' + */ + function typeStr (obj) { + return isArray(obj) ? 'array' : typeof obj; + } + + function escapeRegExp (string) { + return string.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&'); + } + + /** + * Null safe way of checking whether or not an object, + * including its prototype, has a given property + */ + function hasProperty (obj, propName) { + return obj != null && typeof obj === 'object' && (propName in obj); + } + + /** + * Safe way of detecting whether or not the given thing is a primitive and + * whether it has the given property + */ + function primitiveHasOwnProperty (primitive, propName) { + return ( + primitive != null + && typeof primitive !== 'object' + && primitive.hasOwnProperty + && primitive.hasOwnProperty(propName) + ); + } + + // Workaround for https://issues.apache.org/jira/browse/COUCHDB-577 + // See https://github.com/janl/mustache.js/issues/189 + var regExpTest = RegExp.prototype.test; + function testRegExp (re, string) { + return regExpTest.call(re, string); + } + + var nonSpaceRe = /\S/; + function isWhitespace (string) { + return !testRegExp(nonSpaceRe, string); + } + + var entityMap = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''', + '/': '/', + '`': '`', + '=': '=' + }; + + function escapeHtml (string) { + return String(string).replace(/[&<>"'`=\/]/g, function fromEntityMap (s) { + return entityMap[s]; + }); + } + + var whiteRe = /\s*/; + var spaceRe = /\s+/; + var equalsRe = /\s*=/; + var curlyRe = /\s*\}/; + var tagRe = /#|\^|\/|>|\{|&|=|!/; + + /** + * Breaks up the given `template` string into a tree of tokens. If the `tags` + * argument is given here it must be an array with two string values: the + * opening and closing tags used in the template (e.g. [ "<%", "%>" ]). Of + * course, the default is to use mustaches (i.e. mustache.tags). + * + * A token is an array with at least 4 elements. The first element is the + * mustache symbol that was used inside the tag, e.g. "#" or "&". If the tag + * did not contain a symbol (i.e. {{myValue}}) this element is "name". For + * all text that appears outside a symbol this element is "text". + * + * The second element of a token is its "value". For mustache tags this is + * whatever else was inside the tag besides the opening symbol. For text tokens + * this is the text itself. + * + * The third and fourth elements of the token are the start and end indices, + * respectively, of the token in the original template. + * + * Tokens that are the root node of a subtree contain two more elements: 1) an + * array of tokens in the subtree and 2) the index in the original template at + * which the closing tag for that section begins. + * + * Tokens for partials also contain two more elements: 1) a string value of + * indendation prior to that tag and 2) the index of that tag on that line - + * eg a value of 2 indicates the partial is the third tag on this line. + */ + function parseTemplate (template, tags) { + if (!template) + return []; + var lineHasNonSpace = false; + var sections = []; // Stack to hold section tokens + var tokens = []; // Buffer to hold the tokens + var spaces = []; // Indices of whitespace tokens on the current line + var hasTag = false; // Is there a {{tag}} on the current line? + var nonSpace = false; // Is there a non-space char on the current line? + var indentation = ''; // Tracks indentation for tags that use it + var tagIndex = 0; // Stores a count of number of tags encountered on a line + + // Strips all whitespace tokens array for the current line + // if there was a {{#tag}} on it and otherwise only space. + function stripSpace () { + if (hasTag && !nonSpace) { + while (spaces.length) + delete tokens[spaces.pop()]; + } else { + spaces = []; + } + + hasTag = false; + nonSpace = false; + } + + var openingTagRe, closingTagRe, closingCurlyRe; + function compileTags (tagsToCompile) { + if (typeof tagsToCompile === 'string') + tagsToCompile = tagsToCompile.split(spaceRe, 2); + + if (!isArray(tagsToCompile) || tagsToCompile.length !== 2) + throw new Error('Invalid tags: ' + tagsToCompile); + + openingTagRe = new RegExp(escapeRegExp(tagsToCompile[0]) + '\\s*'); + closingTagRe = new RegExp('\\s*' + escapeRegExp(tagsToCompile[1])); + closingCurlyRe = new RegExp('\\s*' + escapeRegExp('}' + tagsToCompile[1])); + } + + compileTags(tags || mustache.tags); + + var scanner = new Scanner(template); + + var start, type, value, chr, token, openSection; + while (!scanner.eos()) { + start = scanner.pos; + + // Match any text between tags. + value = scanner.scanUntil(openingTagRe); + + if (value) { + for (var i = 0, valueLength = value.length; i < valueLength; ++i) { + chr = value.charAt(i); + + if (isWhitespace(chr)) { + spaces.push(tokens.length); + indentation += chr; + } else { + nonSpace = true; + lineHasNonSpace = true; + indentation += ' '; + } + + tokens.push([ 'text', chr, start, start + 1 ]); + start += 1; + + // Check for whitespace on the current line. + if (chr === '\n') { + stripSpace(); + indentation = ''; + tagIndex = 0; + lineHasNonSpace = false; + } + } + } + + // Match the opening tag. + if (!scanner.scan(openingTagRe)) + break; + + hasTag = true; + + // Get the tag type. + type = scanner.scan(tagRe) || 'name'; + scanner.scan(whiteRe); + + // Get the tag value. + if (type === '=') { + value = scanner.scanUntil(equalsRe); + scanner.scan(equalsRe); + scanner.scanUntil(closingTagRe); + } else if (type === '{') { + value = scanner.scanUntil(closingCurlyRe); + scanner.scan(curlyRe); + scanner.scanUntil(closingTagRe); + type = '&'; + } else { + value = scanner.scanUntil(closingTagRe); + } + + // Match the closing tag. + if (!scanner.scan(closingTagRe)) + throw new Error('Unclosed tag at ' + scanner.pos); + + if (type == '>') { + token = [ type, value, start, scanner.pos, indentation, tagIndex, lineHasNonSpace ]; + } else { + token = [ type, value, start, scanner.pos ]; + } + tagIndex++; + tokens.push(token); + + if (type === '#' || type === '^') { + sections.push(token); + } else if (type === '/') { + // Check section nesting. + openSection = sections.pop(); + + if (!openSection) + throw new Error('Unopened section "' + value + '" at ' + start); + + if (openSection[1] !== value) + throw new Error('Unclosed section "' + openSection[1] + '" at ' + start); + } else if (type === 'name' || type === '{' || type === '&') { + nonSpace = true; + } else if (type === '=') { + // Set the tags for the next time around. + compileTags(value); + } + } + + stripSpace(); + + // Make sure there are no open sections when we're done. + openSection = sections.pop(); + + if (openSection) + throw new Error('Unclosed section "' + openSection[1] + '" at ' + scanner.pos); + + return nestTokens(squashTokens(tokens)); + } + + /** + * Combines the values of consecutive text tokens in the given `tokens` array + * to a single token. + */ + function squashTokens (tokens) { + var squashedTokens = []; + + var token, lastToken; + for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) { + token = tokens[i]; + + if (token) { + if (token[0] === 'text' && lastToken && lastToken[0] === 'text') { + lastToken[1] += token[1]; + lastToken[3] = token[3]; + } else { + squashedTokens.push(token); + lastToken = token; + } + } + } + + return squashedTokens; + } + + /** + * Forms the given array of `tokens` into a nested tree structure where + * tokens that represent a section have two additional items: 1) an array of + * all tokens that appear in that section and 2) the index in the original + * template that represents the end of that section. + */ + function nestTokens (tokens) { + var nestedTokens = []; + var collector = nestedTokens; + var sections = []; + + var token, section; + for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) { + token = tokens[i]; + + switch (token[0]) { + case '#': + case '^': + collector.push(token); + sections.push(token); + collector = token[4] = []; + break; + case '/': + section = sections.pop(); + section[5] = token[2]; + collector = sections.length > 0 ? sections[sections.length - 1][4] : nestedTokens; + break; + default: + collector.push(token); + } + } + + return nestedTokens; + } + + /** + * A simple string scanner that is used by the template parser to find + * tokens in template strings. + */ + function Scanner (string) { + this.string = string; + this.tail = string; + this.pos = 0; + } + + /** + * Returns `true` if the tail is empty (end of string). + */ + Scanner.prototype.eos = function eos () { + return this.tail === ''; + }; + + /** + * Tries to match the given regular expression at the current position. + * Returns the matched text if it can match, the empty string otherwise. + */ + Scanner.prototype.scan = function scan (re) { + var match = this.tail.match(re); + + if (!match || match.index !== 0) + return ''; + + var string = match[0]; + + this.tail = this.tail.substring(string.length); + this.pos += string.length; + + return string; + }; + + /** + * Skips all text until the given regular expression can be matched. Returns + * the skipped string, which is the entire tail if no match can be made. + */ + Scanner.prototype.scanUntil = function scanUntil (re) { + var index = this.tail.search(re), match; + + switch (index) { + case -1: + match = this.tail; + this.tail = ''; + break; + case 0: + match = ''; + break; + default: + match = this.tail.substring(0, index); + this.tail = this.tail.substring(index); + } + + this.pos += match.length; + + return match; + }; + + /** + * Represents a rendering context by wrapping a view object and + * maintaining a reference to the parent context. + */ + function Context (view, parentContext) { + this.view = view; + this.cache = { '.': this.view }; + this.parent = parentContext; + } + + /** + * Creates a new context using the given view with this context + * as the parent. + */ + Context.prototype.push = function push (view) { + return new Context(view, this); + }; + + /** + * Returns the value of the given name in this context, traversing + * up the context hierarchy if the value is absent in this context's view. + */ + Context.prototype.lookup = function lookup (name) { + var cache = this.cache; + + var value; + if (cache.hasOwnProperty(name)) { + value = cache[name]; + } else { + var context = this, intermediateValue, names, index, lookupHit = false; + + while (context) { + if (name.indexOf('.') > 0) { + intermediateValue = context.view; + names = name.split('.'); + index = 0; + + /** + * Using the dot notion path in `name`, we descend through the + * nested objects. + * + * To be certain that the lookup has been successful, we have to + * check if the last object in the path actually has the property + * we are looking for. We store the result in `lookupHit`. + * + * This is specially necessary for when the value has been set to + * `undefined` and we want to avoid looking up parent contexts. + * + * In the case where dot notation is used, we consider the lookup + * to be successful even if the last "object" in the path is + * not actually an object but a primitive (e.g., a string, or an + * integer), because it is sometimes useful to access a property + * of an autoboxed primitive, such as the length of a string. + **/ + while (intermediateValue != null && index < names.length) { + if (index === names.length - 1) + lookupHit = ( + hasProperty(intermediateValue, names[index]) + || primitiveHasOwnProperty(intermediateValue, names[index]) + ); + + intermediateValue = intermediateValue[names[index++]]; + } + } else { + intermediateValue = context.view[name]; + + /** + * Only checking against `hasProperty`, which always returns `false` if + * `context.view` is not an object. Deliberately omitting the check + * against `primitiveHasOwnProperty` if dot notation is not used. + * + * Consider this example: + * ``` + * Mustache.render("The length of a football field is {{#length}}{{length}}{{/length}}.", {length: "100 yards"}) + * ``` + * + * If we were to check also against `primitiveHasOwnProperty`, as we do + * in the dot notation case, then render call would return: + * + * "The length of a football field is 9." + * + * rather than the expected: + * + * "The length of a football field is 100 yards." + **/ + lookupHit = hasProperty(context.view, name); + } + + if (lookupHit) { + value = intermediateValue; + break; + } + + context = context.parent; + } + + cache[name] = value; + } + + if (isFunction(value)) + value = value.call(this.view); + + return value; + }; + + /** + * A Writer knows how to take a stream of tokens and render them to a + * string, given a context. It also maintains a cache of templates to + * avoid the need to parse the same template twice. + */ + function Writer () { + this.templateCache = { + _cache: {}, + set: function set (key, value) { + this._cache[key] = value; + }, + get: function get (key) { + return this._cache[key]; + }, + clear: function clear () { + this._cache = {}; + } + }; + } + + /** + * Clears all cached templates in this writer. + */ + Writer.prototype.clearCache = function clearCache () { + if (typeof this.templateCache !== 'undefined') { + this.templateCache.clear(); + } + }; + + /** + * Parses and caches the given `template` according to the given `tags` or + * `mustache.tags` if `tags` is omitted, and returns the array of tokens + * that is generated from the parse. + */ + Writer.prototype.parse = function parse (template, tags) { + var cache = this.templateCache; + var cacheKey = template + ':' + (tags || mustache.tags).join(':'); + var isCacheEnabled = typeof cache !== 'undefined'; + var tokens = isCacheEnabled ? cache.get(cacheKey) : undefined; + + if (tokens == undefined) { + tokens = parseTemplate(template, tags); + isCacheEnabled && cache.set(cacheKey, tokens); + } + return tokens; + }; + + /** + * High-level method that is used to render the given `template` with + * the given `view`. + * + * The optional `partials` argument may be an object that contains the + * names and templates of partials that are used in the template. It may + * also be a function that is used to load partial templates on the fly + * that takes a single argument: the name of the partial. + * + * If the optional `config` argument is given here, then it should be an + * object with a `tags` attribute or an `escape` attribute or both. + * If an array is passed, then it will be interpreted the same way as + * a `tags` attribute on a `config` object. + * + * The `tags` attribute of a `config` object must be an array with two + * string values: the opening and closing tags used in the template (e.g. + * [ "<%", "%>" ]). The default is to mustache.tags. + * + * The `escape` attribute of a `config` object must be a function which + * accepts a string as input and outputs a safely escaped string. + * If an `escape` function is not provided, then an HTML-safe string + * escaping function is used as the default. + */ + Writer.prototype.render = function render (template, view, partials, config) { + var tags = this.getConfigTags(config); + var tokens = this.parse(template, tags); + var context = (view instanceof Context) ? view : new Context(view, undefined); + return this.renderTokens(tokens, context, partials, template, config); + }; + + /** + * Low-level method that renders the given array of `tokens` using + * the given `context` and `partials`. + * + * Note: The `originalTemplate` is only ever used to extract the portion + * of the original template that was contained in a higher-order section. + * If the template doesn't use higher-order sections, this argument may + * be omitted. + */ + Writer.prototype.renderTokens = function renderTokens (tokens, context, partials, originalTemplate, config) { + var buffer = ''; + + var token, symbol, value; + for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) { + value = undefined; + token = tokens[i]; + symbol = token[0]; + + if (symbol === '#') value = this.renderSection(token, context, partials, originalTemplate, config); + else if (symbol === '^') value = this.renderInverted(token, context, partials, originalTemplate, config); + else if (symbol === '>') value = this.renderPartial(token, context, partials, config); + else if (symbol === '&') value = this.unescapedValue(token, context); + else if (symbol === 'name') value = this.escapedValue(token, context, config); + else if (symbol === 'text') value = this.rawValue(token); + + if (value !== undefined) + buffer += value; + } + + return buffer; + }; + + Writer.prototype.renderSection = function renderSection (token, context, partials, originalTemplate, config) { + var self = this; + var buffer = ''; + var value = context.lookup(token[1]); + + // This function is used to render an arbitrary template + // in the current context by higher-order sections. + function subRender (template) { + return self.render(template, context, partials, config); + } + + if (!value) return; + + if (isArray(value)) { + for (var j = 0, valueLength = value.length; j < valueLength; ++j) { + buffer += this.renderTokens(token[4], context.push(value[j]), partials, originalTemplate, config); + } + } else if (typeof value === 'object' || typeof value === 'string' || typeof value === 'number') { + buffer += this.renderTokens(token[4], context.push(value), partials, originalTemplate, config); + } else if (isFunction(value)) { + if (typeof originalTemplate !== 'string') + throw new Error('Cannot use higher-order sections without the original template'); + + // Extract the portion of the original template that the section contains. + value = value.call(context.view, originalTemplate.slice(token[3], token[5]), subRender); + + if (value != null) + buffer += value; + } else { + buffer += this.renderTokens(token[4], context, partials, originalTemplate, config); + } + return buffer; + }; + + Writer.prototype.renderInverted = function renderInverted (token, context, partials, originalTemplate, config) { + var value = context.lookup(token[1]); + + // Use JavaScript's definition of falsy. Include empty arrays. + // See https://github.com/janl/mustache.js/issues/186 + if (!value || (isArray(value) && value.length === 0)) + return this.renderTokens(token[4], context, partials, originalTemplate, config); + }; + + Writer.prototype.indentPartial = function indentPartial (partial, indentation, lineHasNonSpace) { + var filteredIndentation = indentation.replace(/[^ \t]/g, ''); + var partialByNl = partial.split('\n'); + for (var i = 0; i < partialByNl.length; i++) { + if (partialByNl[i].length && (i > 0 || !lineHasNonSpace)) { + partialByNl[i] = filteredIndentation + partialByNl[i]; + } + } + return partialByNl.join('\n'); + }; + + Writer.prototype.renderPartial = function renderPartial (token, context, partials, config) { + if (!partials) return; + var tags = this.getConfigTags(config); + + var value = isFunction(partials) ? partials(token[1]) : partials[token[1]]; + if (value != null) { + var lineHasNonSpace = token[6]; + var tagIndex = token[5]; + var indentation = token[4]; + var indentedValue = value; + if (tagIndex == 0 && indentation) { + indentedValue = this.indentPartial(value, indentation, lineHasNonSpace); + } + var tokens = this.parse(indentedValue, tags); + return this.renderTokens(tokens, context, partials, indentedValue, config); + } + }; + + Writer.prototype.unescapedValue = function unescapedValue (token, context) { + var value = context.lookup(token[1]); + if (value != null) + return value; + }; + + Writer.prototype.escapedValue = function escapedValue (token, context, config) { + var escape = this.getConfigEscape(config) || mustache.escape; + var value = context.lookup(token[1]); + if (value != null) + return (typeof value === 'number' && escape === mustache.escape) ? String(value) : escape(value); + }; + + Writer.prototype.rawValue = function rawValue (token) { + return token[1]; + }; + + Writer.prototype.getConfigTags = function getConfigTags (config) { + if (isArray(config)) { + return config; + } + else if (config && typeof config === 'object') { + return config.tags; + } + else { + return undefined; + } + }; + + Writer.prototype.getConfigEscape = function getConfigEscape (config) { + if (config && typeof config === 'object' && !isArray(config)) { + return config.escape; + } + else { + return undefined; + } + }; + + var mustache = { + name: 'mustache.js', + version: '4.2.0', + tags: [ '{{', '}}' ], + clearCache: undefined, + escape: undefined, + parse: undefined, + render: undefined, + Scanner: undefined, + Context: undefined, + Writer: undefined, + /** + * Allows a user to override the default caching strategy, by providing an + * object with set, get and clear methods. This can also be used to disable + * the cache by setting it to the literal `undefined`. + */ + set templateCache (cache) { + defaultWriter.templateCache = cache; + }, + /** + * Gets the default or overridden caching object from the default writer. + */ + get templateCache () { + return defaultWriter.templateCache; + } + }; + + // All high-level mustache.* functions use this writer. + var defaultWriter = new Writer(); + + /** + * Clears all cached templates in the default writer. + */ + mustache.clearCache = function clearCache () { + return defaultWriter.clearCache(); + }; + + /** + * Parses and caches the given template in the default writer and returns the + * array of tokens it contains. Doing this ahead of time avoids the need to + * parse templates on the fly as they are rendered. + */ + mustache.parse = function parse (template, tags) { + return defaultWriter.parse(template, tags); + }; + + /** + * Renders the `template` with the given `view`, `partials`, and `config` + * using the default writer. + */ + mustache.render = function render (template, view, partials, config) { + if (typeof template !== 'string') { + throw new TypeError('Invalid template! Template should be a "string" ' + + 'but "' + typeStr(template) + '" was given as the first ' + + 'argument for mustache#render(template, view, partials)'); + } + + return defaultWriter.render(template, view, partials, config); + }; + + // Export the escaping function so that the user may override it. + // See https://github.com/janl/mustache.js/issues/244 + mustache.escape = escapeHtml; + + // Export these mainly for testing, but also for advanced usage. + mustache.Scanner = Scanner; + mustache.Context = Context; + mustache.Writer = Writer; + + return mustache; + + }))); +} (mustache)); + +var mustacheExports = mustache.exports; + +const Mustache = mustacheExports; + +/** + * Rewrite escapedValue() function to not delete undefined variables + */ +Mustache.Writer.prototype.escapedValue = function escapedValue(token, context) { + const value = context.lookup(token[1]) || `{{${token[1]}}}`; + return String(value); +}; + +function replacePostmanVariables$1(collectionString, additionalVars = {}) { + const postmanJson = JSON.parse(collectionString); + const { variable = [] } = postmanJson; + const formatVars = variable.reduce((obj, { key, value }) => { + // eslint-disable-next-line no-param-reassign + obj[key] = value; + return obj; + }, {}); + + // Merge collection vars with additional vars + const context = { ...formatVars, ...additionalVars }; + return Mustache.render(collectionString, context); +} + +var varReplacer = replacePostmanVariables$1; + +/* eslint-disable no-param-reassign */ + +/* eslint-disable unicorn/no-unsafe-regex */ +/* eslint-disable default-param-last */ +/* eslint-disable default-case */ +/* eslint-disable no-underscore-dangle */ +/* eslint-disable no-use-before-define */ +const { + promises: { writeFile, readFile }, +} = require$$0$8; + +const { getStatusCodeMessage } = src$4; +const { dump } = jsYaml; +const jsonc = require$$3; +const camelCase = lodash_camelcase; + +const { parseMdTable } = mdUtils; +const replacePostmanVariables = varReplacer; + +async function postmanToOpenAPI( + input, + output, + { + info = {}, + defaultTag = 'default', + pathDepth = 0, + auth: optsAuth, + servers, + externalDocs = {}, + folders = {}, + responseHeaders = true, + replaceVars = false, + additionalVars = {}, + outputFormat = 'yaml', + disabledParams = { + includeQuery: false, + includeHeader: false, + }, + operationId = 'off', + } = {} +) { + // TODO validate? + let collectionFile = await resolveInput(input); + if (replaceVars) { + collectionFile = replacePostmanVariables(collectionFile, additionalVars); + } + const _postmanJson = JSON.parse(collectionFile); + const postmanJson = _postmanJson.collection || _postmanJson; + const { item: items, variable = [] } = postmanJson; + const paths = {}; + const domains = new Set(); + const tags = {}; + const securitySchemes = {}; + + // eslint-disable-next-line prefer-const + for (let [i, element] of items.entries()) { + while (element != null && element.item != null) { + // is a folder + const { item, description: tagDesc } = element; + const tag = calculateFolderTag(element, folders); + const tagged = item.map(e => ({ ...e, tag })); + tags[tag] = tagDesc; + items.splice(i, 1, ...tagged); + // Empty folders will have tagged empty + element = tagged.length > 0 ? tagged.shift() : items[i]; + } + // If there are an empty folder at the end of the collection elements could be `undefined` + if (element != null) { + const { + request: { url, method, body, description: rawDesc, header = [], auth }, + name, + tag = defaultTag, + event: events, + response, + } = element; + const { path, query, protocol, host, port, valid, pathVars } = scrapeURL(url); + if (valid) { + // Remove from name the possible operation id between brackets + // eslint-disable-next-line no-useless-escape + const summary = name.replace(/ \[([^\[\]]*)\]/gi, ''); + domains.add(calculateDomains(protocol, host, port)); + const joinedPath = calculatePath(path, pathDepth); + if (!paths[joinedPath]) paths[joinedPath] = {}; + const { description, paramsMeta } = descriptionParse(rawDesc); + paths[joinedPath][method.toLowerCase()] = { + tags: [tag], + summary, + ...calculateOperationId(operationId, name, summary), + ...(description ? { description } : {}), + ...parseBody(body, method), + ...parseOperationAuth(auth, securitySchemes, optsAuth), + ...parseParameters(query, header, joinedPath, paramsMeta, pathVars, disabledParams), + ...parseResponse(response, events, responseHeaders), + }; + } + } + } + + const openApi = { + openapi: '3.0.0', + info: compileInfo(postmanJson, info), + ...parseExternalDocs(variable, externalDocs), + ...parseServers(domains, servers), + ...parseAuth(postmanJson, optsAuth, securitySchemes), + ...parseTags(tags), + paths, + }; + const openApiDoc = outputFormat === 'json' ? JSON.stringify(openApi, null, 4) : dump(openApi, { skipInvalid: true }); + if (output != null) { + await writeFile(output, openApiDoc, 'utf8'); + } + return openApiDoc; +} + +/* Calculate the tags for folders items based on the options */ +function calculateFolderTag({ tag, name }, { separator = ' > ', concat = true }) { + return tag && concat ? `${tag}${separator}${name}` : name; +} + +function compileInfo(postmanJson, optsInfo) { + const { + info: { name, description: desc }, + variable = [], + } = postmanJson; + const ver = getVarValue(variable, 'version', '1.0.0'); + const { title = name, description = desc, version = ver, termsOfService, license, contact, xLogo } = optsInfo; + return { + title, + description, + version, + ...parseXLogo(variable, xLogo), + ...(termsOfService ? { termsOfService } : {}), + ...parseContact(variable, contact), + ...parseLicense(variable, license), + }; +} + +function parseXLogo(variables, xLogo = {}) { + const urlVar = getVarValue(variables, 'x-logo.urlVar'); + const backgroundColorVar = getVarValue(variables, 'x-logo.backgroundColorVar'); + const altTextVar = getVarValue(variables, 'x-logo.altTextVar'); + const hrefVar = getVarValue(variables, 'x-logo.hrefVar'); + const { url = urlVar, backgroundColor = backgroundColorVar, altText = altTextVar, href = hrefVar } = xLogo; + return url != null ? { 'x-logo': { url, backgroundColor, altText, href } } : {}; +} + +function parseLicense(variables, optsLicense = {}) { + const nameVar = getVarValue(variables, 'license.name'); + const urlVar = getVarValue(variables, 'license.url'); + const { name = nameVar, url = urlVar } = optsLicense; + return name != null ? { license: { name, ...(url ? { url } : {}) } } : {}; +} + +function parseContact(variables, optsContact = {}) { + const nameVar = getVarValue(variables, 'contact.name'); + const urlVar = getVarValue(variables, 'contact.url'); + const emailVar = getVarValue(variables, 'contact.email'); + const { name = nameVar, url = urlVar, email = emailVar } = optsContact; + return [name, url, email].some(e => e != null) + ? { + contact: { + ...(name ? { name } : {}), + ...(url ? { url } : {}), + ...(email ? { email } : {}), + }, + } + : {}; +} + +function parseExternalDocs(variables, optsExternalDocs) { + const descriptionVar = getVarValue(variables, 'externalDocs.description'); + const urlVar = getVarValue(variables, 'externalDocs.url'); + const { description = descriptionVar, url = urlVar } = optsExternalDocs; + return url != null ? { externalDocs: { url, ...(description ? { description } : {}) } } : {}; +} + +function parseBody(body = {}, method) { + // Swagger validation return an error if GET has body + if (['GET', 'DELETE'].includes(method)) { + return {}; + } + + const { mode, raw, options = { raw } } = body; + let content = {}; + + switch (mode) { + case 'raw': { + const { + raw: { language }, + } = options; + + let example = ''; + if (language === 'json') { + if (raw) { + const errors = []; + example = jsonc.parse(raw, errors); + if (errors.length > 0) { + example = raw; + } + } + content = { + 'application/json': { + schema: { + type: 'object', + example, + }, + }, + }; + } else if (language === 'text') { + content = { + 'text/plain': { + schema: { + type: 'string', + example: raw, + }, + }, + }; + } else { + content = { + '*/*': { + schema: { + type: 'string', + // To protect from object types we always stringify this + example: JSON.stringify(raw), + }, + }, + }; + } + break; + } + case 'file': + content = { + 'text/plain': {}, + }; + break; + case 'formdata': { + content = { + 'multipart/form-data': parseFormData(body.formdata), + }; + break; + } + case 'urlencoded': + content = { + 'application/x-www-form-urlencoded': parseFormData(body.urlencoded), + }; + break; + } + + return { requestBody: { content } }; +} + +/** Parse the body for create a form data structure */ +function parseFormData(data) { + const objectSchema = { + schema: { + type: 'object', + }, + }; + return data.reduce((obj, { key, type, description, value }) => { + const { schema } = obj; + if (isRequired(description)) { + (schema.required = schema.required || []).push(key); + } + (schema.properties = schema.properties || {})[key] = { + type: inferType(value), + ...(description ? { description: description.replace(/ ?\[required\] ?/gi, '') } : {}), + ...(value ? { example: value } : {}), + ...(type === 'file' ? { format: 'binary' } : {}), + }; + return obj; + }, objectSchema); +} + +/** + * Default logic to insert parameters, if parameter exist will not be inserted again. + * In Postman this means that only the first parameter is used, the repeated ones are discarded. + * This is a separated method to allow make it configurable in the future + * @param {Map} parameterMap + * @param {Object} param + * @returns the modified parameterMap + */ +const defaultParamInserter = (parameterMap, param) => { + if (!parameterMap.has(param.name)) { + parameterMap.set(param.name, param); + } + return parameterMap; +}; + +/* Parse the Postman query and header and transform into OpenApi parameters */ +function parseParameters( + query, + header, + paths, + paramsMeta = {}, + pathVars, + { includeQuery = false, includeHeader = false }, + paramInserter = defaultParamInserter +) { + // parse Headers + const parameters = [...header.reduce(mapParameters('header', includeHeader, paramInserter), new Map()).values()]; + // parse Query + parameters.push(...query.reduce(mapParameters('query', includeQuery, paramInserter), new Map()).values()); + // Path params + parameters.push(...extractPathParameters(paths, paramsMeta, pathVars)); + return parameters.length ? { parameters } : {}; +} + +/* Accumulator function for different types of parameters */ +function mapParameters(type, includeDisabled, paramInserter) { + return (parameterMap, { key, description, value, disabled }) => { + if (!includeDisabled && disabled === true) return parameterMap; + const required = /\[required\]/gi.test(description); + paramInserter(parameterMap, { + name: key, + in: type, + schema: { type: inferType(value) }, + ...(required ? { required } : {}), + ...(description ? { description: description.replace(/ ?\[required\] ?/gi, '') } : {}), + ...(value ? { example: value } : {}), + }); + return parameterMap; + }; +} + +function extractPathParameters(path, paramsMeta, pathVars) { + const matched = path.match(/{\s*[\w-]+\s*}/g) || []; + return matched.map(match => { + const name = match.slice(1, -1); + const { type: varType = 'string', description: desc, value } = pathVars[name] || {}; + const { type = varType, description = desc, example = value } = paramsMeta[name] || {}; + return { + name, + in: 'path', + schema: { type }, + required: true, + ...(description ? { description } : {}), + ...(example ? { example } : {}), + }; + }); +} + +function getVarValue(variables, name, def = undefined) { + const variable = variables.find(({ key }) => key === name); + return variable ? variable.value : def; +} + +/* calculate the type of a variable based on OpenAPI types */ +function inferType(value) { + if (/^\d+$/.test(value)) return 'integer'; + if (/^[+-]?([0-9]*[.])?[0-9]+$/.test(value)) return 'number'; + if (/^(true|false)$/.test(value)) return 'boolean'; + return 'string'; +} + +/* Calculate the global auth based on options and postman definition */ +function parseAuth({ auth }, optAuth, securitySchemes) { + if (optAuth != null) { + return parseOptsAuth(optAuth); + } + return parsePostmanAuth(auth, securitySchemes); +} + +/* Parse a postman auth definition */ +function parsePostmanAuth(postmanAuth = {}, securitySchemes) { + const { type } = postmanAuth; + if (type != null) { + securitySchemes[`${type}Auth`] = { + type: 'http', + scheme: type, + }; + return { + components: { securitySchemes }, + security: [ + { + [`${type}Auth`]: [], + }, + ], + }; + } + return Object.keys(securitySchemes).length === 0 ? {} : { components: { securitySchemes } }; +} + +/* Parse Auth at operation/request level */ +function parseOperationAuth(auth, securitySchemes, optsAuth) { + if (auth == null || optsAuth != null) { + // In case of config auth operation auth is disabled + return {}; + } + + const { type } = auth; + securitySchemes[`${type}Auth`] = { + type: 'http', + scheme: type, + }; + + return { + security: [{ [`${type}Auth`]: [] }], + }; +} + +/* Parse a options global auth */ +function parseOptsAuth(optAuth) { + const securitySchemes = {}; + const security = []; + for (const [secName, secDefinition] of Object.entries(optAuth)) { + const { type, scheme, ...rest } = secDefinition; + if (type === 'http' && ['bearer', 'basic'].includes(scheme)) { + securitySchemes[secName] = { + type: 'http', + scheme, + ...rest, + }; + security.push({ [secName]: [] }); + } + } + return Object.keys(securitySchemes).length === 0 + ? {} + : { + components: { securitySchemes }, + security, + }; +} + +/* From the path array compose the real path for OpenApi specs */ +function calculatePath(paths, pathDepth) { + paths = paths.slice(pathDepth); // path depth + + // replace repeated '{' and '}' chars + // replace `:` chars at first + return `/${paths + .map(path => { + path = path.replace(/([{}])\1+/g, '$1'); + path = path.replace(/^:(.*)/g, '{$1}'); + return path; + }) + .join('/')}`; +} + +function calculateDomains(protocol, hosts, port) { + return `${protocol}://${hosts.join('.')}${port ? `:${port}` : ''}`; +} + +/** + * To support postman collection v2 and variable replace we should parse the `url` or `url.raw` data + * without trust in the object as in v2 could not exist and if replaceVars = true then values cannot + * be correctly parsed + * @param {Object | String} url + * @returns a url structure as in postman v2.1 collections + */ +function scrapeURL(url) { + // Avoid parse empty url request + if (url === undefined || url === '' || url.raw === '') { + return { valid: false }; + } + + const rawUrl = typeof url === 'string' || url instanceof String ? url : url.raw; + + // Fix for issue #136 if replace vars are not used then new URL throw an error + // when using variables before the schema + const fixedUrl = rawUrl.startsWith('{{') ? `http://${rawUrl}` : rawUrl; + const objUrl = new URL(fixedUrl); + return { + raw: rawUrl, + path: decodeURIComponent(objUrl.pathname).slice(1).split('/'), + query: compoundQueryParams(objUrl.searchParams, url.query), + protocol: objUrl.protocol.slice(0, -1), + host: decodeURIComponent(objUrl.hostname).split('.'), + port: objUrl.port, + valid: true, + pathVars: + url.variable == null + ? {} + : url.variable.reduce((obj, { key, value, description }) => { + obj[key] = { value, description, type: inferType(value) }; + return obj; + }, {}), + }; +} + +/** + * Calculate query parameters in postman collection + * @param {*} searchParams The searchParam instance from an URL object + * @param {*} queryCollection The postman collection query section + * @returns A query params array as created by postman collections Array(Obj) + * + * NOTE: This method was created because we think that some versions of postman don´t add the `query` + * parameter in the url, but after some reasearch the reason why the `query` parameter can not be + * present is just because no query parameters are used so we just format the postman `query` array here. + */ +function compoundQueryParams(searchParams, queryCollection = []) { + return queryCollection; +} + +/* Parse domains from operations or options */ +function parseServers(domains, serversOpts) { + let servers; + if (serversOpts != null) { + // This map is just to filter not supported fields while no validations are implemented + servers = serversOpts.map(({ url, description }) => ({ url, description })); + } else { + servers = Array.from(domains).map(domain => ({ url: domain })); + } + return servers.length > 0 ? { servers } : {}; +} + +/* Transform a object of tags in an array of tags */ +function parseTags(tagsObj) { + const tags = Object.entries(tagsObj).map(([name, description]) => ({ name, description })); + return tags.length > 0 ? { tags } : {}; +} + +function descriptionParse(description) { + if (description == null) return { description }; + const splitDesc = description.split(/# postman-to-openapi/gi); + if (splitDesc.length === 1) return { description }; + return { + description: splitDesc[0].trim(), + paramsMeta: parseMdTable(splitDesc[1]), + }; +} + +function parseResponse(responses, events, responseHeaders) { + if (responses != null && Array.isArray(responses) && responses.length > 0) { + return parseResponseFromExamples(responses, responseHeaders); + } + + return { responses: parseResponseFromEvents(events) }; +} + +function parseResponseFromEvents(events = []) { + let status = 200; + const test = events.filter(event => event.listen === 'test'); + if (test.length > 0) { + const script = test[0].script.exec.join(); + const result = script.match(/\.response\.code\)\.to\.eql\((\d{3})\)|\.to\.have\.status\((\d{3})\)/); + status = result && result[1] != null ? result[1] : result && result[2] != null ? result[2] : status; + } + + return { + [status]: { + description: 'Successful response', + content: { + 'application/json': {}, + }, + }, + }; +} + +function parseResponseFromExamples(responses, responseHeaders) { + // Group responses by status code + const statusCodeMap = responses.reduce( + (statusMap, { name, code, status: description, header, body, _postman_previewlanguage: language }) => { + if (code === undefined) { + code = 'default'; + } + + // The OpenAPI spec requires that `description` be present on responses with content so + // we'll make it match the message that cooresponds to the HTTP status code. + if (!description) { + try { + description = getStatusCodeMessage({ code }); + } catch (err) { + description = code; + } + } + + if (code in statusMap) { + if (!(language in statusMap[code].bodies)) { + statusMap[code].bodies[language] = []; + } + statusMap[code].bodies[language].push({ name, body }); + } else { + statusMap[code] = { + description, + header, + bodies: { [language]: [{ name, body }] }, + }; + } + return statusMap; + }, + {} + ); + + // Parse for OpenAPI + const parsedResponses = Object.entries(statusCodeMap).reduce((parsed, [status, { description, header, bodies }]) => { + parsed[status] = { + description, + ...parseResponseHeaders(header, responseHeaders), + ...parseContent(bodies), + }; + return parsed; + }, {}); + + return { responses: parsedResponses }; +} + +function parseContent(bodiesByLanguage) { + const content = Object.entries(bodiesByLanguage).reduce((contentObj, [language, bodies]) => { + if (language === 'json') { + contentObj['application/json'] = { + schema: { type: 'object' }, + ...parseExamples(bodies, 'json'), + }; + } else { + contentObj['text/plain'] = { + schema: { type: 'string' }, + ...parseExamples(bodies, 'text'), + }; + } + + return contentObj; + }, {}); + + return { content }; +} + +function parseExamples(bodies, language) { + if (Array.isArray(bodies) && bodies.length > 1) { + return { + examples: bodies.reduce((ex, { name: summary, body }, i) => { + ex[`example-${i}`] = { + summary, + value: safeSampleParse(body, summary, language), + }; + return ex; + }, {}), + }; + } + + const { body, name } = bodies[0]; + return { + example: safeSampleParse(body, name, language), + }; +} + +function safeSampleParse(body, name, language) { + if (language === 'json') { + const errors = []; + const parsedBody = jsonc.parse(body == null || body.trim().length === 0 ? '{}' : body, errors); + if (errors.length > 0) { + throw new Error(`Error parsing response example "${name}"`); + } + return parsedBody; + } + return body; +} + +function parseResponseHeaders(headerArray, responseHeaders) { + if (!responseHeaders) { + return {}; + } + + headerArray = headerArray || []; + const headers = headerArray.reduce((acc, { key, value }) => { + acc[key] = { + schema: { + type: inferType(value), + example: value, + }, + }; + return acc; + }, {}); + + return Object.keys(headers).length > 0 ? { headers } : {}; +} + +/** + * Just check if is a string collection or a path. + * moved to method for allow easy changes in the future like check if it is a collection, validations... + */ +async function resolveInput(input) { + if (input.trim().startsWith('{')) { + return input; + } + + return readFile(input, 'utf8'); +} + +/** + * return if the provided text contains the '[required]' mark + * @param {*} text The text where we should look for the required mark + * @returns boolean + */ +function isRequired(text) { + return /\[required\]/gi.test(text); +} + +/** + * calculate the operationId based on the user selected `mode` + * @param {*} mode - mode to calculate the operation id between `off`, `auto` or `brackets` + * @param {*} name - field name of the request/operation in the postman collection without modify. + * @param {*} summary - calculated summary of the operation that will be used in the OpenAPI spec. + * @returns an operation id + */ +function calculateOperationId(mode, name, summary) { + let operationId; + switch (mode) { + case 'off': + break; + case 'auto': + operationId = camelCase(summary); + break; + case 'brackets': { + // eslint-disable-next-line no-useless-escape + const matches = name.match(/\[([^\[\]]*)\]/); + operationId = matches ? matches[1] : undefined; + break; + } + } + return operationId ? { operationId } : {}; +} + +var src$3 = postmanToOpenAPI; + +var postmanToOpenAPI$1 = /*@__PURE__*/getDefaultExportFromCjs(src$3); + +let DebounceTimers$1 = class DebounceTimers{ + constructor(cb , defaultDelay){ + this.cb = cb; + this.delay = defaultDelay; + this.timers = { + + }; + this.pausers = {}; + } + setDelay(delay){ + if ( delay >= 0) + this.delay = delay; + } + pause(key){ + this.pausers[key] = this.pausers[key]|| 0; + this.pausers[key]++; + } + unpause(key){ + var count = this.pausers[key] || 0; + if (count>0) + count--; + this.pausers[key] = count; + } + unpauseAndTime(key){ + this.unpause(key); + this.time(key); + } + time(key){ + var self = this; + var timers = this.timers; + var timer = this.timers[key]; + if (this.pausers[key] > 0) + return; + if (timer) + clearTimeout(timer); + + timers[key] = setTimeout(function onTimer(){ + self.cb(key); + delete timers[key]; + } , self.delay); + } +}; +let ERR_INVALID_ARG_TYPE$1 = class ERR_INVALID_ARG_TYPE extends TypeError{ + constructor(name, expected, actual){ + const type = name.includes('.') ? 'property' : 'argument'; + `The "${name}" ${type} ${determiner} ${expected}`; + + } + }; + function assertIsObject$2(value, name, types = 'Object') { + if (value !== undefined && + (value === null || + typeof value !== 'object' || + Array.isArray(value))) { + const err = new ERR_INVALID_ARG_TYPE$1(name, types, value); + Error.captureStackTrace(err, assertIsObject$2); + throw err; + } + } + + + var utils$2 = { + ERR_INVALID_ARG_TYPE: ERR_INVALID_ARG_TYPE$1, + assertIsObject: assertIsObject$2, + DebounceTimers: DebounceTimers$1 + }; + +const {assertIsObject: assertIsObject$1 } = utils$2; + +function initializeOptions(options) { + assertIsObject$1(options, 'options'); + options = Object.assign({}, options); + options.allowHalfOpen = true; + options.rejectUnauthorized = false; + assertIsObject$1(options.settings, 'options.settings'); + options.settings = Object.assign({}, options.settings); + + // Used only with allowHTTP1 + options.Http1IncomingMessage = options.Http1IncomingMessage || + this.http.IncomingMessage; + options.Http1ServerResponse = options.Http1ServerResponse || + this.http.ServerResponse; + + options.Http2ServerRequest = options.Http2ServerRequest || + ((this.http2 || {}).Http2ServerRequest); + options.Http2ServerResponse = options.Http2ServerResponse || + ((this.http2 || {}).Http2ServerResponse); + return options; + } + + function initializeTLSOptions$1(options, servername) { + options = initializeOptions.call(this,options); + var ALPNProtocols = options.ALPNProtocols = []; + if (this.http2Support) + ALPNProtocols.push('h2'); + if (options.allowHTTP1 == true || !this.http2Support) + ALPNProtocols.push('http/1.1'); + if (servername !== undefined && options.servername === undefined) + options.servername = servername; + return options; + } + + var requestOptions = { + initializeTLSOptions: initializeTLSOptions$1 + }; + +const { URL: URL$3 } = require$$0$e; +const {EventEmitter} = require$$2$3; +const _extend = require$$0$9._extend; +const {DebounceTimers , assertIsObject , ERR_INVALID_ARG_TYPE} = utils$2; +const {initializeTLSOptions } = requestOptions; +const http$3 = require$$0$a; +const https$2 = require$$1$4; +const {Stream} = Stream$3; +function addFunctions(container , obj){ + const proto = obj.prototype; + Object.keys(proto).forEach((name)=>{ + if (container.indexOf(name)!=-1) + return; + if (name.indexOf('_')!=0 && typeof proto[name] == 'function'){ + container.push(name); + } + }); +} +const STUBBED_METHODS_NAME = [ +]; +//We need to proxy all v1 function +addFunctions(STUBBED_METHODS_NAME, http$3.ClientRequest); +addFunctions(STUBBED_METHODS_NAME, http$3.OutgoingMessage); +addFunctions(STUBBED_METHODS_NAME, EventEmitter); +addFunctions(STUBBED_METHODS_NAME, Stream); + +const PROPERTIES_TO_PROXY = [ + 'httpVersionMajor', + 'httpVersionMinor', + 'httpVersion', +]; +const HEADERS_TO_REMOVE = ['host' , 'connection']; + +const $stubs = Symbol('stubs'); + +function ClientRequest$3(){ + this.http2Mimic = true; + this[$stubs] = []; + for (var i=0;i<STUBBED_METHODS_NAME.length;i++){ + let name = STUBBED_METHODS_NAME[i]; + if (!ClientRequest$3.prototype[name]){ + this[name] = function method(){ + return this.genericStubber(name , arguments); + }.bind(this); + } + } + + var requestOptions , cb,url , args; + const isInternal = arguments[0] instanceof RequestInternalEnforce; + var isInternalMethod,isInternalProtocol; + if (isInternal){ + const enforceOptions = arguments[0]; + if ( enforceOptions.method) + isInternalMethod = enforceOptions.method; + if ( enforceOptions.protocol) + isInternalProtocol = enforceOptions.protocol; + } + if (isInternal){ + args = arguments[0].args; + } + else { + args = arguments; + } + if (args[2] != undefined){ + url = args[0]; + requestOptions = args[1]; + cb = args[2]; + } + else if(args[1] == undefined){ + requestOptions = args[0]; + } + else { + requestOptions = args[0]; + cb = args[1]; + } + cb = cb || function dummy(){}; + + if (typeof requestOptions === 'string') { + requestOptions = urlToOptions(new URL$3(requestOptions)); + if (!requestOptions.hostname) { + throw new Error('Unable to determine the domain name'); + } + } + else { + if (url){ + requestOptions = _extend(urlToOptions(new URL$3(url)), requestOptions); + } + else { + requestOptions = _extend({}, requestOptions); + } + } + + if (isInternalProtocol!=isInternalProtocol){ + requestOptions.protocol = isInternalProtocol; + } + + if (requestOptions.protocol == 'https:' && !requestOptions.port && requestOptions.port !=0) + requestOptions.port = 443; + + if (!requestOptions.port && requestOptions.port !=0) + requestOptions.port = 80; + + if (isInternalMethod){ + requestOptions.method = isInternalMethod; + } + else if (!requestOptions.method ) + requestOptions.method = 'GET'; + + requestOptions.method = requestOptions.method.toUpperCase(); + + const requestManager = requestOptions.requestManager || this.getGlobalManager(requestOptions); + requestManager.handleClientRequest(this , requestOptions , cb); +} +ClientRequest$3.prototype = { + getGlobalManager(options){ + if (options.agent) + return (options.agent.protocol == 'https:' ? HttpsRequest$1.globalManager : HttpRequest$1.globalManager); + else + return HttpRequestManager$1.globalManager; + }, + genericStubber(method , args){ + if (this[$stubs ]){ + this[$stubs].push([method,args]); + return true; + } + else + return this[method](...arguments); + }, + on(eventName , cb){ + if (eventName == 'response'){ + if (!cb.http2Safe){ + eventName = 'http1.response'; + arguments[0] = eventName; + } + } + if (this._on){ + this._on(...arguments); + } + else + this.genericStubber('on' , arguments); + + }, + once(eventName , cb){ + if (eventName == 'response'){ + if (!cb.http2Safe){ + eventName = 'http1.response'; + } + } + if (this._once){ + this._once(...arguments); + } + else + this.genericStubber('once' , arguments); + + }, + emitError(error) { + if (this[$stubs]){ + this[$stubs].forEach(([method, args]) => { + if ((method === 'on' || method === 'once') && args[0] === 'error') { + args[1](error); + } + }); + } + else + return this.emit('error', error); + }, + take(stream){ + //We forward all functions to the stream + for (var i=0;i<STUBBED_METHODS_NAME.length;i++){ + let name = STUBBED_METHODS_NAME[i]; + if (stream[name]){ + this[name] = stream[name].bind(stream); + } + // else{ + // throw new Error(`for stub ${name} no original method found`) + // } + } + this._on = stream.on.bind(stream); + this._once = stream.once.bind(stream); + this.proxyProps(stream); + //This should come later in case of user exception + //We trigger the all the stubs that were generted before + for (let i = 0; i<this[$stubs ].length;i++){ + var stub = this[$stubs ][i]; + stream[stub[0]](...stub[1]); + } + this[$stubs] = null; + }, + proxyProps(http2Stream){ + function getter(){ + return http2Stream[this]; + } + function setter(value){ + http2Stream[this] = value; + } + const notToProxy = ['on' , '_on','_once' , 'once','http2Mimic'].concat(STUBBED_METHODS_NAME); + const keys = Object.keys(this); + const keysToProxy = [].concat(PROPERTIES_TO_PROXY); + keys.forEach(function whichProxyKeys(key){ + if (notToProxy.indexOf(key) == -1 && keysToProxy.indexOf(key)==-1){ + keysToProxy.push(key); + } + }); + const properties = Object.getOwnPropertyDescriptors(http2Stream); + for (var i=0;i<keysToProxy.length;i++){ + let name = keysToProxy[i]; + const propConfig = properties[name]; + let shouldCopyValue; + if (!propConfig) + shouldCopyValue = true; + if (propConfig && (propConfig.writable || propConfig)) + shouldCopyValue = true; + + if (shouldCopyValue) + http2Stream[name] = this[name]; + + Object.defineProperty(this , name , { + get : getter.bind(name), + set : setter.bind(name), + }); + } + + } +}; + + +let HttpRequestManager$1 = class HttpRequestManager extends EventEmitter{ + constructor(options){ + super(); + this.httpsAgent = https$2.globalAgent; + this.httpAgent = http$3.globalAgent; + this.init(options); + } + log(){ + } + init(options){ + options = options || {}; + this.http2Clients = {}; + this.cachedHTTP1Result = {}; + this.setModules(); + this.http2Debouncer = new DebounceTimers(function stopConnection(key){ + this.log('stopping ' , key); + var foundConnection = this.http2Clients[key]; + if (foundConnection){ + this.removeHttp2Client(key , foundConnection); + } + }.bind(this) , 1000); + + this.keepH1IdentificationCacheFor = options.keepH1IdentificationCacheFor || 30000; + //the debouncer will accept only values greater then zero + this.http2Debouncer.setDelay(options.keepH2ConnectionFor); + if (options.useHttp){ + this.enforceProtocol = 'http:'; + } + else if(options.useHttps){ + this.enforceProtocol = 'https:'; + } + } + setModules() { + this['http'] = require$$0$a; + this['https'] = require$$1$4; + this['tls'] = require$$1$3; + this['net'] = require$$0$f; + this.http2Support = false; + try{ + this['http2'] = require('http2'); + this.http2Support = true; + } + catch(err){ + //It will automatically fallback to http + } + } + handleClientRequest(clientRequest , requestOptions ,cb){ + const requestManager = this; + const clientKey = requestManager.getClientKey(requestOptions); + + if (requestManager.hasCachedConnection(clientKey)){ + const socket = requestManager.getHttp2Client(clientKey); + const connectionOptions = { + createConnection(){ + return socket; + } + }; + process.nextTick(function onMakeRequest(){ + requestManager.makeRequest( clientRequest ,clientKey , requestOptions, cb , connectionOptions); + }.bind(requestManager)); + } + else + requestManager.holdConnectionToIdentification(clientKey , requestOptions , function onIdentification(error , connectionOptions){ + if (error) { + clientRequest.emitError(error); + return; + } + + requestManager.makeRequest(clientRequest , clientKey , requestOptions, cb , connectionOptions); + }.bind(requestManager)); + } + getClientKey(url){ + return `${url.protocol || this.enforceProtocol}${url.servername || url.host || url.hostname}:${url.port}`; + } + getHttp2Client(clientKey){ + return this.http2Clients[clientKey]; + } + setHttp2Client(clientKey , client){ + const httpManager = this; + const prevClient = httpManager.http2Clients[clientKey]; + if (prevClient) + httpManager.removeHttp2Client(clientKey , prevClient); + httpManager.http2Clients[clientKey] = client; + + function closeClient(){ + httpManager.removeHttp2Client(clientKey , client); + } + client.on('close' , closeClient); + client.on('goaway' , closeClient); + client.on('error' , closeClient); + client.on('frameError' , closeClient); + client.on('timeout' , closeClient); + + } + removeHttp2Client(clientKey , client){ + try{ + delete this.http2Clients[clientKey]; + if (!client.closed){ + client.close(); + } + } + catch(err){ + + } + client.removeAllListeners('close'); + client.removeAllListeners('error'); + client.removeAllListeners('frameError'); + client.removeAllListeners('timeout'); + } + request(url, options, cb){ + var args = new RequestInternalEnforce(arguments); + if (this.enforceProtocol){ + args.protocol = this.enforceProtocol; + } + return new ClientRequest$3(args) + } + get(){ + var args = new RequestInternalEnforce(arguments); + args.method = 'GET'; + var request = this.request(args); + request.end(); + return request; + } + hasCachedConnection(clientKey){ + const http2Client = this.getHttp2Client(clientKey); + if (http2Client){ + return true; + } + return this.cachedHTTP1Result[clientKey] + this.keepH1IdentificationCacheFor < Date.now(); + } + makeRequest(inStream , clientKey , requestOptions ,cb , connectionOptions){ + const http2Client = this.getHttp2Client(clientKey); + if (http2Client){ + return this.makeHttp2Request(clientKey , inStream , http2Client ,Object.assign(connectionOptions || {}, requestOptions), cb); + } + //It's http1.1 let Node.JS core manage it + if (!requestOptions.agent){ + if (requestOptions.protocol == 'https:') + requestOptions.agent = this.httpsAgent; + else + requestOptions.agent = this.httpAgent; + } + return this.makeHttpRequest(clientKey , inStream , requestOptions ,cb , connectionOptions); + } + holdConnectionToIdentification(clientKey , requestOptions , cb){ + const topic = `identify-${clientKey}`; + //If there are any pending identification process let's wait for one to finish + if (this._events[topic]) + this.once(topic , cb); //There is.. let's wait + else { + //We will need to start identification + this.once(topic , function letKnowThereIsAnEvent(){}); //There is.. let's wait + const socket = this.identifyConnection(requestOptions , function onIdentify(error , type){ + if (error) { + return cb(error); + } + + var options = { + createConnection(){ + return socket; + } + }; + if ( type == 'h2' && this.http2Support){ + var http2Client = this.http2.connect(requestOptions ,options); + this.setHttp2Client(clientKey , http2Client); + } + else { + //This is http1.1 + //Cache last result time + this.cachedHTTP1Result[clientKey] = Date.now(); + //Continue let core handle http1.1 + } + cb(null, options); + this.emit(topic , options); + }.bind(this)); + } + + } + makeHttpRequest(clientKey , inStream , options , cb , connectionOptions){ + if (options instanceof URL$3) + options = urlToOptions(options); + + const h1op = _extend({} , options); + if (connectionOptions) + h1op.createConnection = connectionOptions.createConnection; + + const requestModule = h1op.protocol == 'https:' ? this.https : this.http; + const req = requestModule.request(h1op ,cb); + + inStream.take(req); + inStream._on('response' , function onHttp1Response(v){this.emit('http1.response' , v);}); + + } + makeHttp2Request(clientKey , inStream , http2Client , requestOptions , cb){ + var http2Debouncer = this.http2Debouncer; + http2Debouncer.pause(clientKey); + var headers = _extend({} , requestOptions.headers || {}); + if (requestOptions.method) + headers[':method'] = requestOptions.method; + if (requestOptions.path) + headers[':path'] = requestOptions.path; + + Object.keys(headers).forEach((key)=>{ + if (HEADERS_TO_REMOVE.indexOf( (key+'').toLowerCase() ) !=-1){ + delete headers[key]; + } + }); + requestOptions.headers = headers; + var req = http2Client.request( + headers + ); + inStream.emit('socket' , requestOptions.createConnection()); + + let maxContentLength; + let currentContent = 0; + + req.on('data' , function onData(data){ + currentContent+=data.length; + if (currentContent>= maxContentLength) + http2Debouncer.unpauseAndTime(clientKey); + }); + inStream.take(req); + function onResponse(headers){ + maxContentLength = parseInt(headers['content-length']); + if (maxContentLength < 0 ) + this.http2Debouncer.unpauseAndTime(clientKey); + + HttpRequestManager.httpCompatibleResponse(req , requestOptions , headers); + inStream.emit('http1.response' , req); + if (cb) + cb(req); + } + onResponse.http2Safe = true; + req.once('response' , onResponse.bind(this)); + } + static httpCompatibleResponse(res , requestOptions , headers){ + res.httpVersion = '2.0'; + res.rawHeaders = headers; + res.headers = headers; + res.statusCode = headers[':status']; + delete headers[':status']; + } + identifyConnection(requestOptions , cb){ + var socket = this.connect( requestOptions, { allowHTTP1: true }, function onConnect(){ + socket.removeListener('error', cb); + + if (socket.alpnProtocol == 'h2'){ + cb(null, 'h2'); + } + else { + //close http1.1 connection is it cannot be reused + socket.end(); + cb(null, 'h1'); + } + }); + socket.on('error', cb); + return socket; + } + connect(authority, options, listener) { + if (typeof options === 'function') { + listener = options; + options = undefined; + } + + assertIsObject(options, 'options'); + options = Object.assign({}, options); + + if (typeof authority === 'string') + authority = new URL$3(authority); + + assertIsObject(authority, 'authority', ['string', 'Object', 'URL']); + + var protocol = authority.protocol || options.protocol || (this.enforceProtocol != 'detect' ? this.enforceProtocol : null) || 'http:'; + var port = '' + (authority.port !== '' ? + authority.port : (authority.protocol === 'http:' ? 80 : 443)); + var host = authority.hostname || authority.host || 'localhost'; + + var socket; + if (typeof options.createConnection === 'function') { + socket = options.createConnection(authority, options); + } else { + switch (protocol) { + case 'http:': + socket = this.net.connect(port, host , listener); + break; + case 'https:': + socket = this.tls.connect(port, host, initializeTLSOptions.call(this , options, host) , listener); + break; + default: + throw new Error('Not supprted' + protocol); + } + } + return socket; + } +}; +function urlToOptions(url) { + var options = { + protocol: url.protocol, + hostname: 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; +} +class RequestInternalEnforce{ + constructor(args){ + if (args[0] instanceof RequestInternalEnforce){ + return args[0]; + } + this.args = args; + this.method = null; + this.protocol = null; + } +} + +let HttpsRequest$1 = class HttpsRequest extends HttpRequestManager$1{ + constructor(){ + super(...arguments); + this.Agent = https$2.Agent; + this.globalAgent = https$2.globalAgent; + this.enforceProtocol = 'https:'; + } +}; +const httpsRequestSinglton = new HttpsRequest$1; +HttpsRequest$1.globalManager = httpsRequestSinglton; +HttpsRequest$1.Manager = HttpsRequest$1; + +let HttpRequest$1 = class HttpRequest extends HttpRequestManager$1{ + constructor(){ + super(...arguments); + this.Agent = http$3.Agent; + this.globalAgent = http$3.globalAgent; + this.enforceProtocol = 'http:'; + } +}; +const httpRequestSinglton = new HttpRequest$1; +HttpRequest$1.globalManager = httpRequestSinglton; +HttpRequest$1.Manager = HttpRequest$1; + +const singeltonHttpManager = new HttpRequestManager$1(); +singeltonHttpManager.enforceProtocol = 'detect'; +HttpRequestManager$1.globalManager = singeltonHttpManager; + +var request$3 = { + HttpRequest: HttpRequest$1, + HttpsRequest: HttpsRequest$1, + HTTP2OutgoingMessage : ClientRequest$3, + ClientRequest: ClientRequest$3, + HttpRequestManager: HttpRequestManager$1 +}; + +const { + HttpRequest,ClientRequest: ClientRequest$2 +} = request$3; + +const globalManager$1 = HttpRequest.globalManager; +const request$2 = globalManager$1.request.bind(globalManager$1); +const get$5 = globalManager$1.get.bind(globalManager$1); + +const http$2 = Object.assign({},require$$0$a); + +var http_1 = Object.assign(http$2 , { + ClientRequest: ClientRequest$2, + globalManager: globalManager$1, + request: request$2, + get: get$5 +}); + +const { + HttpsRequest, + ClientRequest: ClientRequest$1 +} = request$3; + +const globalManager = HttpsRequest.globalManager; +const request$1 = globalManager.request.bind(globalManager); +const get$4 = globalManager.get.bind(globalManager); + +const https$1 = Object.assign({},require$$1$4); + +var https_1 = Object.assign(https$1 , { + ClientRequest: ClientRequest$1, + globalManager, + request: request$1, + get: get$4 +}); + +const { + HttpRequestManager , HTTP2OutgoingMessage,ClientRequest +} = request$3; +const http$1 = http_1; +const https = https_1; + +const autoDetectManager = new HttpRequestManager(); +HttpRequestManager.globalManager = autoDetectManager; +const request = autoDetectManager.request.bind(autoDetectManager); +const get$3 = autoDetectManager.get.bind(autoDetectManager); + + +var lib$9 = { + HTTP2OutgoingMessage, + ClientRequest, + globalManager : HttpRequestManager.globalManager , + request, + get: get$3, + http: http$1, + https: https +}; + +var h2 = /*@__PURE__*/getDefaultExportFromCjs(lib$9); + +// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js +// (MIT licensed) + +const BUFFER$1 = Symbol('buffer'); +const TYPE$1 = Symbol('type'); + +let Blob$2 = class Blob { + constructor() { + this[TYPE$1] = ''; + + const blobParts = arguments[0]; + const options = arguments[1]; + + const buffers = []; + + 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$1]; + } else { + buffer = Buffer.from(typeof element === 'string' ? element : String(element)); + } + buffers.push(buffer); + } + } + + this[BUFFER$1] = Buffer.concat(buffers); + + let type = options && options.type !== undefined && String(options.type).toLowerCase(); + if (type && !/[^\u0020-\u007E]/.test(type)) { + this[TYPE$1] = type; + } + } + get size() { + return this[BUFFER$1].length; + } + get type() { + return this[TYPE$1]; + } + 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$1]; + const slicedBuffer = buffer.slice(relativeStart, relativeStart + span); + const blob = new Blob([], { type: arguments[2] }); + blob[BUFFER$1] = slicedBuffer; + return blob; + } +}; + +Object.defineProperties(Blob$2.prototype, { + size: { enumerable: true }, + type: { enumerable: true }, + slice: { enumerable: true } +}); + +Object.defineProperty(Blob$2.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$1(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$1.prototype = Object.create(Error.prototype); +FetchError$1.prototype.constructor = FetchError$1; +FetchError$1.prototype.name = 'FetchError'; + +let convert$1; +try { + convert$1 = require('encoding').convert; +} catch (e) {} + +const INTERNALS$3 = Symbol('Body internals'); + +// fix an issue where "PassThrough" isn't a named export for node <10 +const PassThrough$1 = Stream$3.PassThrough; + +/** + * Body mixin + * + * Ref: https://fetch.spec.whatwg.org/#body + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +function Body$1(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$1(body)) { + // body is a URLSearchParams + body = Buffer.from(body.toString()); + } else if (body instanceof Blob$2) { + // body is blob + body = body[BUFFER$1]; + } 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$3) ; else { + // none of the above + // coerce to string then buffer + body = Buffer.from(String(body)); + } + this[INTERNALS$3] = { + body, + disturbed: false, + error: null + }; + this.size = size; + this.timeout = timeout; + + if (body instanceof Stream$3) { + body.on('error', function (err) { + const error = err.name === 'AbortError' ? err : new FetchError$1(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err); + _this[INTERNALS$3].error = error; + }); + } +} + +Body$1.prototype = { + get body() { + return this[INTERNALS$3].body; + }, + + get bodyUsed() { + return this[INTERNALS$3].disturbed; + }, + + /** + * Decode response as ArrayBuffer + * + * @return Promise + */ + arrayBuffer() { + return consumeBody$1.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$1.call(this).then(function (buf) { + return Object.assign( + // Prevent copying + new Blob$2([], { + type: ct.toLowerCase() + }), { + [BUFFER$1]: buf + }); + }); + }, + + /** + * Decode response as json + * + * @return Promise + */ + json() { + var _this2 = this; + + return consumeBody$1.call(this).then(function (buffer) { + try { + return JSON.parse(buffer.toString()); + } catch (err) { + return Body$1.Promise.reject(new FetchError$1(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json')); + } + }); + }, + + /** + * Decode response as text + * + * @return Promise + */ + text() { + return consumeBody$1.call(this).then(function (buffer) { + return buffer.toString(); + }); + }, + + /** + * Decode response as buffer (non-spec api) + * + * @return Promise + */ + buffer() { + return consumeBody$1.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$1.call(this).then(function (buffer) { + return convertBody$1(buffer, _this3.headers); + }); + } +}; + +// In browsers, all properties are enumerable. +Object.defineProperties(Body$1.prototype, { + body: { enumerable: true }, + bodyUsed: { enumerable: true }, + arrayBuffer: { enumerable: true }, + blob: { enumerable: true }, + json: { enumerable: true }, + text: { enumerable: true } +}); + +Body$1.mixIn = function (proto) { + for (const name of Object.getOwnPropertyNames(Body$1.prototype)) { + // istanbul ignore else: future proof + if (!(name in proto)) { + const desc = Object.getOwnPropertyDescriptor(Body$1.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$1() { + var _this4 = this; + + if (this[INTERNALS$3].disturbed) { + return Body$1.Promise.reject(new TypeError(`body used already for: ${this.url}`)); + } + + this[INTERNALS$3].disturbed = true; + + if (this[INTERNALS$3].error) { + return Body$1.Promise.reject(this[INTERNALS$3].error); + } + + // body is null + if (this.body === null) { + return Body$1.Promise.resolve(Buffer.alloc(0)); + } + + // body is buffer + if (Buffer.isBuffer(this.body)) { + return Body$1.Promise.resolve(this.body); + } + + // istanbul ignore if: should never happen + if (!(this.body instanceof Stream$3)) { + return Body$1.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$1.Promise(function (resolve, reject) { + let resTimeout; + + // allow timeout on slow response body + if (_this4.timeout) { + resTimeout = setTimeout(function () { + abort = true; + reject(new FetchError$1(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout')); + }, _this4.timeout); + } + + // handle stream errors + _this4.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$1(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + + _this4.body.on('data', function (chunk) { + if (abort || chunk === null) { + return; + } + + if (_this4.size && accumBytes + chunk.length > _this4.size) { + abort = true; + reject(new FetchError$1(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size')); + return; + } + + accumBytes += chunk.length; + accum.push(chunk); + }); + + _this4.body.on('end', function () { + if (abort) { + return; + } + + clearTimeout(resTimeout); + + try { + resolve(Buffer.concat(accum)); + } catch (err) { + // handle streams that have accumulated too much data (issue #414) + reject(new FetchError$1(`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$1(buffer, headers) { + if (typeof convert$1 !== '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 = /<meta.+?charset=(['"])(.+?)\1/i.exec(str); + } + + // html4 + if (!res && str) { + res = /<meta[\s]+?http-equiv=(['"])content-type\1[\s]+?content=(['"])(.+?)\2/i.exec(str); + + if (res) { + res = /charset=(.*)/i.exec(res.pop()); + } + } + + // xml + if (!res && str) { + res = /<\?xml.+?encoding=(['"])(.+?)\1/i.exec(str); + } + + // found charset + if (res) { + charset = res.pop(); + + // prevent decode issues when sites use incorrect encoding + // ref: https://hsivonen.fi/encoding-menu/ + if (charset === 'gb2312' || charset === 'gbk') { + charset = 'gb18030'; + } + } + + // turn raw buffers into a single utf-8 buffer + return convert$1(buffer, 'UTF-8', charset).toString(); +} + +/** + * Detect a URLSearchParams object + * ref: https://github.com/bitinn/node-fetch/issues/296#issuecomment-307598143 + * + * @param Object obj Object to detect by type or brand + * @return String + */ +function isURLSearchParams$1(obj) { + // Duck-typing as a necessary condition. + if (typeof obj !== 'object' || typeof obj.append !== 'function' || typeof obj.delete !== 'function' || typeof obj.get !== 'function' || typeof obj.getAll !== 'function' || typeof obj.has !== 'function' || typeof obj.set !== 'function') { + return false; + } + + // Brand-checking and more duck-typing as optional condition. + return obj.constructor.name === 'URLSearchParams' || Object.prototype.toString.call(obj) === '[object URLSearchParams]' || typeof obj.sort === 'function'; +} + +/** + * Clone body given Res/Req instance + * + * @param Mixed instance Response or Request instance + * @return Mixed + */ +function clone$7(instance) { + let p1, p2; + let body = instance.body; + + // 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 PassThrough$1(); + p2 = new PassThrough$1(); + body.pipe(p1); + body.pipe(p2); + // set instance body to teed body and return the other teed body + instance[INTERNALS$3].body = p1; + body = p2; + } + + return body; +} + +/** + * 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 Mixed instance Response or Request instance + */ +function extractContentType$1(body) { + // istanbul ignore if: Currently, because of a guard in Request, body + // can never be null. Included here for completeness. + if (body === null) { + // body is null + return null; + } else if (typeof body === 'string') { + // body is string + return 'text/plain;charset=UTF-8'; + } else if (isURLSearchParams$1(body)) { + // body is a URLSearchParams + return 'application/x-www-form-urlencoded;charset=UTF-8'; + } else if (body instanceof Blob$2) { + // body is blob + return body.type || null; + } else if (Buffer.isBuffer(body)) { + // body is buffer + return null; + } else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') { + // body is ArrayBuffer + return null; + } else if (ArrayBuffer.isView(body)) { + // body is ArrayBufferView + return null; + } else if (typeof body.getBoundary === 'function') { + // detect form data input from form-data module + return `multipart/form-data;boundary=${body.getBoundary()}`; + } else if (body instanceof Stream$3) { + // body is stream + // can't really do much about this + return null; + } else { + // 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 Body instance Instance of Body + * @return Number? Number of bytes, or null if not possible + */ +function getTotalBytes(instance) { + const body = instance.body; + + // istanbul ignore if: included for completion + + if (body === null) { + // body is null + return 0; + } else if (Buffer.isBuffer(body)) { + // body is buffer + return body.length; + } else if (body && typeof body.getLengthSync === 'function') { + // detect form data input from form-data module + if (body._lengthRetrievers && body._lengthRetrievers.length == 0 || // 1.x + body.hasKnownLength && body.hasKnownLength()) { + // 2.x + return body.getLengthSync(); + } + return null; + } else { + // body is stream + // can't really do much about this + return null; + } +} + +/** + * Write a Body to a Node.js WritableStream (e.g. http.Request) object. + * + * @param Body instance Instance of Body + * @return Void + */ +function writeToStream(dest, instance) { + const body = instance.body; + + + if (body === null) { + // body is null + dest.end(); + } else if (Buffer.isBuffer(body)) { + // body is buffer + dest.write(body); + dest.end(); + } else { + // body is stream + body.pipe(dest); + } +} + +// expose Promise +Body$1.Promise = global.Promise; + +/** + * headers.js + * + * Headers class offers convenient helpers + */ + +const invalidTokenRegex$1 = /[^\^_`a-zA-Z\-0-9!#$%&'*+.|~]/; +const invalidHeaderCharRegex$1 = /[^\t\x20-\x7e\x80-\xff]/; + +function validateName$1(name) { + name = `${name}`; + if (invalidTokenRegex$1.test(name)) { + throw new TypeError(`${name} is not a legal HTTP header name`); + } +} + +function validateValue$1(value) { + value = `${value}`; + if (invalidHeaderCharRegex$1.test(value)) { + throw new TypeError(`${value} is not a legal HTTP header value`); + } +} + +/** + * Find the key in the map object given a header name. + * + * Returns undefined if not found. + * + * @param String name Header name + * @return String|Undefined + */ +function find$1(map, name) { + name = name.toLowerCase(); + for (const key in map) { + if (key.toLowerCase() === name) { + return key; + } + } + return undefined; +} + +const MAP$1 = Symbol('map'); +let Headers$1 = class Headers { + /** + * Headers class + * + * @param Object headers Response headers + * @return Void + */ + constructor() { + let init = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : undefined; + + this[MAP$1] = 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<sequence<ByteString>> + // 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<ByteString, ByteString> + 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$1(name); + const key = find$1(this[MAP$1], name); + if (key === undefined) { + return null; + } + + return this[MAP$1][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$1(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$1(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$1(name); + validateValue$1(value); + const key = find$1(this[MAP$1], name); + this[MAP$1][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$1(name); + validateValue$1(value); + const key = find$1(this[MAP$1], name); + if (key !== undefined) { + this[MAP$1][key].push(value); + } else { + this[MAP$1][name] = [value]; + } + } + + /** + * Check for header name existence + * + * @param String name Header name + * @return Boolean + */ + has(name) { + name = `${name}`; + validateName$1(name); + return find$1(this[MAP$1], name) !== undefined; + } + + /** + * Delete all header values given name + * + * @param String name Header name + * @return Void + */ + delete(name) { + name = `${name}`; + validateName$1(name); + const key = find$1(this[MAP$1], name); + if (key !== undefined) { + delete this[MAP$1][key]; + } + } + + /** + * Return raw headers (non-spec api) + * + * @return Object + */ + raw() { + return this[MAP$1]; + } + + /** + * Get an iterator on keys. + * + * @return Iterator + */ + keys() { + return createHeadersIterator$1(this, 'key'); + } + + /** + * Get an iterator on values. + * + * @return Iterator + */ + values() { + return createHeadersIterator$1(this, 'value'); + } + + /** + * Get an iterator on entries. + * + * This is the default iterator of the Headers object. + * + * @return Iterator + */ + [Symbol.iterator]() { + return createHeadersIterator$1(this, 'key+value'); + } +}; +Headers$1.prototype.entries = Headers$1.prototype[Symbol.iterator]; + +Object.defineProperty(Headers$1.prototype, Symbol.toStringTag, { + value: 'Headers', + writable: false, + enumerable: false, + configurable: true +}); + +Object.defineProperties(Headers$1.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$1(headers) { + let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value'; + + const keys = Object.keys(headers[MAP$1]).sort(); + return keys.map(kind === 'key' ? function (k) { + return k.toLowerCase(); + } : kind === 'value' ? function (k) { + return headers[MAP$1][k].join(', '); + } : function (k) { + return [k.toLowerCase(), headers[MAP$1][k].join(', ')]; + }); +} + +const INTERNAL$1 = Symbol('internal'); + +function createHeadersIterator$1(target, kind) { + const iterator = Object.create(HeadersIteratorPrototype$1); + iterator[INTERNAL$1] = { + target, + kind, + index: 0 + }; + return iterator; +} + +const HeadersIteratorPrototype$1 = Object.setPrototypeOf({ + next() { + // istanbul ignore if + if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype$1) { + throw new TypeError('Value of `this` is not a HeadersIterator'); + } + + var _INTERNAL = this[INTERNAL$1]; + const target = _INTERNAL.target, + kind = _INTERNAL.kind, + index = _INTERNAL.index; + + const values = getHeaders$1(target, kind); + const len = values.length; + if (index >= len) { + return { + value: undefined, + done: true + }; + } + + this[INTERNAL$1].index = index + 1; + + return { + value: values[index], + done: false + }; + } +}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))); + +Object.defineProperty(HeadersIteratorPrototype$1, 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$1]); + + // http.request() only supports string as Host header. This hack makes + // specifying custom Host header possible. + const hostHeaderKey = find$1(headers[MAP$1], '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$1(); + for (const name of Object.keys(obj)) { + if (invalidTokenRegex$1.test(name)) { + continue; + } + if (Array.isArray(obj[name])) { + for (const val of obj[name]) { + if (invalidHeaderCharRegex$1.test(val)) { + continue; + } + if (headers[MAP$1][name] === undefined) { + headers[MAP$1][name] = [val]; + } else { + headers[MAP$1][name].push(val); + } + } + } else if (!invalidHeaderCharRegex$1.test(obj[name])) { + headers[MAP$1][name] = [obj[name]]; + } + } + return headers; +} + +const INTERNALS$1$1 = Symbol('Response internals'); + +// fix an issue where "STATUS_CODES" aren't a named export for node <10 +const STATUS_CODES$1 = require$$0$a.STATUS_CODES; + +/** + * Response class + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +let Response$1 = 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$1.call(this, body, opts); + + const status = opts.status || 200; + const headers = new Headers$1(opts.headers); + + if (body != null && !headers.has('Content-Type')) { + const contentType = extractContentType$1(body); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + this[INTERNALS$1$1] = { + url: opts.url, + status, + statusText: opts.statusText || STATUS_CODES$1[status], + headers + }; + } + + get url() { + return this[INTERNALS$1$1].url; + } + + get status() { + return this[INTERNALS$1$1].status; + } + + /** + * Convenience property representing if the request ended normally + */ + get ok() { + return this[INTERNALS$1$1].status >= 200 && this[INTERNALS$1$1].status < 300; + } + + get statusText() { + return this[INTERNALS$1$1].statusText; + } + + get headers() { + return this[INTERNALS$1$1].headers; + } + + /** + * Clone this response + * + * @return Response + */ + clone() { + return new Response(clone$7(this), { + url: this.url, + status: this.status, + statusText: this.statusText, + headers: this.headers, + ok: this.ok + }); + } +}; + +Body$1.mixIn(Response$1.prototype); + +Object.defineProperties(Response$1.prototype, { + url: { enumerable: true }, + status: { enumerable: true }, + ok: { enumerable: true }, + statusText: { enumerable: true }, + headers: { enumerable: true }, + clone: { enumerable: true } +}); + +Object.defineProperty(Response$1.prototype, Symbol.toStringTag, { + value: 'Response', + writable: false, + enumerable: false, + configurable: true +}); + +const INTERNALS$2$1 = Symbol('Request internals'); + +// fix an issue where "format", "parse" aren't a named export for node <10 +const parse_url$1 = require$$0$e.parse; +const format_url$1 = require$$0$e.format; + +const streamDestructionSupported = 'destroy' in Stream$3.Readable.prototype; + +/** + * Check if a value is an instance of Request. + * + * @param Mixed input + * @return Boolean + */ +function isRequest$1(input) { + return typeof input === 'object' && typeof input[INTERNALS$2$1] === 'object'; +} + +function isAbortSignal$1(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 + */ +let Request$1 = class Request { + constructor(input) { + let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + let parsedURL; + + // normalize input + if (!isRequest$1(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 = parse_url$1(input.href); + } else { + // coerce input to a string before attempting to parse + parsedURL = parse_url$1(`${input}`); + } + input = {}; + } else { + parsedURL = parse_url$1(input.url); + } + + let method = init.method || input.method || 'GET'; + method = method.toUpperCase(); + + if ((init.body != null || isRequest$1(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$1(input) && input.body !== null ? clone$7(input) : null; + + Body$1.call(this, inputBody, { + timeout: init.timeout || input.timeout || 0, + size: init.size || input.size || 0 + }); + + const headers = new Headers$1(init.headers || input.headers || {}); + + if (inputBody != null && !headers.has('Content-Type')) { + const contentType = extractContentType$1(inputBody); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + let signal = isRequest$1(input) ? input.signal : null; + if ('signal' in init) signal = init.signal; + + if (signal != null && !isAbortSignal$1(signal)) { + throw new TypeError('Expected signal to be an instanceof AbortSignal'); + } + + this[INTERNALS$2$1] = { + 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$1].method; + } + + get url() { + return format_url$1(this[INTERNALS$2$1].parsedURL); + } + + get headers() { + return this[INTERNALS$2$1].headers; + } + + get redirect() { + return this[INTERNALS$2$1].redirect; + } + + get signal() { + return this[INTERNALS$2$1].signal; + } + + /** + * Clone this request + * + * @return Request + */ + clone() { + return new Request(this); + } +}; + +Body$1.mixIn(Request$1.prototype); + +Object.defineProperty(Request$1.prototype, Symbol.toStringTag, { + value: 'Request', + writable: false, + enumerable: false, + configurable: true +}); + +Object.defineProperties(Request$1.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$1].parsedURL; + const headers = new Headers$1(request[INTERNALS$2$1].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$3.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'); + } + + if (!headers.has('Connection') && !request.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: request.agent + }); +} + +/** + * abort-error.js + * + * AbortError interface for cancelled requests + */ + +/** + * Create AbortError instance + * + * @param String message Error message for human + * @return AbortError + */ +function AbortError$1(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$1.prototype = Object.create(Error.prototype); +AbortError$1.prototype.constructor = AbortError$1; +AbortError$1.prototype.name = 'AbortError'; + +// fix an issue where "PassThrough", "resolve" aren't a named export for node <10 +const PassThrough$1$1 = Stream$3.PassThrough; +const resolve_url = require$$0$e.resolve; + +/** + * Fetch function + * + * @param Mixed url Absolute url or Request instance + * @param Object opts Fetch options + * @return Promise + */ +function fetch$3(url, opts) { + + // allow custom promise + if (!fetch$3.Promise) { + throw new Error('native promise missing, set fetch.Promise to your favorite alternative'); + } + + Body$1.Promise = fetch$3.Promise; + + // wrap http.request into fetch + return new fetch$3.Promise(function (resolve, reject) { + // build request object + const request = new Request$1(url, opts); + const options = getNodeRequestOptions(request); + + const send = h2.request; + const signal = request.signal; + + let response = null; + + const abort = function abort() { + let error = new AbortError$1('The user aborted a request.'); + 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 = 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$1(`network timeout at: ${request.url}`, 'request-timeout')); + finalize(); + }, request.timeout); + }); + } + + req.on('error', function (err) { + reject(new FetchError$1(`request to ${request.url} failed, reason: ${err.message}`, 'system', err)); + finalize(); + }); + + req.on('response', function (res) { + clearTimeout(reqTimeout); + + const headers = createHeadersLenient(res.headers); + + // HTTP fetch step 5 + if (fetch$3.isRedirect(res.statusCode)) { + // HTTP fetch step 5.2 + const location = headers.get('Location'); + + // HTTP fetch step 5.3 + const locationURL = location === null ? null : resolve_url(request.url, location); + + // HTTP fetch step 5.5 + switch (request.redirect) { + case 'error': + reject(new FetchError$1(`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$1(`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$1(request.headers), + follow: request.follow, + counter: request.counter + 1, + agent: request.agent, + compress: request.compress, + method: request.method, + body: request.body, + signal: request.signal + }; + + // HTTP-redirect fetch step 9 + if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) { + reject(new FetchError$1('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$3(new Request$1(locationURL, requestOpts))); + finalize(); + return; + } + } + + // prepare response + res.once('end', function () { + if (signal) signal.removeEventListener('abort', abortAndFinalize); + }); + let body = res.pipe(new PassThrough$1$1()); + + const response_options = { + url: request.url, + status: res.statusCode, + statusText: res.statusMessage, + headers: headers, + size: request.size, + timeout: request.timeout + }; + + // 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$1(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$1.Z_SYNC_FLUSH, + finishFlush: zlib$1.Z_SYNC_FLUSH + }; + + // for gzip + if (codings == 'gzip' || codings == 'x-gzip') { + body = body.pipe(zlib$1.createGunzip(zlibOptions)); + response = new Response$1(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$1()); + raw.once('data', function (chunk) { + // see http://stackoverflow.com/questions/37519828 + if ((chunk[0] & 0x0F) === 0x08) { + body = body.pipe(zlib$1.createInflate()); + } else { + body = body.pipe(zlib$1.createInflateRaw()); + } + response = new Response$1(body, response_options); + resolve(response); + }); + return; + } + + // otherwise, use response as-is + response = new Response$1(body, response_options); + resolve(response); + }); + + writeToStream(req, request); + }); +} +/** + * Redirect code matching + * + * @param Number code Status code + * @return Boolean + */ +fetch$3.isRedirect = function (code) { + return code === 301 || code === 302 || code === 303 || code === 307 || code === 308; +}; + +// expose Promise +fetch$3.Promise = global.Promise; + +var lib$8 = /*#__PURE__*/Object.freeze({ + __proto__: null, + FetchError: FetchError$1, + Headers: Headers$1, + Request: Request$1, + Response: Response$1, + default: fetch$3 +}); + +var require$$4 = /*@__PURE__*/getAugmentedNamespace(lib$8); + +var dist = {}; + +var parseCst$1 = {}; + +var PlainValueEc8e588e = {}; + +const Char = { + ANCHOR: '&', + COMMENT: '#', + TAG: '!', + DIRECTIVES_END: '-', + DOCUMENT_END: '.' +}; +const Type = { + ALIAS: 'ALIAS', + BLANK_LINE: 'BLANK_LINE', + BLOCK_FOLDED: 'BLOCK_FOLDED', + BLOCK_LITERAL: 'BLOCK_LITERAL', + COMMENT: 'COMMENT', + DIRECTIVE: 'DIRECTIVE', + DOCUMENT: 'DOCUMENT', + FLOW_MAP: 'FLOW_MAP', + FLOW_SEQ: 'FLOW_SEQ', + MAP: 'MAP', + MAP_KEY: 'MAP_KEY', + MAP_VALUE: 'MAP_VALUE', + PLAIN: 'PLAIN', + QUOTE_DOUBLE: 'QUOTE_DOUBLE', + QUOTE_SINGLE: 'QUOTE_SINGLE', + SEQ: 'SEQ', + SEQ_ITEM: 'SEQ_ITEM' +}; +const defaultTagPrefix = 'tag:yaml.org,2002:'; +const defaultTags = { + MAP: 'tag:yaml.org,2002:map', + SEQ: 'tag:yaml.org,2002:seq', + STR: 'tag:yaml.org,2002:str' +}; + +function findLineStarts(src) { + const ls = [0]; + let offset = src.indexOf('\n'); + + while (offset !== -1) { + offset += 1; + ls.push(offset); + offset = src.indexOf('\n', offset); + } + + return ls; +} + +function getSrcInfo(cst) { + let lineStarts, src; + + if (typeof cst === 'string') { + lineStarts = findLineStarts(cst); + src = cst; + } else { + if (Array.isArray(cst)) cst = cst[0]; + + if (cst && cst.context) { + if (!cst.lineStarts) cst.lineStarts = findLineStarts(cst.context.src); + lineStarts = cst.lineStarts; + src = cst.context.src; + } + } + + return { + lineStarts, + src + }; +} +/** + * @typedef {Object} LinePos - One-indexed position in the source + * @property {number} line + * @property {number} col + */ + +/** + * Determine the line/col position matching a character offset. + * + * Accepts a source string or a CST document as the second parameter. With + * the latter, starting indices for lines are cached in the document as + * `lineStarts: number[]`. + * + * Returns a one-indexed `{ line, col }` location if found, or + * `undefined` otherwise. + * + * @param {number} offset + * @param {string|Document|Document[]} cst + * @returns {?LinePos} + */ + + +function getLinePos(offset, cst) { + if (typeof offset !== 'number' || offset < 0) return null; + const { + lineStarts, + src + } = getSrcInfo(cst); + if (!lineStarts || !src || offset > src.length) return null; + + for (let i = 0; i < lineStarts.length; ++i) { + const start = lineStarts[i]; + + if (offset < start) { + return { + line: i, + col: offset - lineStarts[i - 1] + 1 + }; + } + + if (offset === start) return { + line: i + 1, + col: 1 + }; + } + + const line = lineStarts.length; + return { + line, + col: offset - lineStarts[line - 1] + 1 + }; +} +/** + * Get a specified line from the source. + * + * Accepts a source string or a CST document as the second parameter. With + * the latter, starting indices for lines are cached in the document as + * `lineStarts: number[]`. + * + * Returns the line as a string if found, or `null` otherwise. + * + * @param {number} line One-indexed line number + * @param {string|Document|Document[]} cst + * @returns {?string} + */ + +function getLine(line, cst) { + const { + lineStarts, + src + } = getSrcInfo(cst); + if (!lineStarts || !(line >= 1) || line > lineStarts.length) return null; + const start = lineStarts[line - 1]; + let end = lineStarts[line]; // undefined for last line; that's ok for slice() + + while (end && end > start && src[end - 1] === '\n') --end; + + return src.slice(start, end); +} +/** + * Pretty-print the starting line from the source indicated by the range `pos` + * + * Trims output to `maxWidth` chars while keeping the starting column visible, + * using `…` at either end to indicate dropped characters. + * + * Returns a two-line string (or `null`) with `\n` as separator; the second line + * will hold appropriately indented `^` marks indicating the column range. + * + * @param {Object} pos + * @param {LinePos} pos.start + * @param {LinePos} [pos.end] + * @param {string|Document|Document[]*} cst + * @param {number} [maxWidth=80] + * @returns {?string} + */ + +function getPrettyContext({ + start, + end +}, cst, maxWidth = 80) { + let src = getLine(start.line, cst); + if (!src) return null; + let { + col + } = start; + + if (src.length > maxWidth) { + if (col <= maxWidth - 10) { + src = src.substr(0, maxWidth - 1) + '…'; + } else { + const halfWidth = Math.round(maxWidth / 2); + if (src.length > col + halfWidth) src = src.substr(0, col + halfWidth - 1) + '…'; + col -= src.length - maxWidth; + src = '…' + src.substr(1 - maxWidth); + } + } + + let errLen = 1; + let errEnd = ''; + + if (end) { + if (end.line === start.line && col + (end.col - start.col) <= maxWidth + 1) { + errLen = end.col - start.col; + } else { + errLen = Math.min(src.length + 1, maxWidth) - col; + errEnd = '…'; + } + } + + const offset = col > 1 ? ' '.repeat(col - 1) : ''; + const err = '^'.repeat(errLen); + return `${src}\n${offset}${err}${errEnd}`; +} + +class Range { + static copy(orig) { + return new Range(orig.start, orig.end); + } + + constructor(start, end) { + this.start = start; + this.end = end || start; + } + + isEmpty() { + return typeof this.start !== 'number' || !this.end || this.end <= this.start; + } + /** + * Set `origStart` and `origEnd` to point to the original source range for + * this node, which may differ due to dropped CR characters. + * + * @param {number[]} cr - Positions of dropped CR characters + * @param {number} offset - Starting index of `cr` from the last call + * @returns {number} - The next offset, matching the one found for `origStart` + */ + + + setOrigRange(cr, offset) { + const { + start, + end + } = this; + + if (cr.length === 0 || end <= cr[0]) { + this.origStart = start; + this.origEnd = end; + return offset; + } + + let i = offset; + + while (i < cr.length) { + if (cr[i] > start) break;else ++i; + } + + this.origStart = start + i; + const nextOffset = i; + + while (i < cr.length) { + // if end was at \n, it should now be at \r + if (cr[i] >= end) break;else ++i; + } + + this.origEnd = end + i; + return nextOffset; + } + +} + +/** Root class of all nodes */ + +let Node$1 = class Node { + static addStringTerminator(src, offset, str) { + if (str[str.length - 1] === '\n') return str; + const next = Node.endOfWhiteSpace(src, offset); + return next >= src.length || src[next] === '\n' ? str + '\n' : str; + } // ^(---|...) + + + static atDocumentBoundary(src, offset, sep) { + const ch0 = src[offset]; + if (!ch0) return true; + const prev = src[offset - 1]; + if (prev && prev !== '\n') return false; + + if (sep) { + if (ch0 !== sep) return false; + } else { + if (ch0 !== Char.DIRECTIVES_END && ch0 !== Char.DOCUMENT_END) return false; + } + + const ch1 = src[offset + 1]; + const ch2 = src[offset + 2]; + if (ch1 !== ch0 || ch2 !== ch0) return false; + const ch3 = src[offset + 3]; + return !ch3 || ch3 === '\n' || ch3 === '\t' || ch3 === ' '; + } + + static endOfIdentifier(src, offset) { + let ch = src[offset]; + const isVerbatim = ch === '<'; + const notOk = isVerbatim ? ['\n', '\t', ' ', '>'] : ['\n', '\t', ' ', '[', ']', '{', '}', ',']; + + while (ch && notOk.indexOf(ch) === -1) ch = src[offset += 1]; + + if (isVerbatim && ch === '>') offset += 1; + return offset; + } + + static endOfIndent(src, offset) { + let ch = src[offset]; + + while (ch === ' ') ch = src[offset += 1]; + + return offset; + } + + static endOfLine(src, offset) { + let ch = src[offset]; + + while (ch && ch !== '\n') ch = src[offset += 1]; + + return offset; + } + + static endOfWhiteSpace(src, offset) { + let ch = src[offset]; + + while (ch === '\t' || ch === ' ') ch = src[offset += 1]; + + return offset; + } + + static startOfLine(src, offset) { + let ch = src[offset - 1]; + if (ch === '\n') return offset; + + while (ch && ch !== '\n') ch = src[offset -= 1]; + + return offset + 1; + } + /** + * End of indentation, or null if the line's indent level is not more + * than `indent` + * + * @param {string} src + * @param {number} indent + * @param {number} lineStart + * @returns {?number} + */ + + + static endOfBlockIndent(src, indent, lineStart) { + const inEnd = Node.endOfIndent(src, lineStart); + + if (inEnd > lineStart + indent) { + return inEnd; + } else { + const wsEnd = Node.endOfWhiteSpace(src, inEnd); + const ch = src[wsEnd]; + if (!ch || ch === '\n') return wsEnd; + } + + return null; + } + + static atBlank(src, offset, endAsBlank) { + const ch = src[offset]; + return ch === '\n' || ch === '\t' || ch === ' ' || endAsBlank && !ch; + } + + static nextNodeIsIndented(ch, indentDiff, indicatorAsIndent) { + if (!ch || indentDiff < 0) return false; + if (indentDiff > 0) return true; + return indicatorAsIndent && ch === '-'; + } // should be at line or string end, or at next non-whitespace char + + + static normalizeOffset(src, offset) { + const ch = src[offset]; + return !ch ? offset : ch !== '\n' && src[offset - 1] === '\n' ? offset - 1 : Node.endOfWhiteSpace(src, offset); + } // fold single newline into space, multiple newlines to N - 1 newlines + // presumes src[offset] === '\n' + + + static foldNewline(src, offset, indent) { + let inCount = 0; + let error = false; + let fold = ''; + let ch = src[offset + 1]; + + while (ch === ' ' || ch === '\t' || ch === '\n') { + switch (ch) { + case '\n': + inCount = 0; + offset += 1; + fold += '\n'; + break; + + case '\t': + if (inCount <= indent) error = true; + offset = Node.endOfWhiteSpace(src, offset + 2) - 1; + break; + + case ' ': + inCount += 1; + offset += 1; + break; + } + + ch = src[offset + 1]; + } + + if (!fold) fold = ' '; + if (ch && inCount <= indent) error = true; + return { + fold, + offset, + error + }; + } + + constructor(type, props, context) { + Object.defineProperty(this, 'context', { + value: context || null, + writable: true + }); + this.error = null; + this.range = null; + this.valueRange = null; + this.props = props || []; + this.type = type; + this.value = null; + } + + getPropValue(idx, key, skipKey) { + if (!this.context) return null; + const { + src + } = this.context; + const prop = this.props[idx]; + return prop && src[prop.start] === key ? src.slice(prop.start + (skipKey ? 1 : 0), prop.end) : null; + } + + get anchor() { + for (let i = 0; i < this.props.length; ++i) { + const anchor = this.getPropValue(i, Char.ANCHOR, true); + if (anchor != null) return anchor; + } + + return null; + } + + get comment() { + const comments = []; + + for (let i = 0; i < this.props.length; ++i) { + const comment = this.getPropValue(i, Char.COMMENT, true); + if (comment != null) comments.push(comment); + } + + return comments.length > 0 ? comments.join('\n') : null; + } + + commentHasRequiredWhitespace(start) { + const { + src + } = this.context; + if (this.header && start === this.header.end) return false; + if (!this.valueRange) return false; + const { + end + } = this.valueRange; + return start !== end || Node.atBlank(src, end - 1); + } + + get hasComment() { + if (this.context) { + const { + src + } = this.context; + + for (let i = 0; i < this.props.length; ++i) { + if (src[this.props[i].start] === Char.COMMENT) return true; + } + } + + return false; + } + + get hasProps() { + if (this.context) { + const { + src + } = this.context; + + for (let i = 0; i < this.props.length; ++i) { + if (src[this.props[i].start] !== Char.COMMENT) return true; + } + } + + return false; + } + + get includesTrailingLines() { + return false; + } + + get jsonLike() { + const jsonLikeTypes = [Type.FLOW_MAP, Type.FLOW_SEQ, Type.QUOTE_DOUBLE, Type.QUOTE_SINGLE]; + return jsonLikeTypes.indexOf(this.type) !== -1; + } + + get rangeAsLinePos() { + if (!this.range || !this.context) return undefined; + const start = getLinePos(this.range.start, this.context.root); + if (!start) return undefined; + const end = getLinePos(this.range.end, this.context.root); + return { + start, + end + }; + } + + get rawValue() { + if (!this.valueRange || !this.context) return null; + const { + start, + end + } = this.valueRange; + return this.context.src.slice(start, end); + } + + get tag() { + for (let i = 0; i < this.props.length; ++i) { + const tag = this.getPropValue(i, Char.TAG, false); + + if (tag != null) { + if (tag[1] === '<') { + return { + verbatim: tag.slice(2, -1) + }; + } else { + // eslint-disable-next-line no-unused-vars + const [_, handle, suffix] = tag.match(/^(.*!)([^!]*)$/); + return { + handle, + suffix + }; + } + } + } + + return null; + } + + get valueRangeContainsNewline() { + if (!this.valueRange || !this.context) return false; + const { + start, + end + } = this.valueRange; + const { + src + } = this.context; + + for (let i = start; i < end; ++i) { + if (src[i] === '\n') return true; + } + + return false; + } + + parseComment(start) { + const { + src + } = this.context; + + if (src[start] === Char.COMMENT) { + const end = Node.endOfLine(src, start + 1); + const commentRange = new Range(start, end); + this.props.push(commentRange); + return end; + } + + return start; + } + /** + * Populates the `origStart` and `origEnd` values of all ranges for this + * node. Extended by child classes to handle descendant nodes. + * + * @param {number[]} cr - Positions of dropped CR characters + * @param {number} offset - Starting index of `cr` from the last call + * @returns {number} - The next offset, matching the one found for `origStart` + */ + + + setOrigRanges(cr, offset) { + if (this.range) offset = this.range.setOrigRange(cr, offset); + if (this.valueRange) this.valueRange.setOrigRange(cr, offset); + this.props.forEach(prop => prop.setOrigRange(cr, offset)); + return offset; + } + + toString() { + const { + context: { + src + }, + range, + value + } = this; + if (value != null) return value; + const str = src.slice(range.start, range.end); + return Node.addStringTerminator(src, range.end, str); + } + +}; + +class YAMLError extends Error { + constructor(name, source, message) { + if (!message || !(source instanceof Node$1)) throw new Error(`Invalid arguments for new ${name}`); + super(); + this.name = name; + this.message = message; + this.source = source; + } + + makePretty() { + if (!this.source) return; + this.nodeType = this.source.type; + const cst = this.source.context && this.source.context.root; + + if (typeof this.offset === 'number') { + this.range = new Range(this.offset, this.offset + 1); + const start = cst && getLinePos(this.offset, cst); + + if (start) { + const end = { + line: start.line, + col: start.col + 1 + }; + this.linePos = { + start, + end + }; + } + + delete this.offset; + } else { + this.range = this.source.range; + this.linePos = this.source.rangeAsLinePos; + } + + if (this.linePos) { + const { + line, + col + } = this.linePos.start; + this.message += ` at line ${line}, column ${col}`; + const ctx = cst && getPrettyContext(this.linePos, cst); + if (ctx) this.message += `:\n\n${ctx}\n`; + } + + delete this.source; + } + +} +class YAMLReferenceError extends YAMLError { + constructor(source, message) { + super('YAMLReferenceError', source, message); + } + +} +class YAMLSemanticError extends YAMLError { + constructor(source, message) { + super('YAMLSemanticError', source, message); + } + +} +class YAMLSyntaxError extends YAMLError { + constructor(source, message) { + super('YAMLSyntaxError', source, message); + } + +} +class YAMLWarning extends YAMLError { + constructor(source, message) { + super('YAMLWarning', source, message); + } + +} + +function _defineProperty$1(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; +} + +let PlainValue$6 = class PlainValue extends Node$1 { + static endOfLine(src, start, inFlow) { + let ch = src[start]; + let offset = start; + + while (ch && ch !== '\n') { + if (inFlow && (ch === '[' || ch === ']' || ch === '{' || ch === '}' || ch === ',')) break; + const next = src[offset + 1]; + if (ch === ':' && (!next || next === '\n' || next === '\t' || next === ' ' || inFlow && next === ',')) break; + if ((ch === ' ' || ch === '\t') && next === '#') break; + offset += 1; + ch = next; + } + + return offset; + } + + get strValue() { + if (!this.valueRange || !this.context) return null; + let { + start, + end + } = this.valueRange; + const { + src + } = this.context; + let ch = src[end - 1]; + + while (start < end && (ch === '\n' || ch === '\t' || ch === ' ')) ch = src[--end - 1]; + + let str = ''; + + for (let i = start; i < end; ++i) { + const ch = src[i]; + + if (ch === '\n') { + const { + fold, + offset + } = Node$1.foldNewline(src, i, -1); + str += fold; + i = offset; + } else if (ch === ' ' || ch === '\t') { + // trim trailing whitespace + const wsStart = i; + let next = src[i + 1]; + + while (i < end && (next === ' ' || next === '\t')) { + i += 1; + next = src[i + 1]; + } + + if (next !== '\n') str += i > wsStart ? src.slice(wsStart, i + 1) : ch; + } else { + str += ch; + } + } + + const ch0 = src[start]; + + switch (ch0) { + case '\t': + { + const msg = 'Plain value cannot start with a tab character'; + const errors = [new YAMLSemanticError(this, msg)]; + return { + errors, + str + }; + } + + case '@': + case '`': + { + const msg = `Plain value cannot start with reserved character ${ch0}`; + const errors = [new YAMLSemanticError(this, msg)]; + return { + errors, + str + }; + } + + default: + return str; + } + } + + parseBlockValue(start) { + const { + indent, + inFlow, + src + } = this.context; + let offset = start; + let valueEnd = start; + + for (let ch = src[offset]; ch === '\n'; ch = src[offset]) { + if (Node$1.atDocumentBoundary(src, offset + 1)) break; + const end = Node$1.endOfBlockIndent(src, indent, offset + 1); + if (end === null || src[end] === '#') break; + + if (src[end] === '\n') { + offset = end; + } else { + valueEnd = PlainValue.endOfLine(src, end, inFlow); + offset = valueEnd; + } + } + + if (this.valueRange.isEmpty()) this.valueRange.start = start; + this.valueRange.end = valueEnd; + return valueEnd; + } + /** + * Parses a plain value from the source + * + * Accepted forms are: + * ``` + * #comment + * + * first line + * + * first line #comment + * + * first line + * block + * lines + * + * #comment + * block + * lines + * ``` + * where block lines are empty or have an indent level greater than `indent`. + * + * @param {ParseContext} context + * @param {number} start - Index of first character + * @returns {number} - Index of the character after this scalar, may be `\n` + */ + + + parse(context, start) { + this.context = context; + const { + inFlow, + src + } = context; + let offset = start; + const ch = src[offset]; + + if (ch && ch !== '#' && ch !== '\n') { + offset = PlainValue.endOfLine(src, start, inFlow); + } + + this.valueRange = new Range(start, offset); + offset = Node$1.endOfWhiteSpace(src, offset); + offset = this.parseComment(offset); + + if (!this.hasComment || this.valueRange.isEmpty()) { + offset = this.parseBlockValue(offset); + } + + return offset; + } + +}; + +PlainValueEc8e588e.Char = Char; +PlainValueEc8e588e.Node = Node$1; +PlainValueEc8e588e.PlainValue = PlainValue$6; +PlainValueEc8e588e.Range = Range; +PlainValueEc8e588e.Type = Type; +PlainValueEc8e588e.YAMLError = YAMLError; +PlainValueEc8e588e.YAMLReferenceError = YAMLReferenceError; +PlainValueEc8e588e.YAMLSemanticError = YAMLSemanticError; +PlainValueEc8e588e.YAMLSyntaxError = YAMLSyntaxError; +PlainValueEc8e588e.YAMLWarning = YAMLWarning; +PlainValueEc8e588e._defineProperty = _defineProperty$1; +PlainValueEc8e588e.defaultTagPrefix = defaultTagPrefix; +PlainValueEc8e588e.defaultTags = defaultTags; + +var PlainValue$5 = PlainValueEc8e588e; + +class BlankLine extends PlainValue$5.Node { + constructor() { + super(PlainValue$5.Type.BLANK_LINE); + } + /* istanbul ignore next */ + + + get includesTrailingLines() { + // This is never called from anywhere, but if it were, + // this is the value it should return. + return true; + } + /** + * Parses a blank line from the source + * + * @param {ParseContext} context + * @param {number} start - Index of first \n character + * @returns {number} - Index of the character after this + */ + + + parse(context, start) { + this.context = context; + this.range = new PlainValue$5.Range(start, start + 1); + return start + 1; + } + +} + +class CollectionItem extends PlainValue$5.Node { + constructor(type, props) { + super(type, props); + this.node = null; + } + + get includesTrailingLines() { + return !!this.node && this.node.includesTrailingLines; + } + /** + * @param {ParseContext} context + * @param {number} start - Index of first character + * @returns {number} - Index of the character after this + */ + + + parse(context, start) { + this.context = context; + const { + parseNode, + src + } = context; + let { + atLineStart, + lineStart + } = context; + if (!atLineStart && this.type === PlainValue$5.Type.SEQ_ITEM) this.error = new PlainValue$5.YAMLSemanticError(this, 'Sequence items must not have preceding content on the same line'); + const indent = atLineStart ? start - lineStart : context.indent; + let offset = PlainValue$5.Node.endOfWhiteSpace(src, start + 1); + let ch = src[offset]; + const inlineComment = ch === '#'; + const comments = []; + let blankLine = null; + + while (ch === '\n' || ch === '#') { + if (ch === '#') { + const end = PlainValue$5.Node.endOfLine(src, offset + 1); + comments.push(new PlainValue$5.Range(offset, end)); + offset = end; + } else { + atLineStart = true; + lineStart = offset + 1; + const wsEnd = PlainValue$5.Node.endOfWhiteSpace(src, lineStart); + + if (src[wsEnd] === '\n' && comments.length === 0) { + blankLine = new BlankLine(); + lineStart = blankLine.parse({ + src + }, lineStart); + } + + offset = PlainValue$5.Node.endOfIndent(src, lineStart); + } + + ch = src[offset]; + } + + if (PlainValue$5.Node.nextNodeIsIndented(ch, offset - (lineStart + indent), this.type !== PlainValue$5.Type.SEQ_ITEM)) { + this.node = parseNode({ + atLineStart, + inCollection: false, + indent, + lineStart, + parent: this + }, offset); + } else if (ch && lineStart > start + 1) { + offset = lineStart - 1; + } + + if (this.node) { + if (blankLine) { + // Only blank lines preceding non-empty nodes are captured. Note that + // this means that collection item range start indices do not always + // increase monotonically. -- eemeli/yaml#126 + const items = context.parent.items || context.parent.contents; + if (items) items.push(blankLine); + } + + if (comments.length) Array.prototype.push.apply(this.props, comments); + offset = this.node.range.end; + } else { + if (inlineComment) { + const c = comments[0]; + this.props.push(c); + offset = c.end; + } else { + offset = PlainValue$5.Node.endOfLine(src, start + 1); + } + } + + const end = this.node ? this.node.valueRange.end : offset; + this.valueRange = new PlainValue$5.Range(start, end); + return offset; + } + + setOrigRanges(cr, offset) { + offset = super.setOrigRanges(cr, offset); + return this.node ? this.node.setOrigRanges(cr, offset) : offset; + } + + toString() { + const { + context: { + src + }, + node, + range, + value + } = this; + if (value != null) return value; + const str = node ? src.slice(range.start, node.range.start) + String(node) : src.slice(range.start, range.end); + return PlainValue$5.Node.addStringTerminator(src, range.end, str); + } + +} + +class Comment extends PlainValue$5.Node { + constructor() { + super(PlainValue$5.Type.COMMENT); + } + /** + * Parses a comment line from the source + * + * @param {ParseContext} context + * @param {number} start - Index of first character + * @returns {number} - Index of the character after this scalar + */ + + + parse(context, start) { + this.context = context; + const offset = this.parseComment(start); + this.range = new PlainValue$5.Range(start, offset); + return offset; + } + +} + +function grabCollectionEndComments(node) { + let cnode = node; + + while (cnode instanceof CollectionItem) cnode = cnode.node; + + if (!(cnode instanceof Collection$1)) return null; + const len = cnode.items.length; + let ci = -1; + + for (let i = len - 1; i >= 0; --i) { + const n = cnode.items[i]; + + if (n.type === PlainValue$5.Type.COMMENT) { + // Keep sufficiently indented comments with preceding node + const { + indent, + lineStart + } = n.context; + if (indent > 0 && n.range.start >= lineStart + indent) break; + ci = i; + } else if (n.type === PlainValue$5.Type.BLANK_LINE) ci = i;else break; + } + + if (ci === -1) return null; + const ca = cnode.items.splice(ci, len - ci); + const prevEnd = ca[0].range.start; + + while (true) { + cnode.range.end = prevEnd; + if (cnode.valueRange && cnode.valueRange.end > prevEnd) cnode.valueRange.end = prevEnd; + if (cnode === node) break; + cnode = cnode.context.parent; + } + + return ca; +} +let Collection$1 = class Collection extends PlainValue$5.Node { + static nextContentHasIndent(src, offset, indent) { + const lineStart = PlainValue$5.Node.endOfLine(src, offset) + 1; + offset = PlainValue$5.Node.endOfWhiteSpace(src, lineStart); + const ch = src[offset]; + if (!ch) return false; + if (offset >= lineStart + indent) return true; + if (ch !== '#' && ch !== '\n') return false; + return Collection.nextContentHasIndent(src, offset, indent); + } + + constructor(firstItem) { + super(firstItem.type === PlainValue$5.Type.SEQ_ITEM ? PlainValue$5.Type.SEQ : PlainValue$5.Type.MAP); + + for (let i = firstItem.props.length - 1; i >= 0; --i) { + if (firstItem.props[i].start < firstItem.context.lineStart) { + // props on previous line are assumed by the collection + this.props = firstItem.props.slice(0, i + 1); + firstItem.props = firstItem.props.slice(i + 1); + const itemRange = firstItem.props[0] || firstItem.valueRange; + firstItem.range.start = itemRange.start; + break; + } + } + + this.items = [firstItem]; + const ec = grabCollectionEndComments(firstItem); + if (ec) Array.prototype.push.apply(this.items, ec); + } + + get includesTrailingLines() { + return this.items.length > 0; + } + /** + * @param {ParseContext} context + * @param {number} start - Index of first character + * @returns {number} - Index of the character after this + */ + + + parse(context, start) { + this.context = context; + const { + parseNode, + src + } = context; // It's easier to recalculate lineStart here rather than tracking down the + // last context from which to read it -- eemeli/yaml#2 + + let lineStart = PlainValue$5.Node.startOfLine(src, start); + const firstItem = this.items[0]; // First-item context needs to be correct for later comment handling + // -- eemeli/yaml#17 + + firstItem.context.parent = this; + this.valueRange = PlainValue$5.Range.copy(firstItem.valueRange); + const indent = firstItem.range.start - firstItem.context.lineStart; + let offset = start; + offset = PlainValue$5.Node.normalizeOffset(src, offset); + let ch = src[offset]; + let atLineStart = PlainValue$5.Node.endOfWhiteSpace(src, lineStart) === offset; + let prevIncludesTrailingLines = false; + + while (ch) { + while (ch === '\n' || ch === '#') { + if (atLineStart && ch === '\n' && !prevIncludesTrailingLines) { + const blankLine = new BlankLine(); + offset = blankLine.parse({ + src + }, offset); + this.valueRange.end = offset; + + if (offset >= src.length) { + ch = null; + break; + } + + this.items.push(blankLine); + offset -= 1; // blankLine.parse() consumes terminal newline + } else if (ch === '#') { + if (offset < lineStart + indent && !Collection.nextContentHasIndent(src, offset, indent)) { + return offset; + } + + const comment = new Comment(); + offset = comment.parse({ + indent, + lineStart, + src + }, offset); + this.items.push(comment); + this.valueRange.end = offset; + + if (offset >= src.length) { + ch = null; + break; + } + } + + lineStart = offset + 1; + offset = PlainValue$5.Node.endOfIndent(src, lineStart); + + if (PlainValue$5.Node.atBlank(src, offset)) { + const wsEnd = PlainValue$5.Node.endOfWhiteSpace(src, offset); + const next = src[wsEnd]; + + if (!next || next === '\n' || next === '#') { + offset = wsEnd; + } + } + + ch = src[offset]; + atLineStart = true; + } + + if (!ch) { + break; + } + + if (offset !== lineStart + indent && (atLineStart || ch !== ':')) { + if (offset < lineStart + indent) { + if (lineStart > start) offset = lineStart; + break; + } else if (!this.error) { + const msg = 'All collection items must start at the same column'; + this.error = new PlainValue$5.YAMLSyntaxError(this, msg); + } + } + + if (firstItem.type === PlainValue$5.Type.SEQ_ITEM) { + if (ch !== '-') { + if (lineStart > start) offset = lineStart; + break; + } + } else if (ch === '-' && !this.error) { + // map key may start with -, as long as it's followed by a non-whitespace char + const next = src[offset + 1]; + + if (!next || next === '\n' || next === '\t' || next === ' ') { + const msg = 'A collection cannot be both a mapping and a sequence'; + this.error = new PlainValue$5.YAMLSyntaxError(this, msg); + } + } + + const node = parseNode({ + atLineStart, + inCollection: true, + indent, + lineStart, + parent: this + }, offset); + if (!node) return offset; // at next document start + + this.items.push(node); + this.valueRange.end = node.valueRange.end; + offset = PlainValue$5.Node.normalizeOffset(src, node.range.end); + ch = src[offset]; + atLineStart = false; + prevIncludesTrailingLines = node.includesTrailingLines; // Need to reset lineStart and atLineStart here if preceding node's range + // has advanced to check the current line's indentation level + // -- eemeli/yaml#10 & eemeli/yaml#38 + + if (ch) { + let ls = offset - 1; + let prev = src[ls]; + + while (prev === ' ' || prev === '\t') prev = src[--ls]; + + if (prev === '\n') { + lineStart = ls + 1; + atLineStart = true; + } + } + + const ec = grabCollectionEndComments(node); + if (ec) Array.prototype.push.apply(this.items, ec); + } + + return offset; + } + + setOrigRanges(cr, offset) { + offset = super.setOrigRanges(cr, offset); + this.items.forEach(node => { + offset = node.setOrigRanges(cr, offset); + }); + return offset; + } + + toString() { + const { + context: { + src + }, + items, + range, + value + } = this; + if (value != null) return value; + let str = src.slice(range.start, items[0].range.start) + String(items[0]); + + for (let i = 1; i < items.length; ++i) { + const item = items[i]; + const { + atLineStart, + indent + } = item.context; + if (atLineStart) for (let i = 0; i < indent; ++i) str += ' '; + str += String(item); + } + + return PlainValue$5.Node.addStringTerminator(src, range.end, str); + } + +}; + +class Directive extends PlainValue$5.Node { + constructor() { + super(PlainValue$5.Type.DIRECTIVE); + this.name = null; + } + + get parameters() { + const raw = this.rawValue; + return raw ? raw.trim().split(/[ \t]+/) : []; + } + + parseName(start) { + const { + src + } = this.context; + let offset = start; + let ch = src[offset]; + + while (ch && ch !== '\n' && ch !== '\t' && ch !== ' ') ch = src[offset += 1]; + + this.name = src.slice(start, offset); + return offset; + } + + parseParameters(start) { + const { + src + } = this.context; + let offset = start; + let ch = src[offset]; + + while (ch && ch !== '\n' && ch !== '#') ch = src[offset += 1]; + + this.valueRange = new PlainValue$5.Range(start, offset); + return offset; + } + + parse(context, start) { + this.context = context; + let offset = this.parseName(start + 1); + offset = this.parseParameters(offset); + offset = this.parseComment(offset); + this.range = new PlainValue$5.Range(start, offset); + return offset; + } + +} + +let Document$3 = class Document extends PlainValue$5.Node { + static startCommentOrEndBlankLine(src, start) { + const offset = PlainValue$5.Node.endOfWhiteSpace(src, start); + const ch = src[offset]; + return ch === '#' || ch === '\n' ? offset : start; + } + + constructor() { + super(PlainValue$5.Type.DOCUMENT); + this.directives = null; + this.contents = null; + this.directivesEndMarker = null; + this.documentEndMarker = null; + } + + parseDirectives(start) { + const { + src + } = this.context; + this.directives = []; + let atLineStart = true; + let hasDirectives = false; + let offset = start; + + while (!PlainValue$5.Node.atDocumentBoundary(src, offset, PlainValue$5.Char.DIRECTIVES_END)) { + offset = Document.startCommentOrEndBlankLine(src, offset); + + switch (src[offset]) { + case '\n': + if (atLineStart) { + const blankLine = new BlankLine(); + offset = blankLine.parse({ + src + }, offset); + + if (offset < src.length) { + this.directives.push(blankLine); + } + } else { + offset += 1; + atLineStart = true; + } + + break; + + case '#': + { + const comment = new Comment(); + offset = comment.parse({ + src + }, offset); + this.directives.push(comment); + atLineStart = false; + } + break; + + case '%': + { + const directive = new Directive(); + offset = directive.parse({ + parent: this, + src + }, offset); + this.directives.push(directive); + hasDirectives = true; + atLineStart = false; + } + break; + + default: + if (hasDirectives) { + this.error = new PlainValue$5.YAMLSemanticError(this, 'Missing directives-end indicator line'); + } else if (this.directives.length > 0) { + this.contents = this.directives; + this.directives = []; + } + + return offset; + } + } + + if (src[offset]) { + this.directivesEndMarker = new PlainValue$5.Range(offset, offset + 3); + return offset + 3; + } + + if (hasDirectives) { + this.error = new PlainValue$5.YAMLSemanticError(this, 'Missing directives-end indicator line'); + } else if (this.directives.length > 0) { + this.contents = this.directives; + this.directives = []; + } + + return offset; + } + + parseContents(start) { + const { + parseNode, + src + } = this.context; + if (!this.contents) this.contents = []; + let lineStart = start; + + while (src[lineStart - 1] === '-') lineStart -= 1; + + let offset = PlainValue$5.Node.endOfWhiteSpace(src, start); + let atLineStart = lineStart === start; + this.valueRange = new PlainValue$5.Range(offset); + + while (!PlainValue$5.Node.atDocumentBoundary(src, offset, PlainValue$5.Char.DOCUMENT_END)) { + switch (src[offset]) { + case '\n': + if (atLineStart) { + const blankLine = new BlankLine(); + offset = blankLine.parse({ + src + }, offset); + + if (offset < src.length) { + this.contents.push(blankLine); + } + } else { + offset += 1; + atLineStart = true; + } + + lineStart = offset; + break; + + case '#': + { + const comment = new Comment(); + offset = comment.parse({ + src + }, offset); + this.contents.push(comment); + atLineStart = false; + } + break; + + default: + { + const iEnd = PlainValue$5.Node.endOfIndent(src, offset); + const context = { + atLineStart, + indent: -1, + inFlow: false, + inCollection: false, + lineStart, + parent: this + }; + const node = parseNode(context, iEnd); + if (!node) return this.valueRange.end = iEnd; // at next document start + + this.contents.push(node); + offset = node.range.end; + atLineStart = false; + const ec = grabCollectionEndComments(node); + if (ec) Array.prototype.push.apply(this.contents, ec); + } + } + + offset = Document.startCommentOrEndBlankLine(src, offset); + } + + this.valueRange.end = offset; + + if (src[offset]) { + this.documentEndMarker = new PlainValue$5.Range(offset, offset + 3); + offset += 3; + + if (src[offset]) { + offset = PlainValue$5.Node.endOfWhiteSpace(src, offset); + + if (src[offset] === '#') { + const comment = new Comment(); + offset = comment.parse({ + src + }, offset); + this.contents.push(comment); + } + + switch (src[offset]) { + case '\n': + offset += 1; + break; + + case undefined: + break; + + default: + this.error = new PlainValue$5.YAMLSyntaxError(this, 'Document end marker line cannot have a non-comment suffix'); + } + } + } + + return offset; + } + /** + * @param {ParseContext} context + * @param {number} start - Index of first character + * @returns {number} - Index of the character after this + */ + + + parse(context, start) { + context.root = this; + this.context = context; + const { + src + } = context; + let offset = src.charCodeAt(start) === 0xfeff ? start + 1 : start; // skip BOM + + offset = this.parseDirectives(offset); + offset = this.parseContents(offset); + return offset; + } + + setOrigRanges(cr, offset) { + offset = super.setOrigRanges(cr, offset); + this.directives.forEach(node => { + offset = node.setOrigRanges(cr, offset); + }); + if (this.directivesEndMarker) offset = this.directivesEndMarker.setOrigRange(cr, offset); + this.contents.forEach(node => { + offset = node.setOrigRanges(cr, offset); + }); + if (this.documentEndMarker) offset = this.documentEndMarker.setOrigRange(cr, offset); + return offset; + } + + toString() { + const { + contents, + directives, + value + } = this; + if (value != null) return value; + let str = directives.join(''); + + if (contents.length > 0) { + if (directives.length > 0 || contents[0].type === PlainValue$5.Type.COMMENT) str += '---\n'; + str += contents.join(''); + } + + if (str[str.length - 1] !== '\n') str += '\n'; + return str; + } + +}; + +let Alias$1 = class Alias extends PlainValue$5.Node { + /** + * Parses an *alias from the source + * + * @param {ParseContext} context + * @param {number} start - Index of first character + * @returns {number} - Index of the character after this scalar + */ + parse(context, start) { + this.context = context; + const { + src + } = context; + let offset = PlainValue$5.Node.endOfIdentifier(src, start + 1); + this.valueRange = new PlainValue$5.Range(start + 1, offset); + offset = PlainValue$5.Node.endOfWhiteSpace(src, offset); + offset = this.parseComment(offset); + return offset; + } + +}; + +const Chomp = { + CLIP: 'CLIP', + KEEP: 'KEEP', + STRIP: 'STRIP' +}; +class BlockValue extends PlainValue$5.Node { + constructor(type, props) { + super(type, props); + this.blockIndent = null; + this.chomping = Chomp.CLIP; + this.header = null; + } + + get includesTrailingLines() { + return this.chomping === Chomp.KEEP; + } + + get strValue() { + if (!this.valueRange || !this.context) return null; + let { + start, + end + } = this.valueRange; + const { + indent, + src + } = this.context; + if (this.valueRange.isEmpty()) return ''; + let lastNewLine = null; + let ch = src[end - 1]; + + while (ch === '\n' || ch === '\t' || ch === ' ') { + end -= 1; + + if (end <= start) { + if (this.chomping === Chomp.KEEP) break;else return ''; // probably never happens + } + + if (ch === '\n') lastNewLine = end; + ch = src[end - 1]; + } + + let keepStart = end + 1; + + if (lastNewLine) { + if (this.chomping === Chomp.KEEP) { + keepStart = lastNewLine; + end = this.valueRange.end; + } else { + end = lastNewLine; + } + } + + const bi = indent + this.blockIndent; + const folded = this.type === PlainValue$5.Type.BLOCK_FOLDED; + let atStart = true; + let str = ''; + let sep = ''; + let prevMoreIndented = false; + + for (let i = start; i < end; ++i) { + for (let j = 0; j < bi; ++j) { + if (src[i] !== ' ') break; + i += 1; + } + + const ch = src[i]; + + if (ch === '\n') { + if (sep === '\n') str += '\n';else sep = '\n'; + } else { + const lineEnd = PlainValue$5.Node.endOfLine(src, i); + const line = src.slice(i, lineEnd); + i = lineEnd; + + if (folded && (ch === ' ' || ch === '\t') && i < keepStart) { + if (sep === ' ') sep = '\n';else if (!prevMoreIndented && !atStart && sep === '\n') sep = '\n\n'; + str += sep + line; //+ ((lineEnd < end && src[lineEnd]) || '') + + sep = lineEnd < end && src[lineEnd] || ''; + prevMoreIndented = true; + } else { + str += sep + line; + sep = folded && i < keepStart ? ' ' : '\n'; + prevMoreIndented = false; + } + + if (atStart && line !== '') atStart = false; + } + } + + return this.chomping === Chomp.STRIP ? str : str + '\n'; + } + + parseBlockHeader(start) { + const { + src + } = this.context; + let offset = start + 1; + let bi = ''; + + while (true) { + const ch = src[offset]; + + switch (ch) { + case '-': + this.chomping = Chomp.STRIP; + break; + + case '+': + this.chomping = Chomp.KEEP; + break; + + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + bi += ch; + break; + + default: + this.blockIndent = Number(bi) || null; + this.header = new PlainValue$5.Range(start, offset); + return offset; + } + + offset += 1; + } + } + + parseBlockValue(start) { + const { + indent, + src + } = this.context; + const explicit = !!this.blockIndent; + let offset = start; + let valueEnd = start; + let minBlockIndent = 1; + + for (let ch = src[offset]; ch === '\n'; ch = src[offset]) { + offset += 1; + if (PlainValue$5.Node.atDocumentBoundary(src, offset)) break; + const end = PlainValue$5.Node.endOfBlockIndent(src, indent, offset); // should not include tab? + + if (end === null) break; + const ch = src[end]; + const lineIndent = end - (offset + indent); + + if (!this.blockIndent) { + // no explicit block indent, none yet detected + if (src[end] !== '\n') { + // first line with non-whitespace content + if (lineIndent < minBlockIndent) { + const msg = 'Block scalars with more-indented leading empty lines must use an explicit indentation indicator'; + this.error = new PlainValue$5.YAMLSemanticError(this, msg); + } + + this.blockIndent = lineIndent; + } else if (lineIndent > minBlockIndent) { + // empty line with more whitespace + minBlockIndent = lineIndent; + } + } else if (ch && ch !== '\n' && lineIndent < this.blockIndent) { + if (src[end] === '#') break; + + if (!this.error) { + const src = explicit ? 'explicit indentation indicator' : 'first line'; + const msg = `Block scalars must not be less indented than their ${src}`; + this.error = new PlainValue$5.YAMLSemanticError(this, msg); + } + } + + if (src[end] === '\n') { + offset = end; + } else { + offset = valueEnd = PlainValue$5.Node.endOfLine(src, end); + } + } + + if (this.chomping !== Chomp.KEEP) { + offset = src[valueEnd] ? valueEnd + 1 : valueEnd; + } + + this.valueRange = new PlainValue$5.Range(start + 1, offset); + return offset; + } + /** + * Parses a block value from the source + * + * Accepted forms are: + * ``` + * BS + * block + * lines + * + * BS #comment + * block + * lines + * ``` + * where the block style BS matches the regexp `[|>][-+1-9]*` and block lines + * are empty or have an indent level greater than `indent`. + * + * @param {ParseContext} context + * @param {number} start - Index of first character + * @returns {number} - Index of the character after this block + */ + + + parse(context, start) { + this.context = context; + const { + src + } = context; + let offset = this.parseBlockHeader(start); + offset = PlainValue$5.Node.endOfWhiteSpace(src, offset); + offset = this.parseComment(offset); + offset = this.parseBlockValue(offset); + return offset; + } + + setOrigRanges(cr, offset) { + offset = super.setOrigRanges(cr, offset); + return this.header ? this.header.setOrigRange(cr, offset) : offset; + } + +} + +class FlowCollection extends PlainValue$5.Node { + constructor(type, props) { + super(type, props); + this.items = null; + } + + prevNodeIsJsonLike(idx = this.items.length) { + const node = this.items[idx - 1]; + return !!node && (node.jsonLike || node.type === PlainValue$5.Type.COMMENT && this.prevNodeIsJsonLike(idx - 1)); + } + /** + * @param {ParseContext} context + * @param {number} start - Index of first character + * @returns {number} - Index of the character after this + */ + + + parse(context, start) { + this.context = context; + const { + parseNode, + src + } = context; + let { + indent, + lineStart + } = context; + let char = src[start]; // { or [ + + this.items = [{ + char, + offset: start + }]; + let offset = PlainValue$5.Node.endOfWhiteSpace(src, start + 1); + char = src[offset]; + + while (char && char !== ']' && char !== '}') { + switch (char) { + case '\n': + { + lineStart = offset + 1; + const wsEnd = PlainValue$5.Node.endOfWhiteSpace(src, lineStart); + + if (src[wsEnd] === '\n') { + const blankLine = new BlankLine(); + lineStart = blankLine.parse({ + src + }, lineStart); + this.items.push(blankLine); + } + + offset = PlainValue$5.Node.endOfIndent(src, lineStart); + + if (offset <= lineStart + indent) { + char = src[offset]; + + if (offset < lineStart + indent || char !== ']' && char !== '}') { + const msg = 'Insufficient indentation in flow collection'; + this.error = new PlainValue$5.YAMLSemanticError(this, msg); + } + } + } + break; + + case ',': + { + this.items.push({ + char, + offset + }); + offset += 1; + } + break; + + case '#': + { + const comment = new Comment(); + offset = comment.parse({ + src + }, offset); + this.items.push(comment); + } + break; + + case '?': + case ':': + { + const next = src[offset + 1]; + + if (next === '\n' || next === '\t' || next === ' ' || next === ',' || // in-flow : after JSON-like key does not need to be followed by whitespace + char === ':' && this.prevNodeIsJsonLike()) { + this.items.push({ + char, + offset + }); + offset += 1; + break; + } + } + // fallthrough + + default: + { + const node = parseNode({ + atLineStart: false, + inCollection: false, + inFlow: true, + indent: -1, + lineStart, + parent: this + }, offset); + + if (!node) { + // at next document start + this.valueRange = new PlainValue$5.Range(start, offset); + return offset; + } + + this.items.push(node); + offset = PlainValue$5.Node.normalizeOffset(src, node.range.end); + } + } + + offset = PlainValue$5.Node.endOfWhiteSpace(src, offset); + char = src[offset]; + } + + this.valueRange = new PlainValue$5.Range(start, offset + 1); + + if (char) { + this.items.push({ + char, + offset + }); + offset = PlainValue$5.Node.endOfWhiteSpace(src, offset + 1); + offset = this.parseComment(offset); + } + + return offset; + } + + setOrigRanges(cr, offset) { + offset = super.setOrigRanges(cr, offset); + this.items.forEach(node => { + if (node instanceof PlainValue$5.Node) { + offset = node.setOrigRanges(cr, offset); + } else if (cr.length === 0) { + node.origOffset = node.offset; + } else { + let i = offset; + + while (i < cr.length) { + if (cr[i] > node.offset) break;else ++i; + } + + node.origOffset = node.offset + i; + offset = i; + } + }); + return offset; + } + + toString() { + const { + context: { + src + }, + items, + range, + value + } = this; + if (value != null) return value; + const nodes = items.filter(item => item instanceof PlainValue$5.Node); + let str = ''; + let prevEnd = range.start; + nodes.forEach(node => { + const prefix = src.slice(prevEnd, node.range.start); + prevEnd = node.range.end; + str += prefix + String(node); + + if (str[str.length - 1] === '\n' && src[prevEnd - 1] !== '\n' && src[prevEnd] === '\n') { + // Comment range does not include the terminal newline, but its + // stringified value does. Without this fix, newlines at comment ends + // get duplicated. + prevEnd += 1; + } + }); + str += src.slice(prevEnd, range.end); + return PlainValue$5.Node.addStringTerminator(src, range.end, str); + } + +} + +class QuoteDouble extends PlainValue$5.Node { + static endOfQuote(src, offset) { + let ch = src[offset]; + + while (ch && ch !== '"') { + offset += ch === '\\' ? 2 : 1; + ch = src[offset]; + } + + return offset + 1; + } + /** + * @returns {string | { str: string, errors: YAMLSyntaxError[] }} + */ + + + get strValue() { + if (!this.valueRange || !this.context) return null; + const errors = []; + const { + start, + end + } = this.valueRange; + const { + indent, + src + } = this.context; + if (src[end - 1] !== '"') errors.push(new PlainValue$5.YAMLSyntaxError(this, 'Missing closing "quote')); // Using String#replace is too painful with escaped newlines preceded by + // escaped backslashes; also, this should be faster. + + let str = ''; + + for (let i = start + 1; i < end - 1; ++i) { + const ch = src[i]; + + if (ch === '\n') { + if (PlainValue$5.Node.atDocumentBoundary(src, i + 1)) errors.push(new PlainValue$5.YAMLSemanticError(this, 'Document boundary indicators are not allowed within string values')); + const { + fold, + offset, + error + } = PlainValue$5.Node.foldNewline(src, i, indent); + str += fold; + i = offset; + if (error) errors.push(new PlainValue$5.YAMLSemanticError(this, 'Multi-line double-quoted string needs to be sufficiently indented')); + } else if (ch === '\\') { + i += 1; + + switch (src[i]) { + case '0': + str += '\0'; + break; + // null character + + case 'a': + str += '\x07'; + break; + // bell character + + case 'b': + str += '\b'; + break; + // backspace + + case 'e': + str += '\x1b'; + break; + // escape character + + case 'f': + str += '\f'; + break; + // form feed + + case 'n': + str += '\n'; + break; + // line feed + + case 'r': + str += '\r'; + break; + // carriage return + + case 't': + str += '\t'; + break; + // horizontal tab + + case 'v': + str += '\v'; + break; + // vertical tab + + case 'N': + str += '\u0085'; + break; + // Unicode next line + + case '_': + str += '\u00a0'; + break; + // Unicode non-breaking space + + case 'L': + str += '\u2028'; + break; + // Unicode line separator + + case 'P': + str += '\u2029'; + break; + // Unicode paragraph separator + + case ' ': + str += ' '; + break; + + case '"': + str += '"'; + break; + + case '/': + str += '/'; + break; + + case '\\': + str += '\\'; + break; + + case '\t': + str += '\t'; + break; + + case 'x': + str += this.parseCharCode(i + 1, 2, errors); + i += 2; + break; + + case 'u': + str += this.parseCharCode(i + 1, 4, errors); + i += 4; + break; + + case 'U': + str += this.parseCharCode(i + 1, 8, errors); + i += 8; + break; + + case '\n': + // skip escaped newlines, but still trim the following line + while (src[i + 1] === ' ' || src[i + 1] === '\t') i += 1; + + break; + + default: + errors.push(new PlainValue$5.YAMLSyntaxError(this, `Invalid escape sequence ${src.substr(i - 1, 2)}`)); + str += '\\' + src[i]; + } + } else if (ch === ' ' || ch === '\t') { + // trim trailing whitespace + const wsStart = i; + let next = src[i + 1]; + + while (next === ' ' || next === '\t') { + i += 1; + next = src[i + 1]; + } + + if (next !== '\n') str += i > wsStart ? src.slice(wsStart, i + 1) : ch; + } else { + str += ch; + } + } + + return errors.length > 0 ? { + errors, + str + } : str; + } + + parseCharCode(offset, length, errors) { + const { + src + } = this.context; + const cc = src.substr(offset, length); + const ok = cc.length === length && /^[0-9a-fA-F]+$/.test(cc); + const code = ok ? parseInt(cc, 16) : NaN; + + if (isNaN(code)) { + errors.push(new PlainValue$5.YAMLSyntaxError(this, `Invalid escape sequence ${src.substr(offset - 2, length + 2)}`)); + return src.substr(offset - 2, length + 2); + } + + return String.fromCodePoint(code); + } + /** + * Parses a "double quoted" value from the source + * + * @param {ParseContext} context + * @param {number} start - Index of first character + * @returns {number} - Index of the character after this scalar + */ + + + parse(context, start) { + this.context = context; + const { + src + } = context; + let offset = QuoteDouble.endOfQuote(src, start + 1); + this.valueRange = new PlainValue$5.Range(start, offset); + offset = PlainValue$5.Node.endOfWhiteSpace(src, offset); + offset = this.parseComment(offset); + return offset; + } + +} + +class QuoteSingle extends PlainValue$5.Node { + static endOfQuote(src, offset) { + let ch = src[offset]; + + while (ch) { + if (ch === "'") { + if (src[offset + 1] !== "'") break; + ch = src[offset += 2]; + } else { + ch = src[offset += 1]; + } + } + + return offset + 1; + } + /** + * @returns {string | { str: string, errors: YAMLSyntaxError[] }} + */ + + + get strValue() { + if (!this.valueRange || !this.context) return null; + const errors = []; + const { + start, + end + } = this.valueRange; + const { + indent, + src + } = this.context; + if (src[end - 1] !== "'") errors.push(new PlainValue$5.YAMLSyntaxError(this, "Missing closing 'quote")); + let str = ''; + + for (let i = start + 1; i < end - 1; ++i) { + const ch = src[i]; + + if (ch === '\n') { + if (PlainValue$5.Node.atDocumentBoundary(src, i + 1)) errors.push(new PlainValue$5.YAMLSemanticError(this, 'Document boundary indicators are not allowed within string values')); + const { + fold, + offset, + error + } = PlainValue$5.Node.foldNewline(src, i, indent); + str += fold; + i = offset; + if (error) errors.push(new PlainValue$5.YAMLSemanticError(this, 'Multi-line single-quoted string needs to be sufficiently indented')); + } else if (ch === "'") { + str += ch; + i += 1; + if (src[i] !== "'") errors.push(new PlainValue$5.YAMLSyntaxError(this, 'Unescaped single quote? This should not happen.')); + } else if (ch === ' ' || ch === '\t') { + // trim trailing whitespace + const wsStart = i; + let next = src[i + 1]; + + while (next === ' ' || next === '\t') { + i += 1; + next = src[i + 1]; + } + + if (next !== '\n') str += i > wsStart ? src.slice(wsStart, i + 1) : ch; + } else { + str += ch; + } + } + + return errors.length > 0 ? { + errors, + str + } : str; + } + /** + * Parses a 'single quoted' value from the source + * + * @param {ParseContext} context + * @param {number} start - Index of first character + * @returns {number} - Index of the character after this scalar + */ + + + parse(context, start) { + this.context = context; + const { + src + } = context; + let offset = QuoteSingle.endOfQuote(src, start + 1); + this.valueRange = new PlainValue$5.Range(start, offset); + offset = PlainValue$5.Node.endOfWhiteSpace(src, offset); + offset = this.parseComment(offset); + return offset; + } + +} + +function createNewNode(type, props) { + switch (type) { + case PlainValue$5.Type.ALIAS: + return new Alias$1(type, props); + + case PlainValue$5.Type.BLOCK_FOLDED: + case PlainValue$5.Type.BLOCK_LITERAL: + return new BlockValue(type, props); + + case PlainValue$5.Type.FLOW_MAP: + case PlainValue$5.Type.FLOW_SEQ: + return new FlowCollection(type, props); + + case PlainValue$5.Type.MAP_KEY: + case PlainValue$5.Type.MAP_VALUE: + case PlainValue$5.Type.SEQ_ITEM: + return new CollectionItem(type, props); + + case PlainValue$5.Type.COMMENT: + case PlainValue$5.Type.PLAIN: + return new PlainValue$5.PlainValue(type, props); + + case PlainValue$5.Type.QUOTE_DOUBLE: + return new QuoteDouble(type, props); + + case PlainValue$5.Type.QUOTE_SINGLE: + return new QuoteSingle(type, props); + + /* istanbul ignore next */ + + default: + return null; + // should never happen + } +} +/** + * @param {boolean} atLineStart - Node starts at beginning of line + * @param {boolean} inFlow - true if currently in a flow context + * @param {boolean} inCollection - true if currently in a collection context + * @param {number} indent - Current level of indentation + * @param {number} lineStart - Start of the current line + * @param {Node} parent - The parent of the node + * @param {string} src - Source of the YAML document + */ + + +class ParseContext { + static parseType(src, offset, inFlow) { + switch (src[offset]) { + case '*': + return PlainValue$5.Type.ALIAS; + + case '>': + return PlainValue$5.Type.BLOCK_FOLDED; + + case '|': + return PlainValue$5.Type.BLOCK_LITERAL; + + case '{': + return PlainValue$5.Type.FLOW_MAP; + + case '[': + return PlainValue$5.Type.FLOW_SEQ; + + case '?': + return !inFlow && PlainValue$5.Node.atBlank(src, offset + 1, true) ? PlainValue$5.Type.MAP_KEY : PlainValue$5.Type.PLAIN; + + case ':': + return !inFlow && PlainValue$5.Node.atBlank(src, offset + 1, true) ? PlainValue$5.Type.MAP_VALUE : PlainValue$5.Type.PLAIN; + + case '-': + return !inFlow && PlainValue$5.Node.atBlank(src, offset + 1, true) ? PlainValue$5.Type.SEQ_ITEM : PlainValue$5.Type.PLAIN; + + case '"': + return PlainValue$5.Type.QUOTE_DOUBLE; + + case "'": + return PlainValue$5.Type.QUOTE_SINGLE; + + default: + return PlainValue$5.Type.PLAIN; + } + } + + constructor(orig = {}, { + atLineStart, + inCollection, + inFlow, + indent, + lineStart, + parent + } = {}) { + PlainValue$5._defineProperty(this, "parseNode", (overlay, start) => { + if (PlainValue$5.Node.atDocumentBoundary(this.src, start)) return null; + const context = new ParseContext(this, overlay); + const { + props, + type, + valueStart + } = context.parseProps(start); + const node = createNewNode(type, props); + let offset = node.parse(context, valueStart); + node.range = new PlainValue$5.Range(start, offset); + /* istanbul ignore if */ + + if (offset <= start) { + // This should never happen, but if it does, let's make sure to at least + // step one character forward to avoid a busy loop. + node.error = new Error(`Node#parse consumed no characters`); + node.error.parseEnd = offset; + node.error.source = node; + node.range.end = start + 1; + } + + if (context.nodeStartsCollection(node)) { + if (!node.error && !context.atLineStart && context.parent.type === PlainValue$5.Type.DOCUMENT) { + node.error = new PlainValue$5.YAMLSyntaxError(node, 'Block collection must not have preceding content here (e.g. directives-end indicator)'); + } + + const collection = new Collection$1(node); + offset = collection.parse(new ParseContext(context), offset); + collection.range = new PlainValue$5.Range(start, offset); + return collection; + } + + return node; + }); + + this.atLineStart = atLineStart != null ? atLineStart : orig.atLineStart || false; + this.inCollection = inCollection != null ? inCollection : orig.inCollection || false; + this.inFlow = inFlow != null ? inFlow : orig.inFlow || false; + this.indent = indent != null ? indent : orig.indent; + this.lineStart = lineStart != null ? lineStart : orig.lineStart; + this.parent = parent != null ? parent : orig.parent || {}; + this.root = orig.root; + this.src = orig.src; + } + + nodeStartsCollection(node) { + const { + inCollection, + inFlow, + src + } = this; + if (inCollection || inFlow) return false; + if (node instanceof CollectionItem) return true; // check for implicit key + + let offset = node.range.end; + if (src[offset] === '\n' || src[offset - 1] === '\n') return false; + offset = PlainValue$5.Node.endOfWhiteSpace(src, offset); + return src[offset] === ':'; + } // Anchor and tag are before type, which determines the node implementation + // class; hence this intermediate step. + + + parseProps(offset) { + const { + inFlow, + parent, + src + } = this; + const props = []; + let lineHasProps = false; + offset = this.atLineStart ? PlainValue$5.Node.endOfIndent(src, offset) : PlainValue$5.Node.endOfWhiteSpace(src, offset); + let ch = src[offset]; + + while (ch === PlainValue$5.Char.ANCHOR || ch === PlainValue$5.Char.COMMENT || ch === PlainValue$5.Char.TAG || ch === '\n') { + if (ch === '\n') { + let inEnd = offset; + let lineStart; + + do { + lineStart = inEnd + 1; + inEnd = PlainValue$5.Node.endOfIndent(src, lineStart); + } while (src[inEnd] === '\n'); + + const indentDiff = inEnd - (lineStart + this.indent); + const noIndicatorAsIndent = parent.type === PlainValue$5.Type.SEQ_ITEM && parent.context.atLineStart; + if (src[inEnd] !== '#' && !PlainValue$5.Node.nextNodeIsIndented(src[inEnd], indentDiff, !noIndicatorAsIndent)) break; + this.atLineStart = true; + this.lineStart = lineStart; + lineHasProps = false; + offset = inEnd; + } else if (ch === PlainValue$5.Char.COMMENT) { + const end = PlainValue$5.Node.endOfLine(src, offset + 1); + props.push(new PlainValue$5.Range(offset, end)); + offset = end; + } else { + let end = PlainValue$5.Node.endOfIdentifier(src, offset + 1); + + if (ch === PlainValue$5.Char.TAG && src[end] === ',' && /^[a-zA-Z0-9-]+\.[a-zA-Z0-9-]+,\d\d\d\d(-\d\d){0,2}\/\S/.test(src.slice(offset + 1, end + 13))) { + // Let's presume we're dealing with a YAML 1.0 domain tag here, rather + // than an empty but 'foo.bar' private-tagged node in a flow collection + // followed without whitespace by a plain string starting with a year + // or date divided by something. + end = PlainValue$5.Node.endOfIdentifier(src, end + 5); + } + + props.push(new PlainValue$5.Range(offset, end)); + lineHasProps = true; + offset = PlainValue$5.Node.endOfWhiteSpace(src, end); + } + + ch = src[offset]; + } // '- &a : b' has an anchor on an empty node + + + if (lineHasProps && ch === ':' && PlainValue$5.Node.atBlank(src, offset + 1, true)) offset -= 1; + const type = ParseContext.parseType(src, offset, inFlow); + return { + props, + type, + valueStart: offset + }; + } + /** + * Parses a node from the source + * @param {ParseContext} overlay + * @param {number} start - Index of first non-whitespace character for the node + * @returns {?Node} - null if at a document boundary + */ + + +} + +// Published as 'yaml/parse-cst' +function parse$3(src) { + const cr = []; + + if (src.indexOf('\r') !== -1) { + src = src.replace(/\r\n?/g, (match, offset) => { + if (match.length > 1) cr.push(offset); + return '\n'; + }); + } + + const documents = []; + let offset = 0; + + do { + const doc = new Document$3(); + const context = new ParseContext({ + src + }); + offset = doc.parse(context, offset); + documents.push(doc); + } while (offset < src.length); + + documents.setOrigRanges = () => { + if (cr.length === 0) return false; + + for (let i = 1; i < cr.length; ++i) cr[i] -= i; + + let crOffset = 0; + + for (let i = 0; i < documents.length; ++i) { + crOffset = documents[i].setOrigRanges(cr, crOffset); + } + + cr.splice(0, cr.length); + return true; + }; + + documents.toString = () => documents.join('...\n'); + + return documents; +} + +parseCst$1.parse = parse$3; + +var Document9b4560a1 = {}; + +var resolveSeqD03cb037 = {}; + +var PlainValue$4 = PlainValueEc8e588e; + +function addCommentBefore(str, indent, comment) { + if (!comment) return str; + const cc = comment.replace(/[\s\S]^/gm, `$&${indent}#`); + return `#${cc}\n${indent}${str}`; +} +function addComment(str, indent, comment) { + return !comment ? str : comment.indexOf('\n') === -1 ? `${str} #${comment}` : `${str}\n` + comment.replace(/^/gm, `${indent || ''}#`); +} + +class Node {} + +function toJSON(value, arg, ctx) { + if (Array.isArray(value)) return value.map((v, i) => toJSON(v, String(i), ctx)); + + if (value && typeof value.toJSON === 'function') { + const anchor = ctx && ctx.anchors && ctx.anchors.get(value); + if (anchor) ctx.onCreate = res => { + anchor.res = res; + delete ctx.onCreate; + }; + const res = value.toJSON(arg, ctx); + if (anchor && ctx.onCreate) ctx.onCreate(res); + return res; + } + + if ((!ctx || !ctx.keep) && typeof value === 'bigint') return Number(value); + return value; +} + +class Scalar extends Node { + constructor(value) { + super(); + this.value = value; + } + + toJSON(arg, ctx) { + return ctx && ctx.keep ? this.value : toJSON(this.value, arg, ctx); + } + + toString() { + return String(this.value); + } + +} + +function collectionFromPath(schema, path, value) { + let v = value; + + for (let i = path.length - 1; i >= 0; --i) { + const k = path[i]; + + if (Number.isInteger(k) && k >= 0) { + const a = []; + a[k] = v; + v = a; + } else { + const o = {}; + Object.defineProperty(o, k, { + value: v, + writable: true, + enumerable: true, + configurable: true + }); + v = o; + } + } + + return schema.createNode(v, false); +} // null, undefined, or an empty non-string iterable (e.g. []) + + +const isEmptyPath = path => path == null || typeof path === 'object' && path[Symbol.iterator]().next().done; +class Collection extends Node { + constructor(schema) { + super(); + + PlainValue$4._defineProperty(this, "items", []); + + this.schema = schema; + } + + addIn(path, value) { + if (isEmptyPath(path)) this.add(value);else { + const [key, ...rest] = path; + const node = this.get(key, true); + if (node instanceof Collection) node.addIn(rest, value);else if (node === undefined && this.schema) this.set(key, collectionFromPath(this.schema, rest, value));else throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + } + + deleteIn([key, ...rest]) { + if (rest.length === 0) return this.delete(key); + const node = this.get(key, true); + if (node instanceof Collection) return node.deleteIn(rest);else throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + + getIn([key, ...rest], keepScalar) { + const node = this.get(key, true); + if (rest.length === 0) return !keepScalar && node instanceof Scalar ? node.value : node;else return node instanceof Collection ? node.getIn(rest, keepScalar) : undefined; + } + + hasAllNullValues() { + return this.items.every(node => { + if (!node || node.type !== 'PAIR') return false; + const n = node.value; + return n == null || n instanceof Scalar && n.value == null && !n.commentBefore && !n.comment && !n.tag; + }); + } + + hasIn([key, ...rest]) { + if (rest.length === 0) return this.has(key); + const node = this.get(key, true); + return node instanceof Collection ? node.hasIn(rest) : false; + } + + setIn([key, ...rest], value) { + if (rest.length === 0) { + this.set(key, value); + } else { + const node = this.get(key, true); + if (node instanceof Collection) node.setIn(rest, value);else if (node === undefined && this.schema) this.set(key, collectionFromPath(this.schema, rest, value));else throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + } // overridden in implementations + + /* istanbul ignore next */ + + + toJSON() { + return null; + } + + toString(ctx, { + blockItem, + flowChars, + isMap, + itemIndent + }, onComment, onChompKeep) { + const { + indent, + indentStep, + stringify + } = ctx; + const inFlow = this.type === PlainValue$4.Type.FLOW_MAP || this.type === PlainValue$4.Type.FLOW_SEQ || ctx.inFlow; + if (inFlow) itemIndent += indentStep; + const allNullValues = isMap && this.hasAllNullValues(); + ctx = Object.assign({}, ctx, { + allNullValues, + indent: itemIndent, + inFlow, + type: null + }); + let chompKeep = false; + let hasItemWithNewLine = false; + const nodes = this.items.reduce((nodes, item, i) => { + let comment; + + if (item) { + if (!chompKeep && item.spaceBefore) nodes.push({ + type: 'comment', + str: '' + }); + if (item.commentBefore) item.commentBefore.match(/^.*$/gm).forEach(line => { + nodes.push({ + type: 'comment', + str: `#${line}` + }); + }); + if (item.comment) comment = item.comment; + if (inFlow && (!chompKeep && item.spaceBefore || item.commentBefore || item.comment || item.key && (item.key.commentBefore || item.key.comment) || item.value && (item.value.commentBefore || item.value.comment))) hasItemWithNewLine = true; + } + + chompKeep = false; + let str = stringify(item, ctx, () => comment = null, () => chompKeep = true); + if (inFlow && !hasItemWithNewLine && str.includes('\n')) hasItemWithNewLine = true; + if (inFlow && i < this.items.length - 1) str += ','; + str = addComment(str, itemIndent, comment); + if (chompKeep && (comment || inFlow)) chompKeep = false; + nodes.push({ + type: 'item', + str + }); + return nodes; + }, []); + let str; + + if (nodes.length === 0) { + str = flowChars.start + flowChars.end; + } else if (inFlow) { + const { + start, + end + } = flowChars; + const strings = nodes.map(n => n.str); + + if (hasItemWithNewLine || strings.reduce((sum, str) => sum + str.length + 2, 2) > Collection.maxFlowStringSingleLineLength) { + str = start; + + for (const s of strings) { + str += s ? `\n${indentStep}${indent}${s}` : '\n'; + } + + str += `\n${indent}${end}`; + } else { + str = `${start} ${strings.join(' ')} ${end}`; + } + } else { + const strings = nodes.map(blockItem); + str = strings.shift(); + + for (const s of strings) str += s ? `\n${indent}${s}` : '\n'; + } + + if (this.comment) { + str += '\n' + this.comment.replace(/^/gm, `${indent}#`); + if (onComment) onComment(); + } else if (chompKeep && onChompKeep) onChompKeep(); + + return str; + } + +} + +PlainValue$4._defineProperty(Collection, "maxFlowStringSingleLineLength", 60); + +function asItemIndex(key) { + let idx = key instanceof Scalar ? key.value : key; + if (idx && typeof idx === 'string') idx = Number(idx); + return Number.isInteger(idx) && idx >= 0 ? idx : null; +} + +class YAMLSeq extends Collection { + add(value) { + this.items.push(value); + } + + delete(key) { + const idx = asItemIndex(key); + if (typeof idx !== 'number') return false; + const del = this.items.splice(idx, 1); + return del.length > 0; + } + + get(key, keepScalar) { + const idx = asItemIndex(key); + if (typeof idx !== 'number') return undefined; + const it = this.items[idx]; + return !keepScalar && it instanceof Scalar ? it.value : it; + } + + has(key) { + const idx = asItemIndex(key); + return typeof idx === 'number' && idx < this.items.length; + } + + set(key, value) { + const idx = asItemIndex(key); + if (typeof idx !== 'number') throw new Error(`Expected a valid index, not ${key}.`); + this.items[idx] = value; + } + + toJSON(_, ctx) { + const seq = []; + if (ctx && ctx.onCreate) ctx.onCreate(seq); + let i = 0; + + for (const item of this.items) seq.push(toJSON(item, String(i++), ctx)); + + return seq; + } + + toString(ctx, onComment, onChompKeep) { + if (!ctx) return JSON.stringify(this); + return super.toString(ctx, { + blockItem: n => n.type === 'comment' ? n.str : `- ${n.str}`, + flowChars: { + start: '[', + end: ']' + }, + isMap: false, + itemIndent: (ctx.indent || '') + ' ' + }, onComment, onChompKeep); + } + +} + +const stringifyKey = (key, jsKey, ctx) => { + if (jsKey === null) return ''; + if (typeof jsKey !== 'object') return String(jsKey); + if (key instanceof Node && ctx && ctx.doc) return key.toString({ + anchors: Object.create(null), + doc: ctx.doc, + indent: '', + indentStep: ctx.indentStep, + inFlow: true, + inStringifyKey: true, + stringify: ctx.stringify + }); + return JSON.stringify(jsKey); +}; + +class Pair extends Node { + constructor(key, value = null) { + super(); + this.key = key; + this.value = value; + this.type = Pair.Type.PAIR; + } + + get commentBefore() { + return this.key instanceof Node ? this.key.commentBefore : undefined; + } + + set commentBefore(cb) { + if (this.key == null) this.key = new Scalar(null); + if (this.key instanceof Node) this.key.commentBefore = cb;else { + const msg = 'Pair.commentBefore is an alias for Pair.key.commentBefore. To set it, the key must be a Node.'; + throw new Error(msg); + } + } + + addToJSMap(ctx, map) { + const key = toJSON(this.key, '', ctx); + + if (map instanceof Map) { + const value = toJSON(this.value, key, ctx); + map.set(key, value); + } else if (map instanceof Set) { + map.add(key); + } else { + const stringKey = stringifyKey(this.key, key, ctx); + const value = toJSON(this.value, stringKey, ctx); + if (stringKey in map) Object.defineProperty(map, stringKey, { + value, + writable: true, + enumerable: true, + configurable: true + });else map[stringKey] = value; + } + + return map; + } + + toJSON(_, ctx) { + const pair = ctx && ctx.mapAsMap ? new Map() : {}; + return this.addToJSMap(ctx, pair); + } + + toString(ctx, onComment, onChompKeep) { + if (!ctx || !ctx.doc) return JSON.stringify(this); + const { + indent: indentSize, + indentSeq, + simpleKeys + } = ctx.doc.options; + let { + key, + value + } = this; + let keyComment = key instanceof Node && key.comment; + + if (simpleKeys) { + if (keyComment) { + throw new Error('With simple keys, key nodes cannot have comments'); + } + + if (key instanceof Collection) { + const msg = 'With simple keys, collection cannot be used as a key value'; + throw new Error(msg); + } + } + + let explicitKey = !simpleKeys && (!key || keyComment || (key instanceof Node ? key instanceof Collection || key.type === PlainValue$4.Type.BLOCK_FOLDED || key.type === PlainValue$4.Type.BLOCK_LITERAL : typeof key === 'object')); + const { + doc, + indent, + indentStep, + stringify + } = ctx; + ctx = Object.assign({}, ctx, { + implicitKey: !explicitKey, + indent: indent + indentStep + }); + let chompKeep = false; + let str = stringify(key, ctx, () => keyComment = null, () => chompKeep = true); + str = addComment(str, ctx.indent, keyComment); + + if (!explicitKey && str.length > 1024) { + if (simpleKeys) throw new Error('With simple keys, single line scalar must not span more than 1024 characters'); + explicitKey = true; + } + + if (ctx.allNullValues && !simpleKeys) { + if (this.comment) { + str = addComment(str, ctx.indent, this.comment); + if (onComment) onComment(); + } else if (chompKeep && !keyComment && onChompKeep) onChompKeep(); + + return ctx.inFlow && !explicitKey ? str : `? ${str}`; + } + + str = explicitKey ? `? ${str}\n${indent}:` : `${str}:`; + + if (this.comment) { + // expected (but not strictly required) to be a single-line comment + str = addComment(str, ctx.indent, this.comment); + if (onComment) onComment(); + } + + let vcb = ''; + let valueComment = null; + + if (value instanceof Node) { + if (value.spaceBefore) vcb = '\n'; + + if (value.commentBefore) { + const cs = value.commentBefore.replace(/^/gm, `${ctx.indent}#`); + vcb += `\n${cs}`; + } + + valueComment = value.comment; + } else if (value && typeof value === 'object') { + value = doc.schema.createNode(value, true); + } + + ctx.implicitKey = false; + if (!explicitKey && !this.comment && value instanceof Scalar) ctx.indentAtStart = str.length + 1; + chompKeep = false; + + if (!indentSeq && indentSize >= 2 && !ctx.inFlow && !explicitKey && value instanceof YAMLSeq && value.type !== PlainValue$4.Type.FLOW_SEQ && !value.tag && !doc.anchors.getName(value)) { + // If indentSeq === false, consider '- ' as part of indentation where possible + ctx.indent = ctx.indent.substr(2); + } + + const valueStr = stringify(value, ctx, () => valueComment = null, () => chompKeep = true); + let ws = ' '; + + if (vcb || this.comment) { + ws = `${vcb}\n${ctx.indent}`; + } else if (!explicitKey && value instanceof Collection) { + const flow = valueStr[0] === '[' || valueStr[0] === '{'; + if (!flow || valueStr.includes('\n')) ws = `\n${ctx.indent}`; + } else if (valueStr[0] === '\n') ws = ''; + + if (chompKeep && !valueComment && onChompKeep) onChompKeep(); + return addComment(str + ws + valueStr, ctx.indent, valueComment); + } + +} + +PlainValue$4._defineProperty(Pair, "Type", { + PAIR: 'PAIR', + MERGE_PAIR: 'MERGE_PAIR' +}); + +const getAliasCount = (node, anchors) => { + if (node instanceof Alias) { + const anchor = anchors.get(node.source); + return anchor.count * anchor.aliasCount; + } else if (node instanceof Collection) { + let count = 0; + + for (const item of node.items) { + const c = getAliasCount(item, anchors); + if (c > count) count = c; + } + + return count; + } else if (node instanceof Pair) { + const kc = getAliasCount(node.key, anchors); + const vc = getAliasCount(node.value, anchors); + return Math.max(kc, vc); + } + + return 1; +}; + +class Alias extends Node { + static stringify({ + range, + source + }, { + anchors, + doc, + implicitKey, + inStringifyKey + }) { + let anchor = Object.keys(anchors).find(a => anchors[a] === source); + if (!anchor && inStringifyKey) anchor = doc.anchors.getName(source) || doc.anchors.newName(); + if (anchor) return `*${anchor}${implicitKey ? ' ' : ''}`; + const msg = doc.anchors.getName(source) ? 'Alias node must be after source node' : 'Source node not found for alias node'; + throw new Error(`${msg} [${range}]`); + } + + constructor(source) { + super(); + this.source = source; + this.type = PlainValue$4.Type.ALIAS; + } + + set tag(t) { + throw new Error('Alias nodes cannot have tags'); + } + + toJSON(arg, ctx) { + if (!ctx) return toJSON(this.source, arg, ctx); + const { + anchors, + maxAliasCount + } = ctx; + const anchor = anchors.get(this.source); + /* istanbul ignore if */ + + if (!anchor || anchor.res === undefined) { + const msg = 'This should not happen: Alias anchor was not resolved?'; + if (this.cstNode) throw new PlainValue$4.YAMLReferenceError(this.cstNode, msg);else throw new ReferenceError(msg); + } + + if (maxAliasCount >= 0) { + anchor.count += 1; + if (anchor.aliasCount === 0) anchor.aliasCount = getAliasCount(this.source, anchors); + + if (anchor.count * anchor.aliasCount > maxAliasCount) { + const msg = 'Excessive alias count indicates a resource exhaustion attack'; + if (this.cstNode) throw new PlainValue$4.YAMLReferenceError(this.cstNode, msg);else throw new ReferenceError(msg); + } + } + + return anchor.res; + } // Only called when stringifying an alias mapping key while constructing + // Object output. + + + toString(ctx) { + return Alias.stringify(this, ctx); + } + +} + +PlainValue$4._defineProperty(Alias, "default", true); + +function findPair(items, key) { + const k = key instanceof Scalar ? key.value : key; + + for (const it of items) { + if (it instanceof Pair) { + if (it.key === key || it.key === k) return it; + if (it.key && it.key.value === k) return it; + } + } + + return undefined; +} +class YAMLMap extends Collection { + add(pair, overwrite) { + if (!pair) pair = new Pair(pair);else if (!(pair instanceof Pair)) pair = new Pair(pair.key || pair, pair.value); + const prev = findPair(this.items, pair.key); + const sortEntries = this.schema && this.schema.sortMapEntries; + + if (prev) { + if (overwrite) prev.value = pair.value;else throw new Error(`Key ${pair.key} already set`); + } else if (sortEntries) { + const i = this.items.findIndex(item => sortEntries(pair, item) < 0); + if (i === -1) this.items.push(pair);else this.items.splice(i, 0, pair); + } else { + this.items.push(pair); + } + } + + delete(key) { + const it = findPair(this.items, key); + if (!it) return false; + const del = this.items.splice(this.items.indexOf(it), 1); + return del.length > 0; + } + + get(key, keepScalar) { + const it = findPair(this.items, key); + const node = it && it.value; + return !keepScalar && node instanceof Scalar ? node.value : node; + } + + has(key) { + return !!findPair(this.items, key); + } + + set(key, value) { + this.add(new Pair(key, value), true); + } + /** + * @param {*} arg ignored + * @param {*} ctx Conversion context, originally set in Document#toJSON() + * @param {Class} Type If set, forces the returned collection type + * @returns {*} Instance of Type, Map, or Object + */ + + + toJSON(_, ctx, Type) { + const map = Type ? new Type() : ctx && ctx.mapAsMap ? new Map() : {}; + if (ctx && ctx.onCreate) ctx.onCreate(map); + + for (const item of this.items) item.addToJSMap(ctx, map); + + return map; + } + + toString(ctx, onComment, onChompKeep) { + if (!ctx) return JSON.stringify(this); + + for (const item of this.items) { + if (!(item instanceof Pair)) throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`); + } + + return super.toString(ctx, { + blockItem: n => n.str, + flowChars: { + start: '{', + end: '}' + }, + isMap: true, + itemIndent: ctx.indent || '' + }, onComment, onChompKeep); + } + +} + +const MERGE_KEY = '<<'; +class Merge extends Pair { + constructor(pair) { + if (pair instanceof Pair) { + let seq = pair.value; + + if (!(seq instanceof YAMLSeq)) { + seq = new YAMLSeq(); + seq.items.push(pair.value); + seq.range = pair.value.range; + } + + super(pair.key, seq); + this.range = pair.range; + } else { + super(new Scalar(MERGE_KEY), new YAMLSeq()); + } + + this.type = Pair.Type.MERGE_PAIR; + } // If the value associated with a merge key is a single mapping node, each of + // its key/value pairs is inserted into the current mapping, unless the key + // already exists in it. If the value associated with the merge key is a + // sequence, then this sequence is expected to contain mapping nodes and each + // of these nodes is merged in turn according to its order in the sequence. + // Keys in mapping nodes earlier in the sequence override keys specified in + // later mapping nodes. -- http://yaml.org/type/merge.html + + + addToJSMap(ctx, map) { + for (const { + source + } of this.value.items) { + if (!(source instanceof YAMLMap)) throw new Error('Merge sources must be maps'); + const srcMap = source.toJSON(null, ctx, Map); + + for (const [key, value] of srcMap) { + if (map instanceof Map) { + if (!map.has(key)) map.set(key, value); + } else if (map instanceof Set) { + map.add(key); + } else if (!Object.prototype.hasOwnProperty.call(map, key)) { + Object.defineProperty(map, key, { + value, + writable: true, + enumerable: true, + configurable: true + }); + } + } + } + + return map; + } + + toString(ctx, onComment) { + const seq = this.value; + if (seq.items.length > 1) return super.toString(ctx, onComment); + this.value = seq.items[0]; + const str = super.toString(ctx, onComment); + this.value = seq; + return str; + } + +} + +const binaryOptions = { + defaultType: PlainValue$4.Type.BLOCK_LITERAL, + lineWidth: 76 +}; +const boolOptions = { + trueStr: 'true', + falseStr: 'false' +}; +const intOptions = { + asBigInt: false +}; +const nullOptions = { + nullStr: 'null' +}; +const strOptions = { + defaultType: PlainValue$4.Type.PLAIN, + doubleQuoted: { + jsonEncoding: false, + minMultiLineLength: 40 + }, + fold: { + lineWidth: 80, + minContentWidth: 20 + } +}; + +function resolveScalar(str, tags, scalarFallback) { + for (const { + format, + test, + resolve + } of tags) { + if (test) { + const match = str.match(test); + + if (match) { + let res = resolve.apply(null, match); + if (!(res instanceof Scalar)) res = new Scalar(res); + if (format) res.format = format; + return res; + } + } + } + + if (scalarFallback) str = scalarFallback(str); + return new Scalar(str); +} + +const FOLD_FLOW = 'flow'; +const FOLD_BLOCK = 'block'; +const FOLD_QUOTED = 'quoted'; // presumes i+1 is at the start of a line +// returns index of last newline in more-indented block + +const consumeMoreIndentedLines = (text, i) => { + let ch = text[i + 1]; + + while (ch === ' ' || ch === '\t') { + do { + ch = text[i += 1]; + } while (ch && ch !== '\n'); + + ch = text[i + 1]; + } + + return i; +}; +/** + * Tries to keep input at up to `lineWidth` characters, splitting only on spaces + * not followed by newlines or spaces unless `mode` is `'quoted'`. Lines are + * terminated with `\n` and started with `indent`. + * + * @param {string} text + * @param {string} indent + * @param {string} [mode='flow'] `'block'` prevents more-indented lines + * from being folded; `'quoted'` allows for `\` escapes, including escaped + * newlines + * @param {Object} options + * @param {number} [options.indentAtStart] Accounts for leading contents on + * the first line, defaulting to `indent.length` + * @param {number} [options.lineWidth=80] + * @param {number} [options.minContentWidth=20] Allow highly indented lines to + * stretch the line width or indent content from the start + * @param {function} options.onFold Called once if the text is folded + * @param {function} options.onFold Called once if any line of text exceeds + * lineWidth characters + */ + + +function foldFlowLines(text, indent, mode, { + indentAtStart, + lineWidth = 80, + minContentWidth = 20, + onFold, + onOverflow +}) { + if (!lineWidth || lineWidth < 0) return text; + const endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length); + if (text.length <= endStep) return text; + const folds = []; + const escapedFolds = {}; + let end = lineWidth - indent.length; + + if (typeof indentAtStart === 'number') { + if (indentAtStart > lineWidth - Math.max(2, minContentWidth)) folds.push(0);else end = lineWidth - indentAtStart; + } + + let split = undefined; + let prev = undefined; + let overflow = false; + let i = -1; + let escStart = -1; + let escEnd = -1; + + if (mode === FOLD_BLOCK) { + i = consumeMoreIndentedLines(text, i); + if (i !== -1) end = i + endStep; + } + + for (let ch; ch = text[i += 1];) { + if (mode === FOLD_QUOTED && ch === '\\') { + escStart = i; + + switch (text[i + 1]) { + case 'x': + i += 3; + break; + + case 'u': + i += 5; + break; + + case 'U': + i += 9; + break; + + default: + i += 1; + } + + escEnd = i; + } + + if (ch === '\n') { + if (mode === FOLD_BLOCK) i = consumeMoreIndentedLines(text, i); + end = i + endStep; + split = undefined; + } else { + if (ch === ' ' && prev && prev !== ' ' && prev !== '\n' && prev !== '\t') { + // space surrounded by non-space can be replaced with newline + indent + const next = text[i + 1]; + if (next && next !== ' ' && next !== '\n' && next !== '\t') split = i; + } + + if (i >= end) { + if (split) { + folds.push(split); + end = split + endStep; + split = undefined; + } else if (mode === FOLD_QUOTED) { + // white-space collected at end may stretch past lineWidth + while (prev === ' ' || prev === '\t') { + prev = ch; + ch = text[i += 1]; + overflow = true; + } // Account for newline escape, but don't break preceding escape + + + const j = i > escEnd + 1 ? i - 2 : escStart - 1; // Bail out if lineWidth & minContentWidth are shorter than an escape string + + if (escapedFolds[j]) return text; + folds.push(j); + escapedFolds[j] = true; + end = j + endStep; + split = undefined; + } else { + overflow = true; + } + } + } + + prev = ch; + } + + if (overflow && onOverflow) onOverflow(); + if (folds.length === 0) return text; + if (onFold) onFold(); + let res = text.slice(0, folds[0]); + + for (let i = 0; i < folds.length; ++i) { + const fold = folds[i]; + const end = folds[i + 1] || text.length; + if (fold === 0) res = `\n${indent}${text.slice(0, end)}`;else { + if (mode === FOLD_QUOTED && escapedFolds[fold]) res += `${text[fold]}\\`; + res += `\n${indent}${text.slice(fold + 1, end)}`; + } + } + + return res; +} + +const getFoldOptions = ({ + indentAtStart +}) => indentAtStart ? Object.assign({ + indentAtStart +}, strOptions.fold) : strOptions.fold; // Also checks for lines starting with %, as parsing the output as YAML 1.1 will +// presume that's starting a new document. + + +const containsDocumentMarker = str => /^(%|---|\.\.\.)/m.test(str); + +function lineLengthOverLimit(str, lineWidth, indentLength) { + if (!lineWidth || lineWidth < 0) return false; + const limit = lineWidth - indentLength; + const strLen = str.length; + if (strLen <= limit) return false; + + for (let i = 0, start = 0; i < strLen; ++i) { + if (str[i] === '\n') { + if (i - start > limit) return true; + start = i + 1; + if (strLen - start <= limit) return false; + } + } + + return true; +} + +function doubleQuotedString(value, ctx) { + const { + implicitKey + } = ctx; + const { + jsonEncoding, + minMultiLineLength + } = strOptions.doubleQuoted; + const json = JSON.stringify(value); + if (jsonEncoding) return json; + const indent = ctx.indent || (containsDocumentMarker(value) ? ' ' : ''); + let str = ''; + let start = 0; + + for (let i = 0, ch = json[i]; ch; ch = json[++i]) { + if (ch === ' ' && json[i + 1] === '\\' && json[i + 2] === 'n') { + // space before newline needs to be escaped to not be folded + str += json.slice(start, i) + '\\ '; + i += 1; + start = i; + ch = '\\'; + } + + if (ch === '\\') switch (json[i + 1]) { + case 'u': + { + str += json.slice(start, i); + const code = json.substr(i + 2, 4); + + switch (code) { + case '0000': + str += '\\0'; + break; + + case '0007': + str += '\\a'; + break; + + case '000b': + str += '\\v'; + break; + + case '001b': + str += '\\e'; + break; + + case '0085': + str += '\\N'; + break; + + case '00a0': + str += '\\_'; + break; + + case '2028': + str += '\\L'; + break; + + case '2029': + str += '\\P'; + break; + + default: + if (code.substr(0, 2) === '00') str += '\\x' + code.substr(2);else str += json.substr(i, 6); + } + + i += 5; + start = i + 1; + } + break; + + case 'n': + if (implicitKey || json[i + 2] === '"' || json.length < minMultiLineLength) { + i += 1; + } else { + // folding will eat first newline + str += json.slice(start, i) + '\n\n'; + + while (json[i + 2] === '\\' && json[i + 3] === 'n' && json[i + 4] !== '"') { + str += '\n'; + i += 2; + } + + str += indent; // space after newline needs to be escaped to not be folded + + if (json[i + 2] === ' ') str += '\\'; + i += 1; + start = i + 1; + } + + break; + + default: + i += 1; + } + } + + str = start ? str + json.slice(start) : json; + return implicitKey ? str : foldFlowLines(str, indent, FOLD_QUOTED, getFoldOptions(ctx)); +} + +function singleQuotedString(value, ctx) { + if (ctx.implicitKey) { + if (/\n/.test(value)) return doubleQuotedString(value, ctx); + } else { + // single quoted string can't have leading or trailing whitespace around newline + if (/[ \t]\n|\n[ \t]/.test(value)) return doubleQuotedString(value, ctx); + } + + const indent = ctx.indent || (containsDocumentMarker(value) ? ' ' : ''); + const res = "'" + value.replace(/'/g, "''").replace(/\n+/g, `$&\n${indent}`) + "'"; + return ctx.implicitKey ? res : foldFlowLines(res, indent, FOLD_FLOW, getFoldOptions(ctx)); +} + +function blockString({ + comment, + type, + value +}, ctx, onComment, onChompKeep) { + // 1. Block can't end in whitespace unless the last line is non-empty. + // 2. Strings consisting of only whitespace are best rendered explicitly. + if (/\n[\t ]+$/.test(value) || /^\s*$/.test(value)) { + return doubleQuotedString(value, ctx); + } + + const indent = ctx.indent || (ctx.forceBlockIndent || containsDocumentMarker(value) ? ' ' : ''); + const indentSize = indent ? '2' : '1'; // root is at -1 + + const literal = type === PlainValue$4.Type.BLOCK_FOLDED ? false : type === PlainValue$4.Type.BLOCK_LITERAL ? true : !lineLengthOverLimit(value, strOptions.fold.lineWidth, indent.length); + let header = literal ? '|' : '>'; + if (!value) return header + '\n'; + let wsStart = ''; + let wsEnd = ''; + value = value.replace(/[\n\t ]*$/, ws => { + const n = ws.indexOf('\n'); + + if (n === -1) { + header += '-'; // strip + } else if (value === ws || n !== ws.length - 1) { + header += '+'; // keep + + if (onChompKeep) onChompKeep(); + } + + wsEnd = ws.replace(/\n$/, ''); + return ''; + }).replace(/^[\n ]*/, ws => { + if (ws.indexOf(' ') !== -1) header += indentSize; + const m = ws.match(/ +$/); + + if (m) { + wsStart = ws.slice(0, -m[0].length); + return m[0]; + } else { + wsStart = ws; + return ''; + } + }); + if (wsEnd) wsEnd = wsEnd.replace(/\n+(?!\n|$)/g, `$&${indent}`); + if (wsStart) wsStart = wsStart.replace(/\n+/g, `$&${indent}`); + + if (comment) { + header += ' #' + comment.replace(/ ?[\r\n]+/g, ' '); + if (onComment) onComment(); + } + + if (!value) return `${header}${indentSize}\n${indent}${wsEnd}`; + + if (literal) { + value = value.replace(/\n+/g, `$&${indent}`); + return `${header}\n${indent}${wsStart}${value}${wsEnd}`; + } + + value = value.replace(/\n+/g, '\n$&').replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, '$1$2') // more-indented lines aren't folded + // ^ ind.line ^ empty ^ capture next empty lines only at end of indent + .replace(/\n+/g, `$&${indent}`); + const body = foldFlowLines(`${wsStart}${value}${wsEnd}`, indent, FOLD_BLOCK, strOptions.fold); + return `${header}\n${indent}${body}`; +} + +function plainString(item, ctx, onComment, onChompKeep) { + const { + comment, + type, + value + } = item; + const { + actualString, + implicitKey, + indent, + inFlow + } = ctx; + + if (implicitKey && /[\n[\]{},]/.test(value) || inFlow && /[[\]{},]/.test(value)) { + return doubleQuotedString(value, ctx); + } + + if (!value || /^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(value)) { + // not allowed: + // - empty string, '-' or '?' + // - start with an indicator character (except [?:-]) or /[?-] / + // - '\n ', ': ' or ' \n' anywhere + // - '#' not preceded by a non-space char + // - end with ' ' or ':' + return implicitKey || inFlow || value.indexOf('\n') === -1 ? value.indexOf('"') !== -1 && value.indexOf("'") === -1 ? singleQuotedString(value, ctx) : doubleQuotedString(value, ctx) : blockString(item, ctx, onComment, onChompKeep); + } + + if (!implicitKey && !inFlow && type !== PlainValue$4.Type.PLAIN && value.indexOf('\n') !== -1) { + // Where allowed & type not set explicitly, prefer block style for multiline strings + return blockString(item, ctx, onComment, onChompKeep); + } + + if (indent === '' && containsDocumentMarker(value)) { + ctx.forceBlockIndent = true; + return blockString(item, ctx, onComment, onChompKeep); + } + + const str = value.replace(/\n+/g, `$&\n${indent}`); // Verify that output will be parsed as a string, as e.g. plain numbers and + // booleans get parsed with those types in v1.2 (e.g. '42', 'true' & '0.9e-3'), + // and others in v1.1. + + if (actualString) { + const { + tags + } = ctx.doc.schema; + const resolved = resolveScalar(str, tags, tags.scalarFallback).value; + if (typeof resolved !== 'string') return doubleQuotedString(value, ctx); + } + + const body = implicitKey ? str : foldFlowLines(str, indent, FOLD_FLOW, getFoldOptions(ctx)); + + if (comment && !inFlow && (body.indexOf('\n') !== -1 || comment.indexOf('\n') !== -1)) { + if (onComment) onComment(); + return addCommentBefore(body, indent, comment); + } + + return body; +} + +function stringifyString(item, ctx, onComment, onChompKeep) { + const { + defaultType + } = strOptions; + const { + implicitKey, + inFlow + } = ctx; + let { + type, + value + } = item; + + if (typeof value !== 'string') { + value = String(value); + item = Object.assign({}, item, { + value + }); + } + + const _stringify = _type => { + switch (_type) { + case PlainValue$4.Type.BLOCK_FOLDED: + case PlainValue$4.Type.BLOCK_LITERAL: + return blockString(item, ctx, onComment, onChompKeep); + + case PlainValue$4.Type.QUOTE_DOUBLE: + return doubleQuotedString(value, ctx); + + case PlainValue$4.Type.QUOTE_SINGLE: + return singleQuotedString(value, ctx); + + case PlainValue$4.Type.PLAIN: + return plainString(item, ctx, onComment, onChompKeep); + + default: + return null; + } + }; + + if (type !== PlainValue$4.Type.QUOTE_DOUBLE && /[\x00-\x08\x0b-\x1f\x7f-\x9f]/.test(value)) { + // force double quotes on control characters + type = PlainValue$4.Type.QUOTE_DOUBLE; + } else if ((implicitKey || inFlow) && (type === PlainValue$4.Type.BLOCK_FOLDED || type === PlainValue$4.Type.BLOCK_LITERAL)) { + // should not happen; blocks are not valid inside flow containers + type = PlainValue$4.Type.QUOTE_DOUBLE; + } + + let res = _stringify(type); + + if (res === null) { + res = _stringify(defaultType); + if (res === null) throw new Error(`Unsupported default string type ${defaultType}`); + } + + return res; +} + +function stringifyNumber({ + format, + minFractionDigits, + tag, + value +}) { + if (typeof value === 'bigint') return String(value); + if (!isFinite(value)) return isNaN(value) ? '.nan' : value < 0 ? '-.inf' : '.inf'; + let n = JSON.stringify(value); + + if (!format && minFractionDigits && (!tag || tag === 'tag:yaml.org,2002:float') && /^\d/.test(n)) { + let i = n.indexOf('.'); + + if (i < 0) { + i = n.length; + n += '.'; + } + + let d = minFractionDigits - (n.length - i - 1); + + while (d-- > 0) n += '0'; + } + + return n; +} + +function checkFlowCollectionEnd(errors, cst) { + let char, name; + + switch (cst.type) { + case PlainValue$4.Type.FLOW_MAP: + char = '}'; + name = 'flow map'; + break; + + case PlainValue$4.Type.FLOW_SEQ: + char = ']'; + name = 'flow sequence'; + break; + + default: + errors.push(new PlainValue$4.YAMLSemanticError(cst, 'Not a flow collection!?')); + return; + } + + let lastItem; + + for (let i = cst.items.length - 1; i >= 0; --i) { + const item = cst.items[i]; + + if (!item || item.type !== PlainValue$4.Type.COMMENT) { + lastItem = item; + break; + } + } + + if (lastItem && lastItem.char !== char) { + const msg = `Expected ${name} to end with ${char}`; + let err; + + if (typeof lastItem.offset === 'number') { + err = new PlainValue$4.YAMLSemanticError(cst, msg); + err.offset = lastItem.offset + 1; + } else { + err = new PlainValue$4.YAMLSemanticError(lastItem, msg); + if (lastItem.range && lastItem.range.end) err.offset = lastItem.range.end - lastItem.range.start; + } + + errors.push(err); + } +} +function checkFlowCommentSpace(errors, comment) { + const prev = comment.context.src[comment.range.start - 1]; + + if (prev !== '\n' && prev !== '\t' && prev !== ' ') { + const msg = 'Comments must be separated from other tokens by white space characters'; + errors.push(new PlainValue$4.YAMLSemanticError(comment, msg)); + } +} +function getLongKeyError(source, key) { + const sk = String(key); + const k = sk.substr(0, 8) + '...' + sk.substr(-8); + return new PlainValue$4.YAMLSemanticError(source, `The "${k}" key is too long`); +} +function resolveComments(collection, comments) { + for (const { + afterKey, + before, + comment + } of comments) { + let item = collection.items[before]; + + if (!item) { + if (comment !== undefined) { + if (collection.comment) collection.comment += '\n' + comment;else collection.comment = comment; + } + } else { + if (afterKey && item.value) item = item.value; + + if (comment === undefined) { + if (afterKey || !item.commentBefore) item.spaceBefore = true; + } else { + if (item.commentBefore) item.commentBefore += '\n' + comment;else item.commentBefore = comment; + } + } + } +} + +// on error, will return { str: string, errors: Error[] } +function resolveString(doc, node) { + const res = node.strValue; + if (!res) return ''; + if (typeof res === 'string') return res; + res.errors.forEach(error => { + if (!error.source) error.source = node; + doc.errors.push(error); + }); + return res.str; +} + +function resolveTagHandle(doc, node) { + const { + handle, + suffix + } = node.tag; + let prefix = doc.tagPrefixes.find(p => p.handle === handle); + + if (!prefix) { + const dtp = doc.getDefaults().tagPrefixes; + if (dtp) prefix = dtp.find(p => p.handle === handle); + if (!prefix) throw new PlainValue$4.YAMLSemanticError(node, `The ${handle} tag handle is non-default and was not declared.`); + } + + if (!suffix) throw new PlainValue$4.YAMLSemanticError(node, `The ${handle} tag has no suffix.`); + + if (handle === '!' && (doc.version || doc.options.version) === '1.0') { + if (suffix[0] === '^') { + doc.warnings.push(new PlainValue$4.YAMLWarning(node, 'YAML 1.0 ^ tag expansion is not supported')); + return suffix; + } + + if (/[:/]/.test(suffix)) { + // word/foo -> tag:word.yaml.org,2002:foo + const vocab = suffix.match(/^([a-z0-9-]+)\/(.*)/i); + return vocab ? `tag:${vocab[1]}.yaml.org,2002:${vocab[2]}` : `tag:${suffix}`; + } + } + + return prefix.prefix + decodeURIComponent(suffix); +} + +function resolveTagName(doc, node) { + const { + tag, + type + } = node; + let nonSpecific = false; + + if (tag) { + const { + handle, + suffix, + verbatim + } = tag; + + if (verbatim) { + if (verbatim !== '!' && verbatim !== '!!') return verbatim; + const msg = `Verbatim tags aren't resolved, so ${verbatim} is invalid.`; + doc.errors.push(new PlainValue$4.YAMLSemanticError(node, msg)); + } else if (handle === '!' && !suffix) { + nonSpecific = true; + } else { + try { + return resolveTagHandle(doc, node); + } catch (error) { + doc.errors.push(error); + } + } + } + + switch (type) { + case PlainValue$4.Type.BLOCK_FOLDED: + case PlainValue$4.Type.BLOCK_LITERAL: + case PlainValue$4.Type.QUOTE_DOUBLE: + case PlainValue$4.Type.QUOTE_SINGLE: + return PlainValue$4.defaultTags.STR; + + case PlainValue$4.Type.FLOW_MAP: + case PlainValue$4.Type.MAP: + return PlainValue$4.defaultTags.MAP; + + case PlainValue$4.Type.FLOW_SEQ: + case PlainValue$4.Type.SEQ: + return PlainValue$4.defaultTags.SEQ; + + case PlainValue$4.Type.PLAIN: + return nonSpecific ? PlainValue$4.defaultTags.STR : null; + + default: + return null; + } +} + +function resolveByTagName(doc, node, tagName) { + const { + tags + } = doc.schema; + const matchWithTest = []; + + for (const tag of tags) { + if (tag.tag === tagName) { + if (tag.test) matchWithTest.push(tag);else { + const res = tag.resolve(doc, node); + return res instanceof Collection ? res : new Scalar(res); + } + } + } + + const str = resolveString(doc, node); + if (typeof str === 'string' && matchWithTest.length > 0) return resolveScalar(str, matchWithTest, tags.scalarFallback); + return null; +} + +function getFallbackTagName({ + type +}) { + switch (type) { + case PlainValue$4.Type.FLOW_MAP: + case PlainValue$4.Type.MAP: + return PlainValue$4.defaultTags.MAP; + + case PlainValue$4.Type.FLOW_SEQ: + case PlainValue$4.Type.SEQ: + return PlainValue$4.defaultTags.SEQ; + + default: + return PlainValue$4.defaultTags.STR; + } +} + +function resolveTag(doc, node, tagName) { + try { + const res = resolveByTagName(doc, node, tagName); + + if (res) { + if (tagName && node.tag) res.tag = tagName; + return res; + } + } catch (error) { + /* istanbul ignore if */ + if (!error.source) error.source = node; + doc.errors.push(error); + return null; + } + + try { + const fallback = getFallbackTagName(node); + if (!fallback) throw new Error(`The tag ${tagName} is unavailable`); + const msg = `The tag ${tagName} is unavailable, falling back to ${fallback}`; + doc.warnings.push(new PlainValue$4.YAMLWarning(node, msg)); + const res = resolveByTagName(doc, node, fallback); + res.tag = tagName; + return res; + } catch (error) { + const refError = new PlainValue$4.YAMLReferenceError(node, error.message); + refError.stack = error.stack; + doc.errors.push(refError); + return null; + } +} + +const isCollectionItem = node => { + if (!node) return false; + const { + type + } = node; + return type === PlainValue$4.Type.MAP_KEY || type === PlainValue$4.Type.MAP_VALUE || type === PlainValue$4.Type.SEQ_ITEM; +}; + +function resolveNodeProps(errors, node) { + const comments = { + before: [], + after: [] + }; + let hasAnchor = false; + let hasTag = false; + const props = isCollectionItem(node.context.parent) ? node.context.parent.props.concat(node.props) : node.props; + + for (const { + start, + end + } of props) { + switch (node.context.src[start]) { + case PlainValue$4.Char.COMMENT: + { + if (!node.commentHasRequiredWhitespace(start)) { + const msg = 'Comments must be separated from other tokens by white space characters'; + errors.push(new PlainValue$4.YAMLSemanticError(node, msg)); + } + + const { + header, + valueRange + } = node; + const cc = valueRange && (start > valueRange.start || header && start > header.start) ? comments.after : comments.before; + cc.push(node.context.src.slice(start + 1, end)); + break; + } + // Actual anchor & tag resolution is handled by schema, here we just complain + + case PlainValue$4.Char.ANCHOR: + if (hasAnchor) { + const msg = 'A node can have at most one anchor'; + errors.push(new PlainValue$4.YAMLSemanticError(node, msg)); + } + + hasAnchor = true; + break; + + case PlainValue$4.Char.TAG: + if (hasTag) { + const msg = 'A node can have at most one tag'; + errors.push(new PlainValue$4.YAMLSemanticError(node, msg)); + } + + hasTag = true; + break; + } + } + + return { + comments, + hasAnchor, + hasTag + }; +} + +function resolveNodeValue(doc, node) { + const { + anchors, + errors, + schema + } = doc; + + if (node.type === PlainValue$4.Type.ALIAS) { + const name = node.rawValue; + const src = anchors.getNode(name); + + if (!src) { + const msg = `Aliased anchor not found: ${name}`; + errors.push(new PlainValue$4.YAMLReferenceError(node, msg)); + return null; + } // Lazy resolution for circular references + + + const res = new Alias(src); + + anchors._cstAliases.push(res); + + return res; + } + + const tagName = resolveTagName(doc, node); + if (tagName) return resolveTag(doc, node, tagName); + + if (node.type !== PlainValue$4.Type.PLAIN) { + const msg = `Failed to resolve ${node.type} node here`; + errors.push(new PlainValue$4.YAMLSyntaxError(node, msg)); + return null; + } + + try { + const str = resolveString(doc, node); + return resolveScalar(str, schema.tags, schema.tags.scalarFallback); + } catch (error) { + if (!error.source) error.source = node; + errors.push(error); + return null; + } +} // sets node.resolved on success + + +function resolveNode(doc, node) { + if (!node) return null; + if (node.error) doc.errors.push(node.error); + const { + comments, + hasAnchor, + hasTag + } = resolveNodeProps(doc.errors, node); + + if (hasAnchor) { + const { + anchors + } = doc; + const name = node.anchor; + const prev = anchors.getNode(name); // At this point, aliases for any preceding node with the same anchor + // name have already been resolved, so it may safely be renamed. + + if (prev) anchors.map[anchors.newName(name)] = prev; // During parsing, we need to store the CST node in anchors.map as + // anchors need to be available during resolution to allow for + // circular references. + + anchors.map[name] = node; + } + + if (node.type === PlainValue$4.Type.ALIAS && (hasAnchor || hasTag)) { + const msg = 'An alias node must not specify any properties'; + doc.errors.push(new PlainValue$4.YAMLSemanticError(node, msg)); + } + + const res = resolveNodeValue(doc, node); + + if (res) { + res.range = [node.range.start, node.range.end]; + if (doc.options.keepCstNodes) res.cstNode = node; + if (doc.options.keepNodeTypes) res.type = node.type; + const cb = comments.before.join('\n'); + + if (cb) { + res.commentBefore = res.commentBefore ? `${res.commentBefore}\n${cb}` : cb; + } + + const ca = comments.after.join('\n'); + if (ca) res.comment = res.comment ? `${res.comment}\n${ca}` : ca; + } + + return node.resolved = res; +} + +function resolveMap(doc, cst) { + if (cst.type !== PlainValue$4.Type.MAP && cst.type !== PlainValue$4.Type.FLOW_MAP) { + const msg = `A ${cst.type} node cannot be resolved as a mapping`; + doc.errors.push(new PlainValue$4.YAMLSyntaxError(cst, msg)); + return null; + } + + const { + comments, + items + } = cst.type === PlainValue$4.Type.FLOW_MAP ? resolveFlowMapItems(doc, cst) : resolveBlockMapItems(doc, cst); + const map = new YAMLMap(); + map.items = items; + resolveComments(map, comments); + let hasCollectionKey = false; + + for (let i = 0; i < items.length; ++i) { + const { + key: iKey + } = items[i]; + if (iKey instanceof Collection) hasCollectionKey = true; + + if (doc.schema.merge && iKey && iKey.value === MERGE_KEY) { + items[i] = new Merge(items[i]); + const sources = items[i].value.items; + let error = null; + sources.some(node => { + if (node instanceof Alias) { + // During parsing, alias sources are CST nodes; to account for + // circular references their resolved values can't be used here. + const { + type + } = node.source; + if (type === PlainValue$4.Type.MAP || type === PlainValue$4.Type.FLOW_MAP) return false; + return error = 'Merge nodes aliases can only point to maps'; + } + + return error = 'Merge nodes can only have Alias nodes as values'; + }); + if (error) doc.errors.push(new PlainValue$4.YAMLSemanticError(cst, error)); + } else { + for (let j = i + 1; j < items.length; ++j) { + const { + key: jKey + } = items[j]; + + if (iKey === jKey || iKey && jKey && Object.prototype.hasOwnProperty.call(iKey, 'value') && iKey.value === jKey.value) { + const msg = `Map keys must be unique; "${iKey}" is repeated`; + doc.errors.push(new PlainValue$4.YAMLSemanticError(cst, msg)); + break; + } + } + } + } + + if (hasCollectionKey && !doc.options.mapAsMap) { + const warn = 'Keys with collection values will be stringified as YAML due to JS Object restrictions. Use mapAsMap: true to avoid this.'; + doc.warnings.push(new PlainValue$4.YAMLWarning(cst, warn)); + } + + cst.resolved = map; + return map; +} + +const valueHasPairComment = ({ + context: { + lineStart, + node, + src + }, + props +}) => { + if (props.length === 0) return false; + const { + start + } = props[0]; + if (node && start > node.valueRange.start) return false; + if (src[start] !== PlainValue$4.Char.COMMENT) return false; + + for (let i = lineStart; i < start; ++i) if (src[i] === '\n') return false; + + return true; +}; + +function resolvePairComment(item, pair) { + if (!valueHasPairComment(item)) return; + const comment = item.getPropValue(0, PlainValue$4.Char.COMMENT, true); + let found = false; + const cb = pair.value.commentBefore; + + if (cb && cb.startsWith(comment)) { + pair.value.commentBefore = cb.substr(comment.length + 1); + found = true; + } else { + const cc = pair.value.comment; + + if (!item.node && cc && cc.startsWith(comment)) { + pair.value.comment = cc.substr(comment.length + 1); + found = true; + } + } + + if (found) pair.comment = comment; +} + +function resolveBlockMapItems(doc, cst) { + const comments = []; + const items = []; + let key = undefined; + let keyStart = null; + + for (let i = 0; i < cst.items.length; ++i) { + const item = cst.items[i]; + + switch (item.type) { + case PlainValue$4.Type.BLANK_LINE: + comments.push({ + afterKey: !!key, + before: items.length + }); + break; + + case PlainValue$4.Type.COMMENT: + comments.push({ + afterKey: !!key, + before: items.length, + comment: item.comment + }); + break; + + case PlainValue$4.Type.MAP_KEY: + if (key !== undefined) items.push(new Pair(key)); + if (item.error) doc.errors.push(item.error); + key = resolveNode(doc, item.node); + keyStart = null; + break; + + case PlainValue$4.Type.MAP_VALUE: + { + if (key === undefined) key = null; + if (item.error) doc.errors.push(item.error); + + if (!item.context.atLineStart && item.node && item.node.type === PlainValue$4.Type.MAP && !item.node.context.atLineStart) { + const msg = 'Nested mappings are not allowed in compact mappings'; + doc.errors.push(new PlainValue$4.YAMLSemanticError(item.node, msg)); + } + + let valueNode = item.node; + + if (!valueNode && item.props.length > 0) { + // Comments on an empty mapping value need to be preserved, so we + // need to construct a minimal empty node here to use instead of the + // missing `item.node`. -- eemeli/yaml#19 + valueNode = new PlainValue$4.PlainValue(PlainValue$4.Type.PLAIN, []); + valueNode.context = { + parent: item, + src: item.context.src + }; + const pos = item.range.start + 1; + valueNode.range = { + start: pos, + end: pos + }; + valueNode.valueRange = { + start: pos, + end: pos + }; + + if (typeof item.range.origStart === 'number') { + const origPos = item.range.origStart + 1; + valueNode.range.origStart = valueNode.range.origEnd = origPos; + valueNode.valueRange.origStart = valueNode.valueRange.origEnd = origPos; + } + } + + const pair = new Pair(key, resolveNode(doc, valueNode)); + resolvePairComment(item, pair); + items.push(pair); + + if (key && typeof keyStart === 'number') { + if (item.range.start > keyStart + 1024) doc.errors.push(getLongKeyError(cst, key)); + } + + key = undefined; + keyStart = null; + } + break; + + default: + if (key !== undefined) items.push(new Pair(key)); + key = resolveNode(doc, item); + keyStart = item.range.start; + if (item.error) doc.errors.push(item.error); + + next: for (let j = i + 1;; ++j) { + const nextItem = cst.items[j]; + + switch (nextItem && nextItem.type) { + case PlainValue$4.Type.BLANK_LINE: + case PlainValue$4.Type.COMMENT: + continue next; + + case PlainValue$4.Type.MAP_VALUE: + break next; + + default: + { + const msg = 'Implicit map keys need to be followed by map values'; + doc.errors.push(new PlainValue$4.YAMLSemanticError(item, msg)); + break next; + } + } + } + + if (item.valueRangeContainsNewline) { + const msg = 'Implicit map keys need to be on a single line'; + doc.errors.push(new PlainValue$4.YAMLSemanticError(item, msg)); + } + + } + } + + if (key !== undefined) items.push(new Pair(key)); + return { + comments, + items + }; +} + +function resolveFlowMapItems(doc, cst) { + const comments = []; + const items = []; + let key = undefined; + let explicitKey = false; + let next = '{'; + + for (let i = 0; i < cst.items.length; ++i) { + const item = cst.items[i]; + + if (typeof item.char === 'string') { + const { + char, + offset + } = item; + + if (char === '?' && key === undefined && !explicitKey) { + explicitKey = true; + next = ':'; + continue; + } + + if (char === ':') { + if (key === undefined) key = null; + + if (next === ':') { + next = ','; + continue; + } + } else { + if (explicitKey) { + if (key === undefined && char !== ',') key = null; + explicitKey = false; + } + + if (key !== undefined) { + items.push(new Pair(key)); + key = undefined; + + if (char === ',') { + next = ':'; + continue; + } + } + } + + if (char === '}') { + if (i === cst.items.length - 1) continue; + } else if (char === next) { + next = ':'; + continue; + } + + const msg = `Flow map contains an unexpected ${char}`; + const err = new PlainValue$4.YAMLSyntaxError(cst, msg); + err.offset = offset; + doc.errors.push(err); + } else if (item.type === PlainValue$4.Type.BLANK_LINE) { + comments.push({ + afterKey: !!key, + before: items.length + }); + } else if (item.type === PlainValue$4.Type.COMMENT) { + checkFlowCommentSpace(doc.errors, item); + comments.push({ + afterKey: !!key, + before: items.length, + comment: item.comment + }); + } else if (key === undefined) { + if (next === ',') doc.errors.push(new PlainValue$4.YAMLSemanticError(item, 'Separator , missing in flow map')); + key = resolveNode(doc, item); + } else { + if (next !== ',') doc.errors.push(new PlainValue$4.YAMLSemanticError(item, 'Indicator : missing in flow map entry')); + items.push(new Pair(key, resolveNode(doc, item))); + key = undefined; + explicitKey = false; + } + } + + checkFlowCollectionEnd(doc.errors, cst); + if (key !== undefined) items.push(new Pair(key)); + return { + comments, + items + }; +} + +function resolveSeq$3(doc, cst) { + if (cst.type !== PlainValue$4.Type.SEQ && cst.type !== PlainValue$4.Type.FLOW_SEQ) { + const msg = `A ${cst.type} node cannot be resolved as a sequence`; + doc.errors.push(new PlainValue$4.YAMLSyntaxError(cst, msg)); + return null; + } + + const { + comments, + items + } = cst.type === PlainValue$4.Type.FLOW_SEQ ? resolveFlowSeqItems(doc, cst) : resolveBlockSeqItems(doc, cst); + const seq = new YAMLSeq(); + seq.items = items; + resolveComments(seq, comments); + + if (!doc.options.mapAsMap && items.some(it => it instanceof Pair && it.key instanceof Collection)) { + const warn = 'Keys with collection values will be stringified as YAML due to JS Object restrictions. Use mapAsMap: true to avoid this.'; + doc.warnings.push(new PlainValue$4.YAMLWarning(cst, warn)); + } + + cst.resolved = seq; + return seq; +} + +function resolveBlockSeqItems(doc, cst) { + const comments = []; + const items = []; + + for (let i = 0; i < cst.items.length; ++i) { + const item = cst.items[i]; + + switch (item.type) { + case PlainValue$4.Type.BLANK_LINE: + comments.push({ + before: items.length + }); + break; + + case PlainValue$4.Type.COMMENT: + comments.push({ + comment: item.comment, + before: items.length + }); + break; + + case PlainValue$4.Type.SEQ_ITEM: + if (item.error) doc.errors.push(item.error); + items.push(resolveNode(doc, item.node)); + + if (item.hasProps) { + const msg = 'Sequence items cannot have tags or anchors before the - indicator'; + doc.errors.push(new PlainValue$4.YAMLSemanticError(item, msg)); + } + + break; + + default: + if (item.error) doc.errors.push(item.error); + doc.errors.push(new PlainValue$4.YAMLSyntaxError(item, `Unexpected ${item.type} node in sequence`)); + } + } + + return { + comments, + items + }; +} + +function resolveFlowSeqItems(doc, cst) { + const comments = []; + const items = []; + let explicitKey = false; + let key = undefined; + let keyStart = null; + let next = '['; + let prevItem = null; + + for (let i = 0; i < cst.items.length; ++i) { + const item = cst.items[i]; + + if (typeof item.char === 'string') { + const { + char, + offset + } = item; + + if (char !== ':' && (explicitKey || key !== undefined)) { + if (explicitKey && key === undefined) key = next ? items.pop() : null; + items.push(new Pair(key)); + explicitKey = false; + key = undefined; + keyStart = null; + } + + if (char === next) { + next = null; + } else if (!next && char === '?') { + explicitKey = true; + } else if (next !== '[' && char === ':' && key === undefined) { + if (next === ',') { + key = items.pop(); + + if (key instanceof Pair) { + const msg = 'Chaining flow sequence pairs is invalid'; + const err = new PlainValue$4.YAMLSemanticError(cst, msg); + err.offset = offset; + doc.errors.push(err); + } + + if (!explicitKey && typeof keyStart === 'number') { + const keyEnd = item.range ? item.range.start : item.offset; + if (keyEnd > keyStart + 1024) doc.errors.push(getLongKeyError(cst, key)); + const { + src + } = prevItem.context; + + for (let i = keyStart; i < keyEnd; ++i) if (src[i] === '\n') { + const msg = 'Implicit keys of flow sequence pairs need to be on a single line'; + doc.errors.push(new PlainValue$4.YAMLSemanticError(prevItem, msg)); + break; + } + } + } else { + key = null; + } + + keyStart = null; + explicitKey = false; + next = null; + } else if (next === '[' || char !== ']' || i < cst.items.length - 1) { + const msg = `Flow sequence contains an unexpected ${char}`; + const err = new PlainValue$4.YAMLSyntaxError(cst, msg); + err.offset = offset; + doc.errors.push(err); + } + } else if (item.type === PlainValue$4.Type.BLANK_LINE) { + comments.push({ + before: items.length + }); + } else if (item.type === PlainValue$4.Type.COMMENT) { + checkFlowCommentSpace(doc.errors, item); + comments.push({ + comment: item.comment, + before: items.length + }); + } else { + if (next) { + const msg = `Expected a ${next} in flow sequence`; + doc.errors.push(new PlainValue$4.YAMLSemanticError(item, msg)); + } + + const value = resolveNode(doc, item); + + if (key === undefined) { + items.push(value); + prevItem = item; + } else { + items.push(new Pair(key, value)); + key = undefined; + } + + keyStart = item.range.start; + next = ','; + } + } + + checkFlowCollectionEnd(doc.errors, cst); + if (key !== undefined) items.push(new Pair(key)); + return { + comments, + items + }; +} + +resolveSeqD03cb037.Alias = Alias; +resolveSeqD03cb037.Collection = Collection; +resolveSeqD03cb037.Merge = Merge; +resolveSeqD03cb037.Node = Node; +resolveSeqD03cb037.Pair = Pair; +resolveSeqD03cb037.Scalar = Scalar; +resolveSeqD03cb037.YAMLMap = YAMLMap; +resolveSeqD03cb037.YAMLSeq = YAMLSeq; +resolveSeqD03cb037.addComment = addComment; +resolveSeqD03cb037.binaryOptions = binaryOptions; +resolveSeqD03cb037.boolOptions = boolOptions; +resolveSeqD03cb037.findPair = findPair; +resolveSeqD03cb037.intOptions = intOptions; +resolveSeqD03cb037.isEmptyPath = isEmptyPath; +resolveSeqD03cb037.nullOptions = nullOptions; +resolveSeqD03cb037.resolveMap = resolveMap; +resolveSeqD03cb037.resolveNode = resolveNode; +resolveSeqD03cb037.resolveSeq = resolveSeq$3; +resolveSeqD03cb037.resolveString = resolveString; +resolveSeqD03cb037.strOptions = strOptions; +resolveSeqD03cb037.stringifyNumber = stringifyNumber; +resolveSeqD03cb037.stringifyString = stringifyString; +resolveSeqD03cb037.toJSON = toJSON; + +var Schema88e323a7 = {}; + +var warnings1000a372 = {}; + +var PlainValue$3 = PlainValueEc8e588e; +var resolveSeq$2 = resolveSeqD03cb037; + +/* global atob, btoa, Buffer */ +const binary$1 = { + identify: value => value instanceof Uint8Array, + // Buffer inherits from Uint8Array + default: false, + tag: 'tag:yaml.org,2002:binary', + + /** + * Returns a Buffer in node and an Uint8Array in browsers + * + * To use the resulting buffer as an image, you'll want to do something like: + * + * const blob = new Blob([buffer], { type: 'image/jpeg' }) + * document.querySelector('#photo').src = URL.createObjectURL(blob) + */ + resolve: (doc, node) => { + const src = resolveSeq$2.resolveString(doc, node); + + if (typeof Buffer === 'function') { + return Buffer.from(src, 'base64'); + } else if (typeof atob === 'function') { + // On IE 11, atob() can't handle newlines + const str = atob(src.replace(/[\n\r]/g, '')); + const buffer = new Uint8Array(str.length); + + for (let i = 0; i < str.length; ++i) buffer[i] = str.charCodeAt(i); + + return buffer; + } else { + const msg = 'This environment does not support reading binary tags; either Buffer or atob is required'; + doc.errors.push(new PlainValue$3.YAMLReferenceError(node, msg)); + return null; + } + }, + options: resolveSeq$2.binaryOptions, + stringify: ({ + comment, + type, + value + }, ctx, onComment, onChompKeep) => { + let src; + + if (typeof Buffer === 'function') { + src = value instanceof Buffer ? value.toString('base64') : Buffer.from(value.buffer).toString('base64'); + } else if (typeof btoa === 'function') { + let s = ''; + + for (let i = 0; i < value.length; ++i) s += String.fromCharCode(value[i]); + + src = btoa(s); + } else { + throw new Error('This environment does not support writing binary tags; either Buffer or btoa is required'); + } + + if (!type) type = resolveSeq$2.binaryOptions.defaultType; + + if (type === PlainValue$3.Type.QUOTE_DOUBLE) { + value = src; + } else { + const { + lineWidth + } = resolveSeq$2.binaryOptions; + const n = Math.ceil(src.length / lineWidth); + const lines = new Array(n); + + for (let i = 0, o = 0; i < n; ++i, o += lineWidth) { + lines[i] = src.substr(o, lineWidth); + } + + value = lines.join(type === PlainValue$3.Type.BLOCK_LITERAL ? '\n' : ' '); + } + + return resolveSeq$2.stringifyString({ + comment, + type, + value + }, ctx, onComment, onChompKeep); + } +}; + +function parsePairs(doc, cst) { + const seq = resolveSeq$2.resolveSeq(doc, cst); + + for (let i = 0; i < seq.items.length; ++i) { + let item = seq.items[i]; + if (item instanceof resolveSeq$2.Pair) continue;else if (item instanceof resolveSeq$2.YAMLMap) { + if (item.items.length > 1) { + const msg = 'Each pair must have its own sequence indicator'; + throw new PlainValue$3.YAMLSemanticError(cst, msg); + } + + const pair = item.items[0] || new resolveSeq$2.Pair(); + if (item.commentBefore) pair.commentBefore = pair.commentBefore ? `${item.commentBefore}\n${pair.commentBefore}` : item.commentBefore; + if (item.comment) pair.comment = pair.comment ? `${item.comment}\n${pair.comment}` : item.comment; + item = pair; + } + seq.items[i] = item instanceof resolveSeq$2.Pair ? item : new resolveSeq$2.Pair(item); + } + + return seq; +} +function createPairs(schema, iterable, ctx) { + const pairs = new resolveSeq$2.YAMLSeq(schema); + pairs.tag = 'tag:yaml.org,2002:pairs'; + + for (const it of iterable) { + let key, value; + + if (Array.isArray(it)) { + if (it.length === 2) { + key = it[0]; + value = it[1]; + } else throw new TypeError(`Expected [key, value] tuple: ${it}`); + } else if (it && it instanceof Object) { + const keys = Object.keys(it); + + if (keys.length === 1) { + key = keys[0]; + value = it[key]; + } else throw new TypeError(`Expected { key: value } tuple: ${it}`); + } else { + key = it; + } + + const pair = schema.createPair(key, value, ctx); + pairs.items.push(pair); + } + + return pairs; +} +const pairs = { + default: false, + tag: 'tag:yaml.org,2002:pairs', + resolve: parsePairs, + createNode: createPairs +}; + +class YAMLOMap extends resolveSeq$2.YAMLSeq { + constructor() { + super(); + + PlainValue$3._defineProperty(this, "add", resolveSeq$2.YAMLMap.prototype.add.bind(this)); + + PlainValue$3._defineProperty(this, "delete", resolveSeq$2.YAMLMap.prototype.delete.bind(this)); + + PlainValue$3._defineProperty(this, "get", resolveSeq$2.YAMLMap.prototype.get.bind(this)); + + PlainValue$3._defineProperty(this, "has", resolveSeq$2.YAMLMap.prototype.has.bind(this)); + + PlainValue$3._defineProperty(this, "set", resolveSeq$2.YAMLMap.prototype.set.bind(this)); + + this.tag = YAMLOMap.tag; + } + + toJSON(_, ctx) { + const map = new Map(); + if (ctx && ctx.onCreate) ctx.onCreate(map); + + for (const pair of this.items) { + let key, value; + + if (pair instanceof resolveSeq$2.Pair) { + key = resolveSeq$2.toJSON(pair.key, '', ctx); + value = resolveSeq$2.toJSON(pair.value, key, ctx); + } else { + key = resolveSeq$2.toJSON(pair, '', ctx); + } + + if (map.has(key)) throw new Error('Ordered maps must not include duplicate keys'); + map.set(key, value); + } + + return map; + } + +} + +PlainValue$3._defineProperty(YAMLOMap, "tag", 'tag:yaml.org,2002:omap'); + +function parseOMap(doc, cst) { + const pairs = parsePairs(doc, cst); + const seenKeys = []; + + for (const { + key + } of pairs.items) { + if (key instanceof resolveSeq$2.Scalar) { + if (seenKeys.includes(key.value)) { + const msg = 'Ordered maps must not include duplicate keys'; + throw new PlainValue$3.YAMLSemanticError(cst, msg); + } else { + seenKeys.push(key.value); + } + } + } + + return Object.assign(new YAMLOMap(), pairs); +} + +function createOMap(schema, iterable, ctx) { + const pairs = createPairs(schema, iterable, ctx); + const omap = new YAMLOMap(); + omap.items = pairs.items; + return omap; +} + +const omap = { + identify: value => value instanceof Map, + nodeClass: YAMLOMap, + default: false, + tag: 'tag:yaml.org,2002:omap', + resolve: parseOMap, + createNode: createOMap +}; + +class YAMLSet extends resolveSeq$2.YAMLMap { + constructor() { + super(); + this.tag = YAMLSet.tag; + } + + add(key) { + const pair = key instanceof resolveSeq$2.Pair ? key : new resolveSeq$2.Pair(key); + const prev = resolveSeq$2.findPair(this.items, pair.key); + if (!prev) this.items.push(pair); + } + + get(key, keepPair) { + const pair = resolveSeq$2.findPair(this.items, key); + return !keepPair && pair instanceof resolveSeq$2.Pair ? pair.key instanceof resolveSeq$2.Scalar ? pair.key.value : pair.key : pair; + } + + set(key, value) { + if (typeof value !== 'boolean') throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value}`); + const prev = resolveSeq$2.findPair(this.items, key); + + if (prev && !value) { + this.items.splice(this.items.indexOf(prev), 1); + } else if (!prev && value) { + this.items.push(new resolveSeq$2.Pair(key)); + } + } + + toJSON(_, ctx) { + return super.toJSON(_, ctx, Set); + } + + toString(ctx, onComment, onChompKeep) { + if (!ctx) return JSON.stringify(this); + if (this.hasAllNullValues()) return super.toString(ctx, onComment, onChompKeep);else throw new Error('Set items must all have null values'); + } + +} + +PlainValue$3._defineProperty(YAMLSet, "tag", 'tag:yaml.org,2002:set'); + +function parseSet(doc, cst) { + const map = resolveSeq$2.resolveMap(doc, cst); + if (!map.hasAllNullValues()) throw new PlainValue$3.YAMLSemanticError(cst, 'Set items must all have null values'); + return Object.assign(new YAMLSet(), map); +} + +function createSet$2(schema, iterable, ctx) { + const set = new YAMLSet(); + + for (const value of iterable) set.items.push(schema.createPair(value, null, ctx)); + + return set; +} + +const set = { + identify: value => value instanceof Set, + nodeClass: YAMLSet, + default: false, + tag: 'tag:yaml.org,2002:set', + resolve: parseSet, + createNode: createSet$2 +}; + +const parseSexagesimal = (sign, parts) => { + const n = parts.split(':').reduce((n, p) => n * 60 + Number(p), 0); + return sign === '-' ? -n : n; +}; // hhhh:mm:ss.sss + + +const stringifySexagesimal = ({ + value +}) => { + if (isNaN(value) || !isFinite(value)) return resolveSeq$2.stringifyNumber(value); + let sign = ''; + + if (value < 0) { + sign = '-'; + value = Math.abs(value); + } + + const parts = [value % 60]; // seconds, including ms + + if (value < 60) { + parts.unshift(0); // at least one : is required + } else { + value = Math.round((value - parts[0]) / 60); + parts.unshift(value % 60); // minutes + + if (value >= 60) { + value = Math.round((value - parts[0]) / 60); + parts.unshift(value); // hours + } + } + + return sign + parts.map(n => n < 10 ? '0' + String(n) : String(n)).join(':').replace(/000000\d*$/, '') // % 60 may introduce error + ; +}; + +const intTime = { + identify: value => typeof value === 'number', + default: true, + tag: 'tag:yaml.org,2002:int', + format: 'TIME', + test: /^([-+]?)([0-9][0-9_]*(?::[0-5]?[0-9])+)$/, + resolve: (str, sign, parts) => parseSexagesimal(sign, parts.replace(/_/g, '')), + stringify: stringifySexagesimal +}; +const floatTime = { + identify: value => typeof value === 'number', + default: true, + tag: 'tag:yaml.org,2002:float', + format: 'TIME', + test: /^([-+]?)([0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*)$/, + resolve: (str, sign, parts) => parseSexagesimal(sign, parts.replace(/_/g, '')), + stringify: stringifySexagesimal +}; +const timestamp = { + identify: value => value instanceof Date, + default: true, + tag: 'tag:yaml.org,2002:timestamp', + // If the time zone is omitted, the timestamp is assumed to be specified in UTC. The time part + // may be omitted altogether, resulting in a date format. In such a case, the time part is + // assumed to be 00:00:00Z (start of day, UTC). + test: RegExp('^(?:' + '([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})' + // YYYY-Mm-Dd + '(?:(?:t|T|[ \\t]+)' + // t | T | whitespace + '([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)' + // Hh:Mm:Ss(.ss)? + '(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?' + // Z | +5 | -03:30 + ')?' + ')$'), + resolve: (str, year, month, day, hour, minute, second, millisec, tz) => { + if (millisec) millisec = (millisec + '00').substr(1, 3); + let date = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec || 0); + + if (tz && tz !== 'Z') { + let d = parseSexagesimal(tz[0], tz.slice(1)); + if (Math.abs(d) < 30) d *= 60; + date -= 60000 * d; + } + + return new Date(date); + }, + stringify: ({ + value + }) => value.toISOString().replace(/((T00:00)?:00)?\.000Z$/, '') +}; + +/* global console, process, YAML_SILENCE_DEPRECATION_WARNINGS, YAML_SILENCE_WARNINGS */ +function shouldWarn(deprecation) { + const env = typeof process !== 'undefined' && process.env || {}; + + if (deprecation) { + if (typeof YAML_SILENCE_DEPRECATION_WARNINGS !== 'undefined') return !YAML_SILENCE_DEPRECATION_WARNINGS; + return !env.YAML_SILENCE_DEPRECATION_WARNINGS; + } + + if (typeof YAML_SILENCE_WARNINGS !== 'undefined') return !YAML_SILENCE_WARNINGS; + return !env.YAML_SILENCE_WARNINGS; +} + +function warn(warning, type) { + if (shouldWarn(false)) { + const emit = typeof process !== 'undefined' && process.emitWarning; // This will throw in Jest if `warning` is an Error instance due to + // https://github.com/facebook/jest/issues/2549 + + if (emit) emit(warning, type);else { + // eslint-disable-next-line no-console + console.warn(type ? `${type}: ${warning}` : warning); + } + } +} +function warnFileDeprecation(filename) { + if (shouldWarn(true)) { + const path = filename.replace(/.*yaml[/\\]/i, '').replace(/\.js$/, '').replace(/\\/g, '/'); + warn(`The endpoint 'yaml/${path}' will be removed in a future release.`, 'DeprecationWarning'); + } +} +const warned = {}; +function warnOptionDeprecation(name, alternative) { + if (!warned[name] && shouldWarn(true)) { + warned[name] = true; + let msg = `The option '${name}' will be removed in a future release`; + msg += alternative ? `, use '${alternative}' instead.` : '.'; + warn(msg, 'DeprecationWarning'); + } +} + +warnings1000a372.binary = binary$1; +warnings1000a372.floatTime = floatTime; +warnings1000a372.intTime = intTime; +warnings1000a372.omap = omap; +warnings1000a372.pairs = pairs; +warnings1000a372.set = set; +warnings1000a372.timestamp = timestamp; +warnings1000a372.warn = warn; +warnings1000a372.warnFileDeprecation = warnFileDeprecation; +warnings1000a372.warnOptionDeprecation = warnOptionDeprecation; + +var PlainValue$2 = PlainValueEc8e588e; +var resolveSeq$1 = resolveSeqD03cb037; +var warnings$1 = warnings1000a372; + +function createMap(schema, obj, ctx) { + const map = new resolveSeq$1.YAMLMap(schema); + + if (obj instanceof Map) { + for (const [key, value] of obj) map.items.push(schema.createPair(key, value, ctx)); + } else if (obj && typeof obj === 'object') { + for (const key of Object.keys(obj)) map.items.push(schema.createPair(key, obj[key], ctx)); + } + + if (typeof schema.sortMapEntries === 'function') { + map.items.sort(schema.sortMapEntries); + } + + return map; +} + +const map$2 = { + createNode: createMap, + default: true, + nodeClass: resolveSeq$1.YAMLMap, + tag: 'tag:yaml.org,2002:map', + resolve: resolveSeq$1.resolveMap +}; + +function createSeq(schema, obj, ctx) { + const seq = new resolveSeq$1.YAMLSeq(schema); + + if (obj && obj[Symbol.iterator]) { + for (const it of obj) { + const v = schema.createNode(it, ctx.wrapScalars, null, ctx); + seq.items.push(v); + } + } + + return seq; +} + +const seq = { + createNode: createSeq, + default: true, + nodeClass: resolveSeq$1.YAMLSeq, + tag: 'tag:yaml.org,2002:seq', + resolve: resolveSeq$1.resolveSeq +}; + +const string = { + identify: value => typeof value === 'string', + default: true, + tag: 'tag:yaml.org,2002:str', + resolve: resolveSeq$1.resolveString, + + stringify(item, ctx, onComment, onChompKeep) { + ctx = Object.assign({ + actualString: true + }, ctx); + return resolveSeq$1.stringifyString(item, ctx, onComment, onChompKeep); + }, + + options: resolveSeq$1.strOptions +}; + +const failsafe = [map$2, seq, string]; + +/* global BigInt */ + +const intIdentify$2 = value => typeof value === 'bigint' || Number.isInteger(value); + +const intResolve$1 = (src, part, radix) => resolveSeq$1.intOptions.asBigInt ? BigInt(src) : parseInt(part, radix); + +function intStringify$1(node, radix, prefix) { + const { + value + } = node; + if (intIdentify$2(value) && value >= 0) return prefix + value.toString(radix); + return resolveSeq$1.stringifyNumber(node); +} + +const nullObj = { + identify: value => value == null, + createNode: (schema, value, ctx) => ctx.wrapScalars ? new resolveSeq$1.Scalar(null) : null, + default: true, + tag: 'tag:yaml.org,2002:null', + test: /^(?:~|[Nn]ull|NULL)?$/, + resolve: () => null, + options: resolveSeq$1.nullOptions, + stringify: () => resolveSeq$1.nullOptions.nullStr +}; +const boolObj = { + identify: value => typeof value === 'boolean', + default: true, + tag: 'tag:yaml.org,2002:bool', + test: /^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/, + resolve: str => str[0] === 't' || str[0] === 'T', + options: resolveSeq$1.boolOptions, + stringify: ({ + value + }) => value ? resolveSeq$1.boolOptions.trueStr : resolveSeq$1.boolOptions.falseStr +}; +const octObj = { + identify: value => intIdentify$2(value) && value >= 0, + default: true, + tag: 'tag:yaml.org,2002:int', + format: 'OCT', + test: /^0o([0-7]+)$/, + resolve: (str, oct) => intResolve$1(str, oct, 8), + options: resolveSeq$1.intOptions, + stringify: node => intStringify$1(node, 8, '0o') +}; +const intObj = { + identify: intIdentify$2, + default: true, + tag: 'tag:yaml.org,2002:int', + test: /^[-+]?[0-9]+$/, + resolve: str => intResolve$1(str, str, 10), + options: resolveSeq$1.intOptions, + stringify: resolveSeq$1.stringifyNumber +}; +const hexObj = { + identify: value => intIdentify$2(value) && value >= 0, + default: true, + tag: 'tag:yaml.org,2002:int', + format: 'HEX', + test: /^0x([0-9a-fA-F]+)$/, + resolve: (str, hex) => intResolve$1(str, hex, 16), + options: resolveSeq$1.intOptions, + stringify: node => intStringify$1(node, 16, '0x') +}; +const nanObj = { + identify: value => typeof value === 'number', + default: true, + tag: 'tag:yaml.org,2002:float', + test: /^(?:[-+]?\.inf|(\.nan))$/i, + resolve: (str, nan) => nan ? NaN : str[0] === '-' ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, + stringify: resolveSeq$1.stringifyNumber +}; +const expObj = { + identify: value => typeof value === 'number', + default: true, + tag: 'tag:yaml.org,2002:float', + format: 'EXP', + test: /^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/, + resolve: str => parseFloat(str), + stringify: ({ + value + }) => Number(value).toExponential() +}; +const floatObj = { + identify: value => typeof value === 'number', + default: true, + tag: 'tag:yaml.org,2002:float', + test: /^[-+]?(?:\.([0-9]+)|[0-9]+\.([0-9]*))$/, + + resolve(str, frac1, frac2) { + const frac = frac1 || frac2; + const node = new resolveSeq$1.Scalar(parseFloat(str)); + if (frac && frac[frac.length - 1] === '0') node.minFractionDigits = frac.length; + return node; + }, + + stringify: resolveSeq$1.stringifyNumber +}; +const core = failsafe.concat([nullObj, boolObj, octObj, intObj, hexObj, nanObj, expObj, floatObj]); + +/* global BigInt */ + +const intIdentify$1 = value => typeof value === 'bigint' || Number.isInteger(value); + +const stringifyJSON = ({ + value +}) => JSON.stringify(value); + +const json = [map$2, seq, { + identify: value => typeof value === 'string', + default: true, + tag: 'tag:yaml.org,2002:str', + resolve: resolveSeq$1.resolveString, + stringify: stringifyJSON +}, { + identify: value => value == null, + createNode: (schema, value, ctx) => ctx.wrapScalars ? new resolveSeq$1.Scalar(null) : null, + default: true, + tag: 'tag:yaml.org,2002:null', + test: /^null$/, + resolve: () => null, + stringify: stringifyJSON +}, { + identify: value => typeof value === 'boolean', + default: true, + tag: 'tag:yaml.org,2002:bool', + test: /^true|false$/, + resolve: str => str === 'true', + stringify: stringifyJSON +}, { + identify: intIdentify$1, + default: true, + tag: 'tag:yaml.org,2002:int', + test: /^-?(?:0|[1-9][0-9]*)$/, + resolve: str => resolveSeq$1.intOptions.asBigInt ? BigInt(str) : parseInt(str, 10), + stringify: ({ + value + }) => intIdentify$1(value) ? value.toString() : JSON.stringify(value) +}, { + identify: value => typeof value === 'number', + default: true, + tag: 'tag:yaml.org,2002:float', + test: /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/, + resolve: str => parseFloat(str), + stringify: stringifyJSON +}]; + +json.scalarFallback = str => { + throw new SyntaxError(`Unresolved plain scalar ${JSON.stringify(str)}`); +}; + +/* global BigInt */ + +const boolStringify = ({ + value +}) => value ? resolveSeq$1.boolOptions.trueStr : resolveSeq$1.boolOptions.falseStr; + +const intIdentify = value => typeof value === 'bigint' || Number.isInteger(value); + +function intResolve(sign, src, radix) { + let str = src.replace(/_/g, ''); + + if (resolveSeq$1.intOptions.asBigInt) { + switch (radix) { + case 2: + str = `0b${str}`; + break; + + case 8: + str = `0o${str}`; + break; + + case 16: + str = `0x${str}`; + break; + } + + const n = BigInt(str); + return sign === '-' ? BigInt(-1) * n : n; + } + + const n = parseInt(str, radix); + return sign === '-' ? -1 * n : n; +} + +function intStringify(node, radix, prefix) { + const { + value + } = node; + + if (intIdentify(value)) { + const str = value.toString(radix); + return value < 0 ? '-' + prefix + str.substr(1) : prefix + str; + } + + return resolveSeq$1.stringifyNumber(node); +} + +const yaml11 = failsafe.concat([{ + identify: value => value == null, + createNode: (schema, value, ctx) => ctx.wrapScalars ? new resolveSeq$1.Scalar(null) : null, + default: true, + tag: 'tag:yaml.org,2002:null', + test: /^(?:~|[Nn]ull|NULL)?$/, + resolve: () => null, + options: resolveSeq$1.nullOptions, + stringify: () => resolveSeq$1.nullOptions.nullStr +}, { + identify: value => typeof value === 'boolean', + default: true, + tag: 'tag:yaml.org,2002:bool', + test: /^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/, + resolve: () => true, + options: resolveSeq$1.boolOptions, + stringify: boolStringify +}, { + identify: value => typeof value === 'boolean', + default: true, + tag: 'tag:yaml.org,2002:bool', + test: /^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/i, + resolve: () => false, + options: resolveSeq$1.boolOptions, + stringify: boolStringify +}, { + identify: intIdentify, + default: true, + tag: 'tag:yaml.org,2002:int', + format: 'BIN', + test: /^([-+]?)0b([0-1_]+)$/, + resolve: (str, sign, bin) => intResolve(sign, bin, 2), + stringify: node => intStringify(node, 2, '0b') +}, { + identify: intIdentify, + default: true, + tag: 'tag:yaml.org,2002:int', + format: 'OCT', + test: /^([-+]?)0([0-7_]+)$/, + resolve: (str, sign, oct) => intResolve(sign, oct, 8), + stringify: node => intStringify(node, 8, '0') +}, { + identify: intIdentify, + default: true, + tag: 'tag:yaml.org,2002:int', + test: /^([-+]?)([0-9][0-9_]*)$/, + resolve: (str, sign, abs) => intResolve(sign, abs, 10), + stringify: resolveSeq$1.stringifyNumber +}, { + identify: intIdentify, + default: true, + tag: 'tag:yaml.org,2002:int', + format: 'HEX', + test: /^([-+]?)0x([0-9a-fA-F_]+)$/, + resolve: (str, sign, hex) => intResolve(sign, hex, 16), + stringify: node => intStringify(node, 16, '0x') +}, { + identify: value => typeof value === 'number', + default: true, + tag: 'tag:yaml.org,2002:float', + test: /^(?:[-+]?\.inf|(\.nan))$/i, + resolve: (str, nan) => nan ? NaN : str[0] === '-' ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, + stringify: resolveSeq$1.stringifyNumber +}, { + identify: value => typeof value === 'number', + default: true, + tag: 'tag:yaml.org,2002:float', + format: 'EXP', + test: /^[-+]?([0-9][0-9_]*)?(\.[0-9_]*)?[eE][-+]?[0-9]+$/, + resolve: str => parseFloat(str.replace(/_/g, '')), + stringify: ({ + value + }) => Number(value).toExponential() +}, { + identify: value => typeof value === 'number', + default: true, + tag: 'tag:yaml.org,2002:float', + test: /^[-+]?(?:[0-9][0-9_]*)?\.([0-9_]*)$/, + + resolve(str, frac) { + const node = new resolveSeq$1.Scalar(parseFloat(str.replace(/_/g, ''))); + + if (frac) { + const f = frac.replace(/_/g, ''); + if (f[f.length - 1] === '0') node.minFractionDigits = f.length; + } + + return node; + }, + + stringify: resolveSeq$1.stringifyNumber +}], warnings$1.binary, warnings$1.omap, warnings$1.pairs, warnings$1.set, warnings$1.intTime, warnings$1.floatTime, warnings$1.timestamp); + +const schemas = { + core, + failsafe, + json, + yaml11 +}; +const tags = { + binary: warnings$1.binary, + bool: boolObj, + float: floatObj, + floatExp: expObj, + floatNaN: nanObj, + floatTime: warnings$1.floatTime, + int: intObj, + intHex: hexObj, + intOct: octObj, + intTime: warnings$1.intTime, + map: map$2, + null: nullObj, + omap: warnings$1.omap, + pairs: warnings$1.pairs, + seq, + set: warnings$1.set, + timestamp: warnings$1.timestamp +}; + +function findTagObject(value, tagName, tags) { + if (tagName) { + const match = tags.filter(t => t.tag === tagName); + const tagObj = match.find(t => !t.format) || match[0]; + if (!tagObj) throw new Error(`Tag ${tagName} not found`); + return tagObj; + } // TODO: deprecate/remove class check + + + return tags.find(t => (t.identify && t.identify(value) || t.class && value instanceof t.class) && !t.format); +} + +function createNode$1(value, tagName, ctx) { + if (value instanceof resolveSeq$1.Node) return value; + const { + defaultPrefix, + onTagObj, + prevObjects, + schema, + wrapScalars + } = ctx; + if (tagName && tagName.startsWith('!!')) tagName = defaultPrefix + tagName.slice(2); + let tagObj = findTagObject(value, tagName, schema.tags); + + if (!tagObj) { + if (typeof value.toJSON === 'function') value = value.toJSON(); + if (!value || typeof value !== 'object') return wrapScalars ? new resolveSeq$1.Scalar(value) : value; + tagObj = value instanceof Map ? map$2 : value[Symbol.iterator] ? seq : map$2; + } + + if (onTagObj) { + onTagObj(tagObj); + delete ctx.onTagObj; + } // Detect duplicate references to the same object & use Alias nodes for all + // after first. The `obj` wrapper allows for circular references to resolve. + + + const obj = { + value: undefined, + node: undefined + }; + + if (value && typeof value === 'object' && prevObjects) { + const prev = prevObjects.get(value); + + if (prev) { + const alias = new resolveSeq$1.Alias(prev); // leaves source dirty; must be cleaned by caller + + ctx.aliasNodes.push(alias); // defined along with prevObjects + + return alias; + } + + obj.value = value; + prevObjects.set(value, obj); + } + + obj.node = tagObj.createNode ? tagObj.createNode(ctx.schema, value, ctx) : wrapScalars ? new resolveSeq$1.Scalar(value) : value; + if (tagName && obj.node instanceof resolveSeq$1.Node) obj.node.tag = tagName; + return obj.node; +} + +function getSchemaTags(schemas, knownTags, customTags, schemaId) { + let tags = schemas[schemaId.replace(/\W/g, '')]; // 'yaml-1.1' -> 'yaml11' + + if (!tags) { + const keys = Object.keys(schemas).map(key => JSON.stringify(key)).join(', '); + throw new Error(`Unknown schema "${schemaId}"; use one of ${keys}`); + } + + if (Array.isArray(customTags)) { + for (const tag of customTags) tags = tags.concat(tag); + } else if (typeof customTags === 'function') { + tags = customTags(tags.slice()); + } + + for (let i = 0; i < tags.length; ++i) { + const tag = tags[i]; + + if (typeof tag === 'string') { + const tagObj = knownTags[tag]; + + if (!tagObj) { + const keys = Object.keys(knownTags).map(key => JSON.stringify(key)).join(', '); + throw new Error(`Unknown custom tag "${tag}"; use one of ${keys}`); + } + + tags[i] = tagObj; + } + } + + return tags; +} + +const sortMapEntriesByKey = (a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0; + +let Schema$2 = class Schema { + // TODO: remove in v2 + // TODO: remove in v2 + constructor({ + customTags, + merge, + schema, + sortMapEntries, + tags: deprecatedCustomTags + }) { + this.merge = !!merge; + this.name = schema; + this.sortMapEntries = sortMapEntries === true ? sortMapEntriesByKey : sortMapEntries || null; + if (!customTags && deprecatedCustomTags) warnings$1.warnOptionDeprecation('tags', 'customTags'); + this.tags = getSchemaTags(schemas, tags, customTags || deprecatedCustomTags, schema); + } + + createNode(value, wrapScalars, tagName, ctx) { + const baseCtx = { + defaultPrefix: Schema.defaultPrefix, + schema: this, + wrapScalars + }; + const createCtx = ctx ? Object.assign(ctx, baseCtx) : baseCtx; + return createNode$1(value, tagName, createCtx); + } + + createPair(key, value, ctx) { + if (!ctx) ctx = { + wrapScalars: true + }; + const k = this.createNode(key, ctx.wrapScalars, null, ctx); + const v = this.createNode(value, ctx.wrapScalars, null, ctx); + return new resolveSeq$1.Pair(k, v); + } + +}; + +PlainValue$2._defineProperty(Schema$2, "defaultPrefix", PlainValue$2.defaultTagPrefix); + +PlainValue$2._defineProperty(Schema$2, "defaultTags", PlainValue$2.defaultTags); + +Schema88e323a7.Schema = Schema$2; + +var PlainValue$1 = PlainValueEc8e588e; +var resolveSeq = resolveSeqD03cb037; +var Schema$1 = Schema88e323a7; + +const defaultOptions$1 = { + anchorPrefix: 'a', + customTags: null, + indent: 2, + indentSeq: true, + keepCstNodes: false, + keepNodeTypes: true, + keepBlobsInJSON: true, + mapAsMap: false, + maxAliasCount: 100, + prettyErrors: false, + // TODO Set true in v2 + simpleKeys: false, + version: '1.2' +}; +const scalarOptions = { + get binary() { + return resolveSeq.binaryOptions; + }, + + set binary(opt) { + Object.assign(resolveSeq.binaryOptions, opt); + }, + + get bool() { + return resolveSeq.boolOptions; + }, + + set bool(opt) { + Object.assign(resolveSeq.boolOptions, opt); + }, + + get int() { + return resolveSeq.intOptions; + }, + + set int(opt) { + Object.assign(resolveSeq.intOptions, opt); + }, + + get null() { + return resolveSeq.nullOptions; + }, + + set null(opt) { + Object.assign(resolveSeq.nullOptions, opt); + }, + + get str() { + return resolveSeq.strOptions; + }, + + set str(opt) { + Object.assign(resolveSeq.strOptions, opt); + } + +}; +const documentOptions = { + '1.0': { + schema: 'yaml-1.1', + merge: true, + tagPrefixes: [{ + handle: '!', + prefix: PlainValue$1.defaultTagPrefix + }, { + handle: '!!', + prefix: 'tag:private.yaml.org,2002:' + }] + }, + 1.1: { + schema: 'yaml-1.1', + merge: true, + tagPrefixes: [{ + handle: '!', + prefix: '!' + }, { + handle: '!!', + prefix: PlainValue$1.defaultTagPrefix + }] + }, + 1.2: { + schema: 'core', + merge: false, + tagPrefixes: [{ + handle: '!', + prefix: '!' + }, { + handle: '!!', + prefix: PlainValue$1.defaultTagPrefix + }] + } +}; + +function stringifyTag(doc, tag) { + if ((doc.version || doc.options.version) === '1.0') { + const priv = tag.match(/^tag:private\.yaml\.org,2002:([^:/]+)$/); + if (priv) return '!' + priv[1]; + const vocab = tag.match(/^tag:([a-zA-Z0-9-]+)\.yaml\.org,2002:(.*)/); + return vocab ? `!${vocab[1]}/${vocab[2]}` : `!${tag.replace(/^tag:/, '')}`; + } + + let p = doc.tagPrefixes.find(p => tag.indexOf(p.prefix) === 0); + + if (!p) { + const dtp = doc.getDefaults().tagPrefixes; + p = dtp && dtp.find(p => tag.indexOf(p.prefix) === 0); + } + + if (!p) return tag[0] === '!' ? tag : `!<${tag}>`; + const suffix = tag.substr(p.prefix.length).replace(/[!,[\]{}]/g, ch => ({ + '!': '%21', + ',': '%2C', + '[': '%5B', + ']': '%5D', + '{': '%7B', + '}': '%7D' + })[ch]); + return p.handle + suffix; +} + +function getTagObject(tags, item) { + if (item instanceof resolveSeq.Alias) return resolveSeq.Alias; + + if (item.tag) { + const match = tags.filter(t => t.tag === item.tag); + if (match.length > 0) return match.find(t => t.format === item.format) || match[0]; + } + + let tagObj, obj; + + if (item instanceof resolveSeq.Scalar) { + obj = item.value; // TODO: deprecate/remove class check + + const match = tags.filter(t => t.identify && t.identify(obj) || t.class && obj instanceof t.class); + tagObj = match.find(t => t.format === item.format) || match.find(t => !t.format); + } else { + obj = item; + tagObj = tags.find(t => t.nodeClass && obj instanceof t.nodeClass); + } + + if (!tagObj) { + const name = obj && obj.constructor ? obj.constructor.name : typeof obj; + throw new Error(`Tag not resolved for ${name} value`); + } + + return tagObj; +} // needs to be called before value stringifier to allow for circular anchor refs + + +function stringifyProps(node, tagObj, { + anchors, + doc +}) { + const props = []; + const anchor = doc.anchors.getName(node); + + if (anchor) { + anchors[anchor] = node; + props.push(`&${anchor}`); + } + + if (node.tag) { + props.push(stringifyTag(doc, node.tag)); + } else if (!tagObj.default) { + props.push(stringifyTag(doc, tagObj.tag)); + } + + return props.join(' '); +} + +function stringify$2(item, ctx, onComment, onChompKeep) { + const { + anchors, + schema + } = ctx.doc; + let tagObj; + + if (!(item instanceof resolveSeq.Node)) { + const createCtx = { + aliasNodes: [], + onTagObj: o => tagObj = o, + prevObjects: new Map() + }; + item = schema.createNode(item, true, null, createCtx); + + for (const alias of createCtx.aliasNodes) { + alias.source = alias.source.node; + let name = anchors.getName(alias.source); + + if (!name) { + name = anchors.newName(); + anchors.map[name] = alias.source; + } + } + } + + if (item instanceof resolveSeq.Pair) return item.toString(ctx, onComment, onChompKeep); + if (!tagObj) tagObj = getTagObject(schema.tags, item); + const props = stringifyProps(item, tagObj, ctx); + if (props.length > 0) ctx.indentAtStart = (ctx.indentAtStart || 0) + props.length + 1; + const str = typeof tagObj.stringify === 'function' ? tagObj.stringify(item, ctx, onComment, onChompKeep) : item instanceof resolveSeq.Scalar ? resolveSeq.stringifyString(item, ctx, onComment, onChompKeep) : item.toString(ctx, onComment, onChompKeep); + if (!props) return str; + return item instanceof resolveSeq.Scalar || str[0] === '{' || str[0] === '[' ? `${props} ${str}` : `${props}\n${ctx.indent}${str}`; +} + +class Anchors { + static validAnchorNode(node) { + return node instanceof resolveSeq.Scalar || node instanceof resolveSeq.YAMLSeq || node instanceof resolveSeq.YAMLMap; + } + + constructor(prefix) { + PlainValue$1._defineProperty(this, "map", Object.create(null)); + + this.prefix = prefix; + } + + createAlias(node, name) { + this.setAnchor(node, name); + return new resolveSeq.Alias(node); + } + + createMergePair(...sources) { + const merge = new resolveSeq.Merge(); + merge.value.items = sources.map(s => { + if (s instanceof resolveSeq.Alias) { + if (s.source instanceof resolveSeq.YAMLMap) return s; + } else if (s instanceof resolveSeq.YAMLMap) { + return this.createAlias(s); + } + + throw new Error('Merge sources must be Map nodes or their Aliases'); + }); + return merge; + } + + getName(node) { + const { + map + } = this; + return Object.keys(map).find(a => map[a] === node); + } + + getNames() { + return Object.keys(this.map); + } + + getNode(name) { + return this.map[name]; + } + + newName(prefix) { + if (!prefix) prefix = this.prefix; + const names = Object.keys(this.map); + + for (let i = 1; true; ++i) { + const name = `${prefix}${i}`; + if (!names.includes(name)) return name; + } + } // During parsing, map & aliases contain CST nodes + + + resolveNodes() { + const { + map, + _cstAliases + } = this; + Object.keys(map).forEach(a => { + map[a] = map[a].resolved; + }); + + _cstAliases.forEach(a => { + a.source = a.source.resolved; + }); + + delete this._cstAliases; + } + + setAnchor(node, name) { + if (node != null && !Anchors.validAnchorNode(node)) { + throw new Error('Anchors may only be set for Scalar, Seq and Map nodes'); + } + + if (name && /[\x00-\x19\s,[\]{}]/.test(name)) { + throw new Error('Anchor names must not contain whitespace or control characters'); + } + + const { + map + } = this; + const prev = node && Object.keys(map).find(a => map[a] === node); + + if (prev) { + if (!name) { + return prev; + } else if (prev !== name) { + delete map[prev]; + map[name] = node; + } + } else { + if (!name) { + if (!node) return null; + name = this.newName(); + } + + map[name] = node; + } + + return name; + } + +} + +const visit = (node, tags) => { + if (node && typeof node === 'object') { + const { + tag + } = node; + + if (node instanceof resolveSeq.Collection) { + if (tag) tags[tag] = true; + node.items.forEach(n => visit(n, tags)); + } else if (node instanceof resolveSeq.Pair) { + visit(node.key, tags); + visit(node.value, tags); + } else if (node instanceof resolveSeq.Scalar) { + if (tag) tags[tag] = true; + } + } + + return tags; +}; + +const listTagNames = node => Object.keys(visit(node, {})); + +function parseContents(doc, contents) { + const comments = { + before: [], + after: [] + }; + let body = undefined; + let spaceBefore = false; + + for (const node of contents) { + if (node.valueRange) { + if (body !== undefined) { + const msg = 'Document contains trailing content not separated by a ... or --- line'; + doc.errors.push(new PlainValue$1.YAMLSyntaxError(node, msg)); + break; + } + + const res = resolveSeq.resolveNode(doc, node); + + if (spaceBefore) { + res.spaceBefore = true; + spaceBefore = false; + } + + body = res; + } else if (node.comment !== null) { + const cc = body === undefined ? comments.before : comments.after; + cc.push(node.comment); + } else if (node.type === PlainValue$1.Type.BLANK_LINE) { + spaceBefore = true; + + if (body === undefined && comments.before.length > 0 && !doc.commentBefore) { + // space-separated comments at start are parsed as document comments + doc.commentBefore = comments.before.join('\n'); + comments.before = []; + } + } + } + + doc.contents = body || null; + + if (!body) { + doc.comment = comments.before.concat(comments.after).join('\n') || null; + } else { + const cb = comments.before.join('\n'); + + if (cb) { + const cbNode = body instanceof resolveSeq.Collection && body.items[0] ? body.items[0] : body; + cbNode.commentBefore = cbNode.commentBefore ? `${cb}\n${cbNode.commentBefore}` : cb; + } + + doc.comment = comments.after.join('\n') || null; + } +} + +function resolveTagDirective({ + tagPrefixes +}, directive) { + const [handle, prefix] = directive.parameters; + + if (!handle || !prefix) { + const msg = 'Insufficient parameters given for %TAG directive'; + throw new PlainValue$1.YAMLSemanticError(directive, msg); + } + + if (tagPrefixes.some(p => p.handle === handle)) { + const msg = 'The %TAG directive must only be given at most once per handle in the same document.'; + throw new PlainValue$1.YAMLSemanticError(directive, msg); + } + + return { + handle, + prefix + }; +} + +function resolveYamlDirective(doc, directive) { + let [version] = directive.parameters; + if (directive.name === 'YAML:1.0') version = '1.0'; + + if (!version) { + const msg = 'Insufficient parameters given for %YAML directive'; + throw new PlainValue$1.YAMLSemanticError(directive, msg); + } + + if (!documentOptions[version]) { + const v0 = doc.version || doc.options.version; + const msg = `Document will be parsed as YAML ${v0} rather than YAML ${version}`; + doc.warnings.push(new PlainValue$1.YAMLWarning(directive, msg)); + } + + return version; +} + +function parseDirectives(doc, directives, prevDoc) { + const directiveComments = []; + let hasDirectives = false; + + for (const directive of directives) { + const { + comment, + name + } = directive; + + switch (name) { + case 'TAG': + try { + doc.tagPrefixes.push(resolveTagDirective(doc, directive)); + } catch (error) { + doc.errors.push(error); + } + + hasDirectives = true; + break; + + case 'YAML': + case 'YAML:1.0': + if (doc.version) { + const msg = 'The %YAML directive must only be given at most once per document.'; + doc.errors.push(new PlainValue$1.YAMLSemanticError(directive, msg)); + } + + try { + doc.version = resolveYamlDirective(doc, directive); + } catch (error) { + doc.errors.push(error); + } + + hasDirectives = true; + break; + + default: + if (name) { + const msg = `YAML only supports %TAG and %YAML directives, and not %${name}`; + doc.warnings.push(new PlainValue$1.YAMLWarning(directive, msg)); + } + + } + + if (comment) directiveComments.push(comment); + } + + if (prevDoc && !hasDirectives && '1.1' === (doc.version || prevDoc.version || doc.options.version)) { + const copyTagPrefix = ({ + handle, + prefix + }) => ({ + handle, + prefix + }); + + doc.tagPrefixes = prevDoc.tagPrefixes.map(copyTagPrefix); + doc.version = prevDoc.version; + } + + doc.commentBefore = directiveComments.join('\n') || null; +} + +function assertCollection(contents) { + if (contents instanceof resolveSeq.Collection) return true; + throw new Error('Expected a YAML collection as document contents'); +} + +let Document$2 = class Document { + constructor(options) { + this.anchors = new Anchors(options.anchorPrefix); + this.commentBefore = null; + this.comment = null; + this.contents = null; + this.directivesEndMarker = null; + this.errors = []; + this.options = options; + this.schema = null; + this.tagPrefixes = []; + this.version = null; + this.warnings = []; + } + + add(value) { + assertCollection(this.contents); + return this.contents.add(value); + } + + addIn(path, value) { + assertCollection(this.contents); + this.contents.addIn(path, value); + } + + delete(key) { + assertCollection(this.contents); + return this.contents.delete(key); + } + + deleteIn(path) { + if (resolveSeq.isEmptyPath(path)) { + if (this.contents == null) return false; + this.contents = null; + return true; + } + + assertCollection(this.contents); + return this.contents.deleteIn(path); + } + + getDefaults() { + return Document.defaults[this.version] || Document.defaults[this.options.version] || {}; + } + + get(key, keepScalar) { + return this.contents instanceof resolveSeq.Collection ? this.contents.get(key, keepScalar) : undefined; + } + + getIn(path, keepScalar) { + if (resolveSeq.isEmptyPath(path)) return !keepScalar && this.contents instanceof resolveSeq.Scalar ? this.contents.value : this.contents; + return this.contents instanceof resolveSeq.Collection ? this.contents.getIn(path, keepScalar) : undefined; + } + + has(key) { + return this.contents instanceof resolveSeq.Collection ? this.contents.has(key) : false; + } + + hasIn(path) { + if (resolveSeq.isEmptyPath(path)) return this.contents !== undefined; + return this.contents instanceof resolveSeq.Collection ? this.contents.hasIn(path) : false; + } + + set(key, value) { + assertCollection(this.contents); + this.contents.set(key, value); + } + + setIn(path, value) { + if (resolveSeq.isEmptyPath(path)) this.contents = value;else { + assertCollection(this.contents); + this.contents.setIn(path, value); + } + } + + setSchema(id, customTags) { + if (!id && !customTags && this.schema) return; + if (typeof id === 'number') id = id.toFixed(1); + + if (id === '1.0' || id === '1.1' || id === '1.2') { + if (this.version) this.version = id;else this.options.version = id; + delete this.options.schema; + } else if (id && typeof id === 'string') { + this.options.schema = id; + } + + if (Array.isArray(customTags)) this.options.customTags = customTags; + const opt = Object.assign({}, this.getDefaults(), this.options); + this.schema = new Schema$1.Schema(opt); + } + + parse(node, prevDoc) { + if (this.options.keepCstNodes) this.cstNode = node; + if (this.options.keepNodeTypes) this.type = 'DOCUMENT'; + const { + directives = [], + contents = [], + directivesEndMarker, + error, + valueRange + } = node; + + if (error) { + if (!error.source) error.source = this; + this.errors.push(error); + } + + parseDirectives(this, directives, prevDoc); + if (directivesEndMarker) this.directivesEndMarker = true; + this.range = valueRange ? [valueRange.start, valueRange.end] : null; + this.setSchema(); + this.anchors._cstAliases = []; + parseContents(this, contents); + this.anchors.resolveNodes(); + + if (this.options.prettyErrors) { + for (const error of this.errors) if (error instanceof PlainValue$1.YAMLError) error.makePretty(); + + for (const warn of this.warnings) if (warn instanceof PlainValue$1.YAMLError) warn.makePretty(); + } + + return this; + } + + listNonDefaultTags() { + return listTagNames(this.contents).filter(t => t.indexOf(Schema$1.Schema.defaultPrefix) !== 0); + } + + setTagPrefix(handle, prefix) { + if (handle[0] !== '!' || handle[handle.length - 1] !== '!') throw new Error('Handle must start and end with !'); + + if (prefix) { + const prev = this.tagPrefixes.find(p => p.handle === handle); + if (prev) prev.prefix = prefix;else this.tagPrefixes.push({ + handle, + prefix + }); + } else { + this.tagPrefixes = this.tagPrefixes.filter(p => p.handle !== handle); + } + } + + toJSON(arg, onAnchor) { + const { + keepBlobsInJSON, + mapAsMap, + maxAliasCount + } = this.options; + const keep = keepBlobsInJSON && (typeof arg !== 'string' || !(this.contents instanceof resolveSeq.Scalar)); + const ctx = { + doc: this, + indentStep: ' ', + keep, + mapAsMap: keep && !!mapAsMap, + maxAliasCount, + stringify: stringify$2 // Requiring directly in Pair would create circular dependencies + + }; + const anchorNames = Object.keys(this.anchors.map); + if (anchorNames.length > 0) ctx.anchors = new Map(anchorNames.map(name => [this.anchors.map[name], { + alias: [], + aliasCount: 0, + count: 1 + }])); + const res = resolveSeq.toJSON(this.contents, arg, ctx); + if (typeof onAnchor === 'function' && ctx.anchors) for (const { + count, + res + } of ctx.anchors.values()) onAnchor(res, count); + return res; + } + + toString() { + if (this.errors.length > 0) throw new Error('Document with errors cannot be stringified'); + const indentSize = this.options.indent; + + if (!Number.isInteger(indentSize) || indentSize <= 0) { + const s = JSON.stringify(indentSize); + throw new Error(`"indent" option must be a positive integer, not ${s}`); + } + + this.setSchema(); + const lines = []; + let hasDirectives = false; + + if (this.version) { + let vd = '%YAML 1.2'; + + if (this.schema.name === 'yaml-1.1') { + if (this.version === '1.0') vd = '%YAML:1.0';else if (this.version === '1.1') vd = '%YAML 1.1'; + } + + lines.push(vd); + hasDirectives = true; + } + + const tagNames = this.listNonDefaultTags(); + this.tagPrefixes.forEach(({ + handle, + prefix + }) => { + if (tagNames.some(t => t.indexOf(prefix) === 0)) { + lines.push(`%TAG ${handle} ${prefix}`); + hasDirectives = true; + } + }); + if (hasDirectives || this.directivesEndMarker) lines.push('---'); + + if (this.commentBefore) { + if (hasDirectives || !this.directivesEndMarker) lines.unshift(''); + lines.unshift(this.commentBefore.replace(/^/gm, '#')); + } + + const ctx = { + anchors: Object.create(null), + doc: this, + indent: '', + indentStep: ' '.repeat(indentSize), + stringify: stringify$2 // Requiring directly in nodes would create circular dependencies + + }; + let chompKeep = false; + let contentComment = null; + + if (this.contents) { + if (this.contents instanceof resolveSeq.Node) { + if (this.contents.spaceBefore && (hasDirectives || this.directivesEndMarker)) lines.push(''); + if (this.contents.commentBefore) lines.push(this.contents.commentBefore.replace(/^/gm, '#')); // top-level block scalars need to be indented if followed by a comment + + ctx.forceBlockIndent = !!this.comment; + contentComment = this.contents.comment; + } + + const onChompKeep = contentComment ? null : () => chompKeep = true; + const body = stringify$2(this.contents, ctx, () => contentComment = null, onChompKeep); + lines.push(resolveSeq.addComment(body, '', contentComment)); + } else if (this.contents !== undefined) { + lines.push(stringify$2(this.contents, ctx)); + } + + if (this.comment) { + if ((!chompKeep || contentComment) && lines[lines.length - 1] !== '') lines.push(''); + lines.push(this.comment.replace(/^/gm, '#')); + } + + return lines.join('\n') + '\n'; + } + +}; + +PlainValue$1._defineProperty(Document$2, "defaults", documentOptions); + +Document9b4560a1.Document = Document$2; +Document9b4560a1.defaultOptions = defaultOptions$1; +Document9b4560a1.scalarOptions = scalarOptions; + +var parseCst = parseCst$1; +var Document$1 = Document9b4560a1; +var Schema = Schema88e323a7; +var PlainValue = PlainValueEc8e588e; +var warnings = warnings1000a372; + + +function createNode(value, wrapScalars = true, tag) { + if (tag === undefined && typeof wrapScalars === 'string') { + tag = wrapScalars; + wrapScalars = true; + } + + const options = Object.assign({}, Document$1.Document.defaults[Document$1.defaultOptions.version], Document$1.defaultOptions); + const schema = new Schema.Schema(options); + return schema.createNode(value, wrapScalars, tag); +} + +class Document extends Document$1.Document { + constructor(options) { + super(Object.assign({}, Document$1.defaultOptions, options)); + } + +} + +function parseAllDocuments(src, options) { + const stream = []; + let prev; + + for (const cstDoc of parseCst.parse(src)) { + const doc = new Document(options); + doc.parse(cstDoc, prev); + stream.push(doc); + prev = doc; + } + + return stream; +} + +function parseDocument(src, options) { + const cst = parseCst.parse(src); + const doc = new Document(options).parse(cst[0]); + + if (cst.length > 1) { + const errMsg = 'Source contains multiple documents; please use YAML.parseAllDocuments()'; + doc.errors.unshift(new PlainValue.YAMLSemanticError(cst[1], errMsg)); + } + + return doc; +} + +function parse$2(src, options) { + const doc = parseDocument(src, options); + doc.warnings.forEach(warning => warnings.warn(warning)); + if (doc.errors.length > 0) throw doc.errors[0]; + return doc.toJSON(); +} + +function stringify$1(value, options) { + const doc = new Document(options); + doc.contents = value; + return String(doc); +} + +const YAML = { + createNode, + defaultOptions: Document$1.defaultOptions, + Document, + parse: parse$2, + parseAllDocuments, + parseCST: parseCst.parse, + parseDocument, + scalarOptions: Document$1.scalarOptions, + stringify: stringify$1 +}; + +dist.YAML = YAML; + +var yaml$2 = dist.YAML; + +/** +* escapes JSON Pointer using ~0 for ~ and ~1 for / +* @param s the string to escape +* @return the escaped string +*/ +function jpescape$1(s) { + return s.replace(/\~/g, '~0').replace(/\//g, '~1'); +} + +/** +* unescapes JSON Pointer using ~0 for ~ and ~1 for / +* @param s the string to unescape +* @return the unescaped string +*/ +function jpunescape(s) { + return s.replace(/\~1/g, '/').replace(/~0/g, '~'); +} + +// JSON Pointer specification: http://tools.ietf.org/html/rfc6901 + +/** +* from obj, return the property with a JSON Pointer prop, optionally setting it +* to newValue +* @param obj the object to point into +* @param prop the JSON Pointer or JSON Reference +* @param newValue optional value to set the property to +* @return the found property, or false +*/ +function jptr$3(obj, prop, newValue) { + if (typeof obj === 'undefined') return false; + if (!prop || typeof prop !== 'string' || (prop === '#')) return (typeof newValue !== 'undefined' ? newValue : obj); + + if (prop.indexOf('#')>=0) { + let parts = prop.split('#'); + let uri = parts[0]; + if (uri) return false; // we do internal resolution only + prop = parts[1]; + prop = decodeURIComponent(prop.slice(1).split('+').join(' ')); + } + if (prop.startsWith('/')) prop = prop.slice(1); + + let components = prop.split('/'); + for (let i=0;i<components.length;i++) { + components[i] = jpunescape(components[i]); + + let setAndLast = (typeof newValue !== 'undefined') && (i == components.length-1); + + let index = parseInt(components[i],10); + if (!Array.isArray(obj) || isNaN(index) || (index.toString() !== components[i])) { + index = (Array.isArray(obj) && components[i] === '-') ? -2 : -1; + } + else { + components[i] = (i > 0) ? components[i-1] : ''; // backtrack to indexed property name + } + + if ((index != -1) || (obj && obj.hasOwnProperty(components[i]))) { + if (index >= 0) { + if (setAndLast) { + obj[index] = newValue; + } + obj = obj[index]; + } + else if (index === -2) { + if (setAndLast) { + if (Array.isArray(obj)) { + obj.push(newValue); + } + return newValue; + } + else return undefined; + } + else { + if (setAndLast) { + obj[components[i]] = newValue; + } + obj = obj[components[i]]; + } + } + else { + if ((typeof newValue !== 'undefined') && (typeof obj === 'object') && + (!Array.isArray(obj))) { + obj[components[i]] = (setAndLast ? newValue : ((components[i+1] === '0' || components[i+1] === '-') ? [] : {})); + obj = obj[components[i]]; + } + else return false; + } + } + return obj; +} + +var jptr_1 = { + jptr : jptr$3, + jpescape : jpescape$1, + jpunescape : jpunescape +}; + +function isRef$4(obj,key) { + return ((key === '$ref') && (!!obj && typeof obj[key] === 'string')); +} + +var isref = { + isRef: isRef$4 +}; + +/** +* a collection of cloning functions +*/ + +/** +* a no-op placeholder which returns the given object unchanged +* useful for when a clone function needs to be passed but cloning is not +* required +* @param obj the input object +* @return the input object, unchanged +*/ +function nop(obj) { + return obj; +} + +/** +* clones the given object using JSON.parse and JSON.stringify +* @param obj the object to clone +* @return the cloned object +*/ +function clone$6(obj) { + return JSON.parse(JSON.stringify(obj)); +} + +/** +* clones the given object's properties shallowly, ignores properties from prototype +* @param obj the object to clone +* @return the cloned object +*/ +function shallowClone(obj) { + let result = {}; + for (let p in obj) { + if (obj.hasOwnProperty(p)) { + result[p] = obj[p]; + } + } + return result; +} + +/** +* clones the given object's properties deeply, ignores properties from prototype +* @param obj the object to clone +* @return the cloned object +*/ +function deepClone(obj) { + let result = Array.isArray(obj) ? [] : {}; + for (let p in obj) { + if (obj.hasOwnProperty(p) || Array.isArray(obj)) { + result[p] = (typeof obj[p] === 'object') ? deepClone(obj[p]) : obj[p]; + } + } + return result; +} + +/** +* clones the given object's properties shallowly, using Object.assign +* @param obj the object to clone +* @return the cloned object +*/ +function fastClone(obj) { + return Object.assign({},obj); +} + +/** +* Source: stackoverflow http://bit.ly/2A1Kha6 +*/ + +function circularClone(obj, hash) { + if (!hash) hash = new WeakMap(); + // Do not try to clone primitives or functions + if (Object(obj) !== obj || obj instanceof Function) return obj; + if (hash.has(obj)) return hash.get(obj); // Cyclic reference + try { // Try to run constructor (without arguments, as we don't know them) + var result = new obj.constructor(); + } catch(e) { // Constructor failed, create object without running the constructor + result = Object.create(Object.getPrototypeOf(obj)); + } + // Optional: support for some standard constructors (extend as desired) + /*if (obj instanceof Map) + Array.from(obj, ([key, val]) => result.set(circularClone(key, hash), + circularClone(val, hash)) ); + else if (obj instanceof Set) + Array.from(obj, (key) => result.add(circularClone(key, hash)) ); + */ + // Register in hash + hash.set(obj, result); + // Clone and assign enumerable own properties recursively + return Object.assign(result, ...Object.keys(obj).map ( + key => ({ [key]: circularClone(obj[key], hash) }) )); +} + +var clone_1 = { + nop : nop, + clone : clone$6, + shallowClone : shallowClone, + deepClone : deepClone, + fastClone : fastClone, + circularClone : circularClone +}; + +const jpescape = jptr_1.jpescape; + +function defaultState() { + return { + path: '#', + depth: 0, + pkey: '', + parent: {}, + payload: {}, + seen: new WeakMap(), + identity: false, + identityDetection: false + }; +} + +/** +* recurses through the properties of an object, given an optional starting state +* anything you pass in state.payload is passed to the callback each time +* @param object the object to recurse through +* @param state optional starting state, can be set to null or {} +* @param callback the function which receives object,key,state on each property +*/ +function recurse$3(object, state, callback) { + if (!state) state = {depth:0}; + if (!state.depth) { + state = Object.assign({},defaultState(),state); + } + if (typeof object !== 'object') return; + let oPath = state.path; + for (let key in object) { + state.key = key; + state.path = state.path + '/' + encodeURIComponent(jpescape(key)); + state.identityPath = state.seen.get(object[key]); + state.identity = (typeof state.identityPath !== 'undefined'); + if (object.hasOwnProperty(key)) { + callback(object, key, state); + } + if ((typeof object[key] === 'object') && (!state.identity)) { + if (state.identityDetection && !Array.isArray(object[key]) && object[key] !== null) { + state.seen.set(object[key],state.path); + } + let newState = {}; + newState.parent = object; + newState.path = state.path; + newState.depth = state.depth ? state.depth+1 : 1; + newState.pkey = key; + newState.payload = state.payload; + newState.seen = state.seen; + newState.identity = false; + newState.identityDetection = state.identityDetection; + recurse$3(object[key], newState, callback); + } + state.path = oPath; + } +} + +var recurse_1 = { + recurse : recurse$3 +}; + +const recurse$2 = recurse_1.recurse; +const clone$5 = clone_1.shallowClone; +const jptr$2 = jptr_1.jptr; +const isRef$3 = isref.isRef; + +var getLogger = function (options) { + if (options && options.verbose) { + return { + warn: function() { + var args = Array.prototype.slice.call(arguments); + console.warn.apply(console, args); + } + } + } + else { + return { + warn: function() { + //nop + } + } + } +}; + +/** +* dereferences the given object +* @param o the object to dereference +* @definitions a source of definitions to reference +* @options optional settings (used recursively) +* @return the dereferenced object +*/ +function dereference(o,definitions,options) { + if (!options) options = {}; + if (!options.cache) options.cache = {}; + if (!options.state) options.state = {}; + options.state.identityDetection = true; + // options.depth allows us to limit cloning to the first invocation + options.depth = (options.depth ? options.depth+1 : 1); + let obj = (options.depth > 1 ? o : clone$5(o)); + let container = { data: obj }; + let defs = (options.depth > 1 ? definitions : clone$5(definitions)); + // options.master is the top level object, regardless of depth + if (!options.master) options.master = obj; + + let logger = getLogger(options); + + let changes = 1; + while (changes > 0) { + changes = 0; + recurse$2(container,options.state,function(obj,key,state){ + if (isRef$3(obj,key)) { + let $ref = obj[key]; // immutable + changes++; + if (!options.cache[$ref]) { + let entry = {}; + entry.path = state.path.split('/$ref')[0]; + entry.key = $ref; + logger.warn('Dereffing %s at %s',$ref,entry.path); + entry.source = defs; + entry.data = jptr$2(entry.source,entry.key); + if (entry.data === false) { + entry.data = jptr$2(options.master,entry.key); + entry.source = options.master; + } + if (entry.data === false) { + logger.warn('Missing $ref target',entry.key); + } + options.cache[$ref] = entry; + entry.data = state.parent[state.pkey] = dereference(jptr$2(entry.source,entry.key),entry.source,options); + if (options.$ref && (typeof state.parent[state.pkey] === 'object') && (state.parent[state.pkey] !== null)) state.parent[state.pkey][options.$ref] = $ref; + entry.resolved = true; + } + else { + let entry = options.cache[$ref]; + if (entry.resolved) { + // we have already seen and resolved this reference + logger.warn('Patching %s for %s',$ref,entry.path); + state.parent[state.pkey] = entry.data; + if (options.$ref && (typeof state.parent[state.pkey] === 'object') && (state.parent[state.pkey] !== null)) state.parent[state.pkey][options.$ref] = $ref; + } + else if ($ref === entry.path) { + // reference to itself, throw + throw new Error(`Tight circle at ${entry.path}`); + } + else { + // we're dealing with a circular reference here + logger.warn('Unresolved ref'); + state.parent[state.pkey] = jptr$2(entry.source,entry.path); + if (state.parent[state.pkey] === false) { + state.parent[state.pkey] = jptr$2(entry.source,entry.key); + } + if (options.$ref && (typeof state.parent[state.pkey] === 'object') && (state.parent[state.pkey] !== null)) state.parent[options.$ref] = $ref; + } + } + } + }); + } + return container.data; +} + +var dereference_1 = { + dereference : dereference +}; + +var fastSafeStringify = stringify; +stringify.default = stringify; +stringify.stable = deterministicStringify; +stringify.stableStringify = deterministicStringify; + +var LIMIT_REPLACE_NODE = '[...]'; +var CIRCULAR_REPLACE_NODE = '[Circular]'; + +var arr = []; +var replacerStack = []; + +function defaultOptions () { + return { + depthLimit: Number.MAX_SAFE_INTEGER, + edgesLimit: Number.MAX_SAFE_INTEGER + } +} + +// Regular stringify +function stringify (obj, replacer, spacer, options) { + if (typeof options === 'undefined') { + options = defaultOptions(); + } + + decirc(obj, '', 0, [], undefined, 0, options); + var res; + try { + if (replacerStack.length === 0) { + res = JSON.stringify(obj, replacer, spacer); + } else { + res = JSON.stringify(obj, replaceGetterValues(replacer), spacer); + } + } catch (_) { + return JSON.stringify('[unable to serialize, circular reference is too complex to analyze]') + } finally { + while (arr.length !== 0) { + var part = arr.pop(); + if (part.length === 4) { + Object.defineProperty(part[0], part[1], part[3]); + } else { + part[0][part[1]] = part[2]; + } + } + } + return res +} + +function setReplace (replace, val, k, parent) { + var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k); + if (propertyDescriptor.get !== undefined) { + if (propertyDescriptor.configurable) { + Object.defineProperty(parent, k, { value: replace }); + arr.push([parent, k, val, propertyDescriptor]); + } else { + replacerStack.push([val, k, replace]); + } + } else { + parent[k] = replace; + arr.push([parent, k, val]); + } +} + +function decirc (val, k, edgeIndex, stack, parent, depth, options) { + depth += 1; + var i; + if (typeof val === 'object' && val !== null) { + for (i = 0; i < stack.length; i++) { + if (stack[i] === val) { + setReplace(CIRCULAR_REPLACE_NODE, val, k, parent); + return + } + } + + if ( + typeof options.depthLimit !== 'undefined' && + depth > options.depthLimit + ) { + setReplace(LIMIT_REPLACE_NODE, val, k, parent); + return + } + + if ( + typeof options.edgesLimit !== 'undefined' && + edgeIndex + 1 > options.edgesLimit + ) { + setReplace(LIMIT_REPLACE_NODE, val, k, parent); + return + } + + stack.push(val); + // Optimize for Arrays. Big arrays could kill the performance otherwise! + if (Array.isArray(val)) { + for (i = 0; i < val.length; i++) { + decirc(val[i], i, i, stack, val, depth, options); + } + } else { + var keys = Object.keys(val); + for (i = 0; i < keys.length; i++) { + var key = keys[i]; + decirc(val[key], key, i, stack, val, depth, options); + } + } + stack.pop(); + } +} + +// Stable-stringify +function compareFunction (a, b) { + if (a < b) { + return -1 + } + if (a > b) { + return 1 + } + return 0 +} + +function deterministicStringify (obj, replacer, spacer, options) { + if (typeof options === 'undefined') { + options = defaultOptions(); + } + + var tmp = deterministicDecirc(obj, '', 0, [], undefined, 0, options) || obj; + var res; + try { + if (replacerStack.length === 0) { + res = JSON.stringify(tmp, replacer, spacer); + } else { + res = JSON.stringify(tmp, replaceGetterValues(replacer), spacer); + } + } catch (_) { + return JSON.stringify('[unable to serialize, circular reference is too complex to analyze]') + } finally { + // Ensure that we restore the object as it was. + while (arr.length !== 0) { + var part = arr.pop(); + if (part.length === 4) { + Object.defineProperty(part[0], part[1], part[3]); + } else { + part[0][part[1]] = part[2]; + } + } + } + return res +} + +function deterministicDecirc (val, k, edgeIndex, stack, parent, depth, options) { + depth += 1; + var i; + if (typeof val === 'object' && val !== null) { + for (i = 0; i < stack.length; i++) { + if (stack[i] === val) { + setReplace(CIRCULAR_REPLACE_NODE, val, k, parent); + return + } + } + try { + if (typeof val.toJSON === 'function') { + return + } + } catch (_) { + return + } + + if ( + typeof options.depthLimit !== 'undefined' && + depth > options.depthLimit + ) { + setReplace(LIMIT_REPLACE_NODE, val, k, parent); + return + } + + if ( + typeof options.edgesLimit !== 'undefined' && + edgeIndex + 1 > options.edgesLimit + ) { + setReplace(LIMIT_REPLACE_NODE, val, k, parent); + return + } + + stack.push(val); + // Optimize for Arrays. Big arrays could kill the performance otherwise! + if (Array.isArray(val)) { + for (i = 0; i < val.length; i++) { + deterministicDecirc(val[i], i, i, stack, val, depth, options); + } + } else { + // Create a temporary object in the required way + var tmp = {}; + var keys = Object.keys(val).sort(compareFunction); + for (i = 0; i < keys.length; i++) { + var key = keys[i]; + deterministicDecirc(val[key], key, i, stack, val, depth, options); + tmp[key] = val[key]; + } + if (typeof parent !== 'undefined') { + arr.push([parent, k, val]); + parent[k] = tmp; + } else { + return tmp + } + } + stack.pop(); + } +} + +// wraps replacer function to handle values we couldn't replace +// and mark them as replaced value +function replaceGetterValues (replacer) { + replacer = + typeof replacer !== 'undefined' + ? replacer + : function (k, v) { + return v + }; + return function (key, val) { + if (replacerStack.length > 0) { + for (var i = 0; i < replacerStack.length; i++) { + var part = replacerStack[i]; + if (part[1] === key && part[0] === val) { + val = part[2]; + replacerStack.splice(i, 1); + break + } + } + } + return replacer.call(this, key, val) + } +} + +const sjs = fastSafeStringify; + +const colour = process.env.NODE_DISABLE_COLORS ? + { red: '', yellow: '', green: '', normal: '' } : + { red: '\x1b[31m', yellow: '\x1b[33;1m', green: '\x1b[32m', normal: '\x1b[0m' }; + +function uniqueOnly(value, index, self) { + return self.indexOf(value) === index; +} + +function hasDuplicates(array) { + return (new Set(array)).size !== array.length; +} + +function allSame(array) { + return (new Set(array)).size <= 1; +} + +function deepEquals(obj1, obj2) { + function _equals(obj1, obj2) { + return sjs.stringify(obj1) === sjs.stringify(Object.assign({}, obj1, obj2)); + } + return _equals(obj1, obj2) && _equals(obj2, obj1); +} + +function compressArray(arr) { + let result = []; + for (let candidate of arr) { + let dupe = result.find(function(e,i,a){ + return deepEquals(e,candidate); + }); + if (!dupe) result.push(candidate); + } + return result; +} + +function distinctArray(arr) { + return (arr.length === compressArray(arr).length); +} + +function firstDupe(arr) { + return arr.find(function(e,i,a){ + return arr.indexOf(e)<i; + }); +} + +/** + * simple hash implementation based on https://stackoverflow.com/a/7616484/1749888 + * @param {string} s - string to hash + * @returns {number} numerical hash code + */ +function hash(s) { + let hash = 0; + let chr; + if (s.length === 0) return hash; + for (let i = 0; i < s.length; i++) { + chr = s.charCodeAt(i); + hash = ((hash << 5) - hash) + chr; + hash |= 0; // Convert to 32bit integer + } + return hash; +} + +String.prototype.toCamelCase = function camelize() { + return this.toLowerCase().replace(/[-_ \/\.](.)/g, function (match, group1) { + return group1.toUpperCase(); + }); +}; + +const parameterTypeProperties = [ + 'format', + 'minimum', + 'maximum', + 'exclusiveMinimum', + 'exclusiveMaximum', + 'minLength', + 'maxLength', + 'multipleOf', + 'minItems', + 'maxItems', + 'uniqueItems', + 'minProperties', + 'maxProperties', + 'additionalProperties', + 'pattern', + 'enum', + 'default' +]; + +const arrayProperties = [ + 'items', + 'minItems', + 'maxItems', + 'uniqueItems' +]; + +const httpMethods = [ + 'get', + 'post', + 'put', + 'delete', + 'patch', + 'head', + 'options', + 'trace' +]; + +function sanitise(s) { + s = s.replace('[]','Array'); + let components = s.split('/'); + components[0] = components[0].replace(/[^A-Za-z0-9_\-\.]+|\s+/gm, '_'); + return components.join('/'); +} + +function sanitiseAll(s) { + return sanitise(s.split('/').join('_')); +} + +var oasKitCommon = { + + colour: colour, + uniqueOnly: uniqueOnly, + hasDuplicates: hasDuplicates, + allSame: allSame, + distinctArray: distinctArray, + firstDupe: firstDupe, + hash: hash, + parameterTypeProperties: parameterTypeProperties, + arrayProperties: arrayProperties, + httpMethods: httpMethods, + sanitise: sanitise, + sanitiseAll: sanitiseAll + +}; + +const fs$2 = require$$0$8; +const path$1 = require$$0$b; +const url$2 = require$$0$e; + +const fetch$2 = require$$4; +const yaml$1 = yaml$2; + +const jptr$1 = jptr_1.jptr; +const recurse$1 = recurse_1.recurse; +const clone$4 = clone_1.clone; +const deRef = dereference_1.dereference; +const isRef$2 = isref.isRef; +const common$3 = oasKitCommon; + +function unique(arr) { + return [... new Set(arr)]; +} + +function readFileAsync(filename, encoding, options, pointer, def) { + return new Promise(function (resolve, reject) { + fs$2.readFile(filename, encoding, function (err, data) { + if (err) { + if (options.ignoreIOErrors && def) { + if (options.verbose) console.warn('FAILED',pointer); + options.externalRefs[pointer].failed = true; + resolve(def); + } + else { + reject(err); + } + } + else { + resolve(data); + } + }); + }); +} + +function resolveAllFragment(obj, context, src, parentPath, base, options) { + + let attachPoint = options.externalRefs[src+parentPath].paths[0]; + + let baseUrl = url$2.parse(base); + let seen = {}; // seen is indexed by the $ref value and contains path replacements + let changes = 1; + while (changes) { + changes = 0; + recurse$1(obj, {identityDetection:true}, function (obj, key, state) { + if (isRef$2(obj, key)) { + if (obj[key].startsWith('#')) { + if (!seen[obj[key]] && !obj.$fixed) { + let target = clone$4(jptr$1(context, obj[key])); + if (options.verbose>1) console.warn((target === false ? common$3.colour.red : common$3.colour.green)+'Fragment resolution', obj[key], common$3.colour.normal); + /* + ResolutionCase:A is where there is a local reference in an externally + referenced document, and we have not seen it before. The reference + is replaced by a copy of the data pointed to, which may be outside this fragment + but within the context of the external document + */ + if (target === false) { + state.parent[state.pkey] = {}; /* case:A(2) where the resolution fails */ + if (options.fatal) { + let ex = new Error('Fragment $ref resolution failed '+obj[key]); + if (options.promise) options.promise.reject(ex); + else throw ex; + } + } + else { + changes++; + state.parent[state.pkey] = target; + seen[obj[key]] = state.path.replace('/%24ref',''); + } + } + else { + if (!obj.$fixed) { + let newRef = (attachPoint+'/'+seen[obj[key]]).split('/#/').join('/'); + state.parent[state.pkey] = { $ref: newRef, 'x-miro': obj[key], $fixed: true }; + if (options.verbose>1) console.warn('Replacing with',newRef); + changes++; + } + /* + ResolutionCase:B is where there is a local reference in an externally + referenced document, and we have seen this reference before and resolved it. + We create a new object containing the (immutable) $ref string + */ + } + } + else if (baseUrl.protocol) { + let newRef = url$2.resolve(base,obj[key]).toString(); + if (options.verbose>1) console.warn(common$3.colour.yellow+'Rewriting external url ref',obj[key],'as',newRef,common$3.colour.normal); + obj['x-miro'] = obj[key]; + if (options.externalRefs[obj[key]]) { + if (!options.externalRefs[newRef]) { + options.externalRefs[newRef] = options.externalRefs[obj[key]]; + } + options.externalRefs[newRef].failed = options.externalRefs[obj[key]].failed; + } + obj[key] = newRef; + } + else if (!obj['x-miro']) { + let newRef = url$2.resolve(base,obj[key]).toString(); + let failed = false; + if (options.externalRefs[obj[key]]) { + failed = options.externalRefs[obj[key]].failed; + } + if (!failed) { + if (options.verbose>1) console.warn(common$3.colour.yellow+'Rewriting external ref',obj[key],'as',newRef,common$3.colour.normal); + obj['x-miro'] = obj[key]; // we use x-miro as a flag so we don't do this > once + obj[key] = newRef; + } + } + } + }); + } + + recurse$1(obj,{},function(obj,key,state){ + if (isRef$2(obj, key)) { + if (typeof obj.$fixed !== 'undefined') delete obj.$fixed; + } + }); + + if (options.verbose>1) console.warn('Finished fragment resolution'); + return obj; +} + +function filterData(data, options) { + if (!options.filters || !options.filters.length) return data; + for (let filter of options.filters) { + data = filter(data, options); + } + return data; +} + +function testProtocol(input, backup) { + if (input && input.length > 2) return input; + if (backup && backup.length > 2) return backup; + return 'file:'; +} + +function resolveExternal(root, pointer, options, callback) { + var u = url$2.parse(options.source); + var base = options.source.split('\\').join('/').split('/'); + let doc = base.pop(); // drop the actual filename + if (!doc) base.pop(); // in case it ended with a / + let fragment = ''; + let fnComponents = pointer.split('#'); + if (fnComponents.length > 1) { + fragment = '#' + fnComponents[1]; + pointer = fnComponents[0]; + } + base = base.join('/'); + + let u2 = url$2.parse(pointer); + let effectiveProtocol = testProtocol(u2.protocol, u.protocol); + + let target; + if (effectiveProtocol === 'file:') { + target = path$1.resolve(base ? base + '/' : '', pointer); + } + else { + target = url$2.resolve(base ? base + '/' : '', pointer); + } + + if (options.cache[target]) { + if (options.verbose) console.warn('CACHED', target, fragment); + /* + resolutionSource:A this is where we have cached the externally-referenced document from a + file, http or custom handler + */ + let context = clone$4(options.cache[target]); + let data = options.externalRef = context; + if (fragment) { + data = jptr$1(data, fragment); + if (data === false) { + data = {}; // case:A(2) where the resolution fails + if (options.fatal) { + let ex = new Error('Cached $ref resolution failed '+target+fragment); + if (options.promise) options.promise.reject(ex); + else throw ex; + } + } + } + data = resolveAllFragment(data, context, pointer, fragment, target, options); + data = filterData(data, options); + callback(clone$4(data), target, options); + return Promise.resolve(data); + } + + if (options.verbose) console.warn('GET', target, fragment); + + if (options.handlers && options.handlers[effectiveProtocol]) { + return options.handlers[effectiveProtocol](base, pointer, fragment, options) + .then(function (data) { + options.externalRef = data; + data = filterData(data, options); + options.cache[target] = data; + callback(data, target, options); + return data; + }) + .catch(function(ex){ + if (options.verbose) console.warn(ex); + throw ex; + }); + } + else if (effectiveProtocol && effectiveProtocol.startsWith('http')) { + const fetchOptions = Object.assign({}, options.fetchOptions, { agent: options.agent }); + return options.fetch(target, fetchOptions) + .then(function (res) { + if (res.status !== 200) { + if (options.ignoreIOErrors) { + if (options.verbose) console.warn('FAILED',pointer); + options.externalRefs[pointer].failed = true; + return '{"$ref":"'+pointer+'"}'; + } + else { + throw new Error(`Received status code ${res.status}: ${target}`); + } + } + return res.text(); + }) + .then(function (data) { + try { + let context = yaml$1.parse(data, { schema:'core', prettyErrors: true }); + data = options.externalRef = context; + options.cache[target] = clone$4(data); + /* resolutionSource:B, from the network, data is fresh, but we clone it into the cache */ + if (fragment) { + data = jptr$1(data, fragment); + if (data === false) { + data = {}; /* case:B(2) where the resolution fails */ + if (options.fatal) { + let ex = new Error('Remote $ref resolution failed '+target+fragment); + if (options.promise) options.promise.reject(ex); + else throw ex; + } + } + } + data = resolveAllFragment(data, context, pointer, fragment, target, options); + data = filterData(data, options); + } + catch (ex) { + if (options.verbose) console.warn(ex); + if (options.promise && options.fatal) options.promise.reject(ex); + else throw ex; + } + callback(data, target, options); + return data; + }) + .catch(function (err) { + if (options.verbose) console.warn(err); + options.cache[target] = {}; + if (options.promise && options.fatal) options.promise.reject(err); + else throw err; + }); + } + else { + const def = '{"$ref":"'+pointer+'"}'; + return readFileAsync(target, options.encoding || 'utf8', options, pointer, def) + .then(function (data) { + try { + let context = yaml$1.parse(data, { schema:'core', prettyErrors: true }); + data = options.externalRef = context; + /* + resolutionSource:C from a file, data is fresh but we clone it into the cache + */ + options.cache[target] = clone$4(data); + if (fragment) { + data = jptr$1(data, fragment); + if (data === false) { + data = {}; /* case:C(2) where the resolution fails */ + if (options.fatal) { + let ex = new Error('File $ref resolution failed '+target+fragment); + if (options.promise) options.promise.reject(ex); + else throw ex; + } + } + } + data = resolveAllFragment(data, context, pointer, fragment, target, options); + data = filterData(data, options); + } + catch (ex) { + if (options.verbose) console.warn(ex); + if (options.promise && options.fatal) options.promise.reject(ex); + else throw ex; + } + callback(data, target, options); + return data; + }) + .catch(function(err){ + if (options.verbose) console.warn(err); + if (options.promise && options.fatal) options.promise.reject(err); + else throw err; + }); + } +} + +function scanExternalRefs(options) { + return new Promise(function (res, rej) { + + function inner(obj,key,state){ + if (obj[key] && isRef$2(obj[key],'$ref')) { + let $ref = obj[key].$ref; + if (!$ref.startsWith('#')) { // is external + + let $extra = ''; + + if (!refs[$ref]) { + let potential = Object.keys(refs).find(function(e,i,a){ + return $ref.startsWith(e+'/'); + }); + if (potential) { + if (options.verbose) console.warn('Found potential subschema at',potential); + $extra = '/'+($ref.split('#')[1]||'').replace(potential.split('#')[1]||''); + $extra = $extra.split('/undefined').join(''); // FIXME + $ref = potential; + } + } + + if (!refs[$ref]) { + refs[$ref] = { resolved: false, paths: [], extras:{}, description: obj[key].description }; + } + if (refs[$ref].resolved) { + // we've already seen it + if (refs[$ref].failed) ; + else if (options.rewriteRefs) { + let newRef = refs[$ref].resolvedAt; + if (options.verbose>1) console.warn('Rewriting ref', $ref, newRef); + obj[key]['x-miro'] = $ref; + obj[key].$ref = newRef+$extra; // resolutionCase:C (new string) + } + else { + obj[key] = clone$4(refs[$ref].data); // resolutionCase:D (cloned:yes) + } + } + else { + refs[$ref].paths.push(state.path); + refs[$ref].extras[state.path] = $extra; + } + } + } + } + + let refs = options.externalRefs; + + if ((options.resolver.depth>0) && (options.source === options.resolver.base)) { + // we only need to do any of this when called directly on pass #1 + return res(refs); + } + + recurse$1(options.openapi.definitions, {identityDetection: true, path: '#/definitions'}, inner); + recurse$1(options.openapi.components, {identityDetection: true, path: '#/components'}, inner); + recurse$1(options.openapi, {identityDetection: true}, inner); + + res(refs); + }); +} + +function findExternalRefs(options) { + return new Promise(function (res, rej) { + + scanExternalRefs(options) + .then(function (refs) { + for (let ref in refs) { + + if (!refs[ref].resolved) { + let depth = options.resolver.depth; + if (depth>0) depth++; + options.resolver.actions[depth].push(function () { + return resolveExternal(options.openapi, ref, options, function (data, source, options) { + if (!refs[ref].resolved) { + let external = {}; + external.context = refs[ref]; + external.$ref = ref; + external.original = clone$4(data); + external.updated = data; + external.source = source; + options.externals.push(external); + refs[ref].resolved = true; + } + + let localOptions = Object.assign({}, options, { source: '', + resolver: {actions: options.resolver.actions, + depth: options.resolver.actions.length-1, base: options.resolver.base } }); + if (options.patch && refs[ref].description && !data.description && + (typeof data === 'object')) { + data.description = refs[ref].description; + } + refs[ref].data = data; + + // sorting $refs by length causes bugs (due to overlapping regions?) + let pointers = unique(refs[ref].paths); + pointers = pointers.sort(function(a,b){ + const aComp = (a.startsWith('#/components/') || a.startsWith('#/definitions/')); + const bComp = (b.startsWith('#/components/') || b.startsWith('#/definitions/')); + if (aComp && !bComp) return -1; + if (bComp && !aComp) return +1; + return 0; + }); + + for (let ptr of pointers) { + // shared x-ms-examples $refs confuse the fixupRefs heuristic in index.js + if (refs[ref].resolvedAt && (ptr !== refs[ref].resolvedAt) && (ptr.indexOf('x-ms-examples/')<0)) { + if (options.verbose>1) console.warn('Creating pointer to data at', ptr); + jptr$1(options.openapi, ptr, { $ref: refs[ref].resolvedAt+refs[ref].extras[ptr], 'x-miro': ref+refs[ref].extras[ptr] }); // resolutionCase:E (new object) + } + else { + if (refs[ref].resolvedAt) { + if (options.verbose>1) console.warn('Avoiding circular reference'); + } + else { + refs[ref].resolvedAt = ptr; + if (options.verbose>1) console.warn('Creating initial clone of data at', ptr); + } + let cdata = clone$4(data); + jptr$1(options.openapi, ptr, cdata); // resolutionCase:F (cloned:yes) + } + } + if (options.resolver.actions[localOptions.resolver.depth].length === 0) { + //options.resolver.actions[localOptions.resolver.depth].push(function () { return scanExternalRefs(localOptions) }); + options.resolver.actions[localOptions.resolver.depth].push(function () { return findExternalRefs(localOptions) }); // findExternalRefs calls scanExternalRefs + } + }); + }); + } + } + }) + .catch(function(ex){ + if (options.verbose) console.warn(ex); + rej(ex); + }); + + let result = {options:options}; + result.actions = options.resolver.actions[options.resolver.depth]; + res(result); + }); +} + +const serial = funcs => + funcs.reduce((promise, func) => + promise.then(result => func().then(Array.prototype.concat.bind(result))), Promise.resolve([])); + +function loopReferences(options, res, rej) { + options.resolver.actions.push([]); + findExternalRefs(options) + .then(function (data) { + serial(data.actions) + .then(function () { + if (options.resolver.depth>=options.resolver.actions.length) { + console.warn('Ran off the end of resolver actions'); + return res(true); + } else { + options.resolver.depth++; + if (options.resolver.actions[options.resolver.depth].length) { + setTimeout(function () { + loopReferences(data.options, res, rej); + }, 0); + } + else { + if (options.verbose>1) console.warn(common$3.colour.yellow+'Finished external resolution!',common$3.colour.normal); + if (options.resolveInternal) { + if (options.verbose>1) console.warn(common$3.colour.yellow+'Starting internal resolution!',common$3.colour.normal); + options.openapi = deRef(options.openapi,options.original,{verbose:options.verbose-1}); + if (options.verbose>1) console.warn(common$3.colour.yellow+'Finished internal resolution!',common$3.colour.normal); + } + recurse$1(options.openapi,{},function(obj,key,state){ + if (isRef$2(obj, key)) { + if (!options.preserveMiro) delete obj['x-miro']; + } + }); + res(options); + } + } + }) + .catch(function (ex) { + if (options.verbose) console.warn(ex); + rej(ex); + }); + }) + .catch(function(ex){ + if (options.verbose) console.warn(ex); + rej(ex); + }); +} + +function setupOptions(options) { + if (!options.cache) options.cache = {}; + if (!options.fetch) options.fetch = fetch$2; + + if (options.source) { + let srcUrl = url$2.parse(options.source); + if (!srcUrl.protocol || srcUrl.protocol.length <= 2) { // windows drive-letters + options.source = path$1.resolve(options.source); + } + } + + options.externals = []; + options.externalRefs = {}; + options.rewriteRefs = true; + options.resolver = {}; + options.resolver.depth = 0; + options.resolver.base = options.source; + options.resolver.actions = [[]]; +} + +/** compatibility function for swagger2openapi */ +function optionalResolve(options) { + setupOptions(options); + return new Promise(function (res, rej) { + if (options.resolve) + loopReferences(options, res, rej); + else + res(options); + }); +} + +function resolve(openapi,source,options) { + if (!options) options = {}; + options.openapi = openapi; + options.source = source; + options.resolve = true; + setupOptions(options); + return new Promise(function (res, rej) { + loopReferences(options, res, rej); + }); +} + +var oasResolver = { + optionalResolve: optionalResolve, + resolve: resolve +}; + +/** +* functions to walk an OpenAPI schema object and traverse all subschemas +* calling a callback function on each one +*/ + +/** +* obtains the default starting state for the `state` object used +* by walkSchema +* @return the state object suitable for use in walkSchema +*/ +function getDefaultState() { + return { depth: 0, seen: new WeakMap(), top: true, combine: false, allowRefSiblings: false }; +} + +/** +* begins the walk of a schema object +* @param schema the schema object to walk +* @param parent the parent schema, if any. Use empty object if none +* @param state the initial starting state of the walker, usually obtained from `getDefaultState`. Use empty object to auto-initialise +* @param callback a function taking a schema, parent and state to be called on this and all subschemas +* @return the schema object +*/ +function walkSchema(schema, parent, state, callback) { + + if (typeof state.depth === 'undefined') state = getDefaultState(); + if ((schema === null) || (typeof schema === 'undefined')) return schema; + if (typeof schema.$ref !== 'undefined') { + let temp = {$ref:schema.$ref}; + if (state.allowRefSiblings && schema.description) { + temp.description = schema.description; + } + callback(temp,parent,state); + return temp; // all other properties SHALL be ignored + } + + if (state.combine) { + if (schema.allOf && Array.isArray(schema.allOf) && schema.allOf.length === 1) { + schema = Object.assign({},schema.allOf[0],schema); + delete schema.allOf; + } + if (schema.anyOf && Array.isArray(schema.anyOf) && schema.anyOf.length === 1) { + schema = Object.assign({},schema.anyOf[0],schema); + delete schema.anyOf; + } + if (schema.oneOf && Array.isArray(schema.oneOf) && schema.oneOf.length === 1) { + schema = Object.assign({},schema.oneOf[0],schema); + delete schema.oneOf; + } + } + + callback(schema,parent,state); + if (state.seen.has(schema)) { + return schema; + } + //else + if ((typeof schema === 'object') && (schema !== null)) state.seen.set(schema,true); + state.top = false; + state.depth++; + + if (typeof schema.items !== 'undefined') { + state.property = 'items'; + walkSchema(schema.items,schema,state,callback); + } + if (schema.additionalItems) { + if (typeof schema.additionalItems === 'object') { + state.property = 'additionalItems'; + walkSchema(schema.additionalItems,schema,state,callback); + } + } + if (schema.additionalProperties) { + if (typeof schema.additionalProperties === 'object') { + state.property = 'additionalProperties'; + walkSchema(schema.additionalProperties,schema,state,callback); + } + } + if (schema.properties) { + for (let prop in schema.properties) { + let subSchema = schema.properties[prop]; + state.property = 'properties/'+prop; + walkSchema(subSchema,schema,state,callback); + } + } + if (schema.patternProperties) { + for (let prop in schema.patternProperties) { + let subSchema = schema.patternProperties[prop]; + state.property = 'patternProperties/'+prop; + walkSchema(subSchema,schema,state,callback); + } + } + if (schema.allOf) { + for (let index in schema.allOf) { + let subSchema = schema.allOf[index]; + state.property = 'allOf/'+index; + walkSchema(subSchema,schema,state,callback); + } + } + if (schema.anyOf) { + for (let index in schema.anyOf) { + let subSchema = schema.anyOf[index]; + state.property = 'anyOf/'+index; + walkSchema(subSchema,schema,state,callback); + } + } + if (schema.oneOf) { + for (let index in schema.oneOf) { + let subSchema = schema.oneOf[index]; + state.property = 'oneOf/'+index; + walkSchema(subSchema,schema,state,callback); + } + } + if (schema.not) { + state.property = 'not'; + walkSchema(schema.not,schema,state,callback); + } + state.depth--; + return schema; +} + +var oasSchemaWalker = { + getDefaultState: getDefaultState, + walkSchema: walkSchema +}; + +const http = require$$0$a; + +const ours = { + "default": "Default response", + "1XX": "Informational", + "103": "Early hints", // not in Node < 10 + "2XX": "Successful", + "3XX": "Redirection", + "4XX": "Client Error", + "5XX": "Server Error", + "7XX": "Developer Error" // April fools RFC +}; + +var statusCodes$1 = { + statusCodes: Object.assign({},ours,http.STATUS_CODES) +}; + +var name = "swagger2openapi"; +var version$1 = "7.0.8"; +var description = "Convert Swagger 2.0 definitions to OpenApi 3.0 and validate"; +var main$2 = "index.js"; +var bin = { + swagger2openapi: "./swagger2openapi.js", + "oas-validate": "./oas-validate.js", + boast: "./boast.js" +}; +var funding = "https://github.com/Mermade/oas-kit?sponsor=1"; +var scripts = { + test: "mocha" +}; +var browserify = { + transform: [ + [ + "babelify", + { + presets: [ + "es2015" + ] + } + ] + ] +}; +var repository = { + url: "https://github.com/Mermade/oas-kit.git", + type: "git" +}; +var bugs = { + url: "https://github.com/mermade/oas-kit/issues" +}; +var author = "Mike Ralphson <mike.ralphson@gmail.com>"; +var license = "BSD-3-Clause"; +var dependencies = { + "call-me-maybe": "^1.0.1", + "node-fetch": "^2.6.1", + "node-fetch-h2": "^2.3.0", + "node-readfiles": "^0.2.0", + "oas-kit-common": "^1.0.8", + "oas-resolver": "^2.5.6", + "oas-schema-walker": "^1.1.5", + "oas-validator": "^5.0.8", + reftools: "^1.1.9", + yaml: "^1.10.0", + yargs: "^17.0.1" +}; +var keywords = [ + "swagger", + "openapi", + "openapi2", + "openapi3", + "converter", + "conversion", + "validator", + "validation", + "resolver", + "lint", + "linter" +]; +var gitHead = "b1bba3fc5007e96a991bf2a015cf0534ac36b88b"; +var require$$14 = { + name: name, + version: version$1, + description: description, + main: main$2, + bin: bin, + funding: funding, + scripts: scripts, + browserify: browserify, + repository: repository, + bugs: bugs, + author: author, + license: license, + dependencies: dependencies, + keywords: keywords, + gitHead: gitHead +}; + +const fs$1 = require$$0$8; +const url$1 = require$$0$e; + +const maybe = maybe$3; +const fetch$1 = require$$4; +const yaml = yaml$2; + +const jptr = jptr_1; +const resolveInternal = jptr.jptr; +const isRef$1 = isref.isRef; +const clone$3 = clone_1.clone; +const cclone = clone_1.circularClone; +const recurse = recurse_1.recurse; +const resolver = oasResolver; +const sw = oasSchemaWalker; +const common$2 = oasKitCommon; + +const statusCodes = statusCodes$1.statusCodes; + +const ourVersion = require$$14.version; + +// TODO handle specification-extensions with plugins? + +const targetVersion = '3.0.0'; +let componentNames; // initialised in main + +class S2OError extends Error { + constructor(message) { + super(message); + this.name = 'S2OError'; + } +} + +function throwError(message, options) { + let err = new S2OError(message); + err.options = options; + if (options.promise) { + options.promise.reject(err); + } + else { + throw err; + } +} + +function throwOrWarn(message, container, options) { + if (options.warnOnly) { + container[options.warnProperty||'x-s2o-warning'] = message; + } + else { + throwError(message, options); + } +} + +function fixUpSubSchema(schema,parent,options) { + if (schema.nullable) options.patches++; + if (schema.discriminator && typeof schema.discriminator === 'string') { + schema.discriminator = { propertyName: schema.discriminator }; + } + if (schema.items && Array.isArray(schema.items)) { + if (schema.items.length === 0) { + schema.items = {}; + } + else if (schema.items.length === 1) { + schema.items = schema.items[0]; + } + else schema.items = { anyOf: schema.items }; + } + + if (schema.type && Array.isArray(schema.type)) { + if (options.patch) { + options.patches++; + if (schema.type.length === 0) { + delete schema.type; + } + else { + if (!schema.oneOf) schema.oneOf = []; + for (let type of schema.type) { + let newSchema = {}; + if (type === 'null') { + schema.nullable = true; + } + else { + newSchema.type = type; + for (let prop of common$2.arrayProperties) { + if (typeof schema.prop !== 'undefined') { + newSchema[prop] = schema[prop]; + delete schema[prop]; + } + } + } + if (newSchema.type) { + schema.oneOf.push(newSchema); + } + } + delete schema.type; + if (schema.oneOf.length === 0) { + delete schema.oneOf; // means was just null => nullable + } + else if (schema.oneOf.length < 2) { + schema.type = schema.oneOf[0].type; + if (Object.keys(schema.oneOf[0]).length > 1) { + throwOrWarn('Lost properties from oneOf',schema,options); + } + delete schema.oneOf; + } + } + // do not else this + if (schema.type && Array.isArray(schema.type) && schema.type.length === 1) { + schema.type = schema.type[0]; + } + } + else { + throwError('(Patchable) schema type must not be an array', options); + } + } + + if (schema.type && schema.type === 'null') { + delete schema.type; + schema.nullable = true; + } + if ((schema.type === 'array') && (!schema.items)) { + schema.items = {}; + } + if (schema.type === 'file') { + schema.type = 'string'; + schema.format = 'binary'; + } + if (typeof schema.required === 'boolean') { + if (schema.required && schema.name) { + if (typeof parent.required === 'undefined') { + parent.required = []; + } + if (Array.isArray(parent.required)) parent.required.push(schema.name); + } + delete schema.required; + } + + // TODO if we have a nested properties (object inside an object) and the + // *parent* type is not set, force it to object + // TODO if default is set but type is not set, force type to typeof default + + if (schema.xml && typeof schema.xml.namespace === 'string') { + if (!schema.xml.namespace) delete schema.xml.namespace; + } + if (typeof schema.allowEmptyValue !== 'undefined') { + options.patches++; + delete schema.allowEmptyValue; + } +} + +function fixUpSubSchemaExtensions(schema,parent) { + if (schema["x-required"] && Array.isArray(schema["x-required"])) { + if (!schema.required) schema.required = []; + schema.required = schema.required.concat(schema["x-required"]); + delete schema["x-required"]; + } + if (schema["x-anyOf"]) { + schema.anyOf = schema["x-anyOf"]; + delete schema["x-anyOf"]; + } + if (schema["x-oneOf"]) { + schema.oneOf = schema["x-oneOf"]; + delete schema["x-oneOf"]; + } + if (schema["x-not"]) { + schema.not = schema["x-not"]; + delete schema["x-not"]; + } + if (typeof schema["x-nullable"] === 'boolean') { + schema.nullable = schema["x-nullable"]; + delete schema["x-nullable"]; + } + if ((typeof schema["x-discriminator"] === 'object') && (typeof schema["x-discriminator"].propertyName === 'string')) { + schema.discriminator = schema["x-discriminator"]; + delete schema["x-discriminator"]; + for (let entry in schema.discriminator.mapping) { + let schemaOrRef = schema.discriminator.mapping[entry]; + if (schemaOrRef.startsWith('#/definitions/')) { + schema.discriminator.mapping[entry] = schemaOrRef.replace('#/definitions/','#/components/schemas/'); + } + } + } +} + +function fixUpSchema(schema,options) { + sw.walkSchema(schema,{},{},function(schema,parent,state){ + fixUpSubSchemaExtensions(schema); + fixUpSubSchema(schema,parent,options); + }); +} + +function getMiroComponentName(ref) { + if (ref.indexOf('#')>=0) { + ref = ref.split('#')[1].split('/').pop(); + } + else { + ref = ref.split('/').pop().split('.')[0]; + } + return encodeURIComponent(common$2.sanitise(ref)); +} + +function fixupRefs(obj, key, state) { + let options = state.payload.options; + if (isRef$1(obj,key)) { + if (obj[key].startsWith('#/components/')) ; + else if (obj[key] === '#/consumes') { + // people are *so* creative + delete obj[key]; + state.parent[state.pkey] = clone$3(options.openapi.consumes); + } + else if (obj[key] === '#/produces') { + // and by creative, I mean devious + delete obj[key]; + state.parent[state.pkey] = clone$3(options.openapi.produces); + } + else if (obj[key].startsWith('#/definitions/')) { + //only the first part of a schema component name must be sanitised + let keys = obj[key].replace('#/definitions/', '').split('/'); + const ref = jptr.jpunescape(keys[0]); + + let newKey = componentNames.schemas[decodeURIComponent(ref)]; // lookup, resolves a $ref + if (newKey) { + keys[0] = newKey; + } + else { + throwOrWarn('Could not resolve reference '+obj[key],obj,options); + } + obj[key] = '#/components/schemas/' + keys.join('/'); + } + else if (obj[key].startsWith('#/parameters/')) { + // for extensions like Apigee's x-templates + obj[key] = '#/components/parameters/' + common$2.sanitise(obj[key].replace('#/parameters/', '')); + } + else if (obj[key].startsWith('#/responses/')) { + // for extensions like Apigee's x-templates + obj[key] = '#/components/responses/' + common$2.sanitise(obj[key].replace('#/responses/', '')); + } + else if (obj[key].startsWith('#')) { + // fixes up direct $refs or those created by resolvers + let target = clone$3(jptr.jptr(options.openapi,obj[key])); + if (target === false) throwOrWarn('direct $ref not found '+obj[key],obj,options); + else if (options.refmap[obj[key]]) { + obj[key] = options.refmap[obj[key]]; + } + else { + // we use a heuristic to determine what kind of thing is being referenced + let oldRef = obj[key]; + oldRef = oldRef.replace('/properties/headers/',''); + oldRef = oldRef.replace('/properties/responses/',''); + oldRef = oldRef.replace('/properties/parameters/',''); + oldRef = oldRef.replace('/properties/schemas/',''); + let type = 'schemas'; + let schemaIndex = oldRef.lastIndexOf('/schema'); + type = (oldRef.indexOf('/headers/')>schemaIndex) ? 'headers' : + ((oldRef.indexOf('/responses/')>schemaIndex) ? 'responses' : + ((oldRef.indexOf('/example')>schemaIndex) ? 'examples' : + ((oldRef.indexOf('/x-')>schemaIndex) ? 'extensions' : + ((oldRef.indexOf('/parameters/')>schemaIndex) ? 'parameters' : 'schemas')))); + + // non-body/form parameters have not moved in the overall structure (like responses) + // but extracting the requestBodies can cause the *number* of parameters to change + + if (type === 'schemas') { + fixUpSchema(target,options); + } + + if ((type !== 'responses') && (type !== 'extensions')) { + let prefix = type.substr(0,type.length-1); + if ((prefix === 'parameter') && target.name && (target.name === common$2.sanitise(target.name))) { + prefix = encodeURIComponent(target.name); + } + + let suffix = 1; + if (obj['x-miro']) { + prefix = getMiroComponentName(obj['x-miro']); + suffix = ''; + } + + while (jptr.jptr(options.openapi,'#/components/'+type+'/'+prefix+suffix)) { + suffix = (suffix === '' ? 2 : ++suffix); + } + + let newRef = '#/components/'+type+'/'+prefix+suffix; + let refSuffix = ''; + + if (type === 'examples') { + target = { value: target }; + refSuffix = '/value'; + } + + jptr.jptr(options.openapi,newRef,target); + options.refmap[obj[key]] = newRef+refSuffix; + obj[key] = newRef+refSuffix; + } + } + } + + delete obj['x-miro']; + // do this last - rework cases where $ref object has sibling properties + if (Object.keys(obj).length > 1) { + const tmpRef = obj[key]; + const inSchema = state.path.indexOf('/schema') >= 0; // not perfect, but in the absence of a reasonably-sized and complete OAS 2.0 parser... + if (options.refSiblings === 'preserve') ; + else if (inSchema && (options.refSiblings === 'allOf')) { + delete obj.$ref; + state.parent[state.pkey] = { allOf: [ { $ref: tmpRef }, obj ]}; + } + else { // remove, or not 'preserve' and not in a schema + state.parent[state.pkey] = { $ref: tmpRef }; + } + } + + } + if ((key === 'x-ms-odata') && (typeof obj[key] === 'string') && (obj[key].startsWith('#/'))) { + let keys = obj[key].replace('#/definitions/', '').replace('#/components/schemas/','').split('/'); + let newKey = componentNames.schemas[decodeURIComponent(keys[0])]; // lookup, resolves a $ref + if (newKey) { + keys[0] = newKey; + } + else { + throwOrWarn('Could not resolve reference '+obj[key],obj,options); + } + obj[key] = '#/components/schemas/' + keys.join('/'); + } +} + +/* +* This has to happen as a separate pass because multiple $refs may point +* through elements of the same path +*/ +function dedupeRefs(openapi, options) { + for (let ref in options.refmap) { + jptr.jptr(openapi,ref,{ $ref: options.refmap[ref] }); + } +} + +function processSecurity(securityObject) { + for (let s in securityObject) { + for (let k in securityObject[s]) { + let sname = common$2.sanitise(k); + if (k !== sname) { + securityObject[s][sname] = securityObject[s][k]; + delete securityObject[s][k]; + } + } + } +} + +function processSecurityScheme(scheme, options) { + if (scheme.type === 'basic') { + scheme.type = 'http'; + scheme.scheme = 'basic'; + } + if (scheme.type === 'oauth2') { + let flow = {}; + let flowName = scheme.flow; + if (scheme.flow === 'application') flowName = 'clientCredentials'; + if (scheme.flow === 'accessCode') flowName = 'authorizationCode'; + if (typeof scheme.authorizationUrl !== 'undefined') flow.authorizationUrl = scheme.authorizationUrl.split('?')[0].trim() || '/'; + if (typeof scheme.tokenUrl === 'string') flow.tokenUrl = scheme.tokenUrl.split('?')[0].trim() || '/'; + flow.scopes = scheme.scopes || {}; + scheme.flows = {}; + scheme.flows[flowName] = flow; + delete scheme.flow; + delete scheme.authorizationUrl; + delete scheme.tokenUrl; + delete scheme.scopes; + if (typeof scheme.name !== 'undefined') { + if (options.patch) { + options.patches++; + delete scheme.name; + } + else { + throwError('(Patchable) oauth2 securitySchemes should not have name property', options); + } + } + } +} + +function keepParameters(value) { + return (value && !value["x-s2o-delete"]); +} + +function processHeader(header, options) { + if (header.$ref) { + header.$ref = header.$ref.replace('#/responses/', '#/components/responses/'); + } + else { + if (header.type && !header.schema) { + header.schema = {}; + } + if (header.type) header.schema.type = header.type; + if (header.items && header.items.type !== 'array') { + if (header.items.collectionFormat !== header.collectionFormat) { + throwOrWarn('Nested collectionFormats are not supported', header, options); + } + delete header.items.collectionFormat; + } + if (header.type === 'array') { + if (header.collectionFormat === 'ssv') { + throwOrWarn('collectionFormat:ssv is no longer supported for headers', header, options); // not lossless + } + else if (header.collectionFormat === 'pipes') { + throwOrWarn('collectionFormat:pipes is no longer supported for headers', header, options); // not lossless + } + else if (header.collectionFormat === 'multi') { + header.explode = true; + } + else if (header.collectionFormat === 'tsv') { + throwOrWarn('collectionFormat:tsv is no longer supported', header, options); // not lossless + header["x-collectionFormat"] = 'tsv'; + } + else { // 'csv' + header.style = 'simple'; + } + delete header.collectionFormat; + } + else if (header.collectionFormat) { + if (options.patch) { + options.patches++; + delete header.collectionFormat; + } + else { + throwError('(Patchable) collectionFormat is only applicable to header.type array', options); + } + } + delete header.type; + for (let prop of common$2.parameterTypeProperties) { + if (typeof header[prop] !== 'undefined') { + header.schema[prop] = header[prop]; + delete header[prop]; + } + } + for (let prop of common$2.arrayProperties) { + if (typeof header[prop] !== 'undefined') { + header.schema[prop] = header[prop]; + delete header[prop]; + } + } + } +} + +function fixParamRef(param, options) { + if (param.$ref.indexOf('#/parameters/') >= 0) { + let refComponents = param.$ref.split('#/parameters/'); + param.$ref = refComponents[0] + '#/components/parameters/' + common$2.sanitise(refComponents[1]); + } + if (param.$ref.indexOf('#/definitions/') >= 0) { + throwOrWarn('Definition used as parameter', param, options); + } +} + +function attachRequestBody(op,options) { + let newOp = {}; + for (let key of Object.keys(op)) { + newOp[key] = op[key]; + if (key === 'parameters') { + newOp.requestBody = {}; + if (options.rbname) newOp[options.rbname] = ''; + } + } + newOp.requestBody = {}; // just in case there are no parameters + return newOp; +} + +/** + * @returns op, as it may have changed + */ +function processParameter(param, op, path, method, index, openapi, options) { + let result = {}; + let singularRequestBody = true; + let originalType; + + if (op && op.consumes && (typeof op.consumes === 'string')) { + if (options.patch) { + options.patches++; + op.consumes = [op.consumes]; + } + else { + return throwError('(Patchable) operation.consumes must be an array', options); + } + } + if (!Array.isArray(openapi.consumes)) delete openapi.consumes; + let consumes = ((op ? op.consumes : null) || (openapi.consumes || [])).filter(common$2.uniqueOnly); + + if (param && param.$ref && (typeof param.$ref === 'string')) { + // if we still have a ref here, it must be an internal one + fixParamRef(param, options); + let ptr = decodeURIComponent(param.$ref.replace('#/components/parameters/', '')); + let rbody = false; + let target = openapi.components.parameters[ptr]; // resolves a $ref, must have been sanitised already + + if (((!target) || (target["x-s2o-delete"])) && param.$ref.startsWith('#/')) { + // if it's gone, chances are it's a requestBody component now unless spec was broken + param["x-s2o-delete"] = true; + rbody = true; + } + + // shared formData parameters from swagger or path level could be used in any combination. + // we dereference all op.requestBody's then hash them and pull out common ones later + + if (rbody) { + let ref = param.$ref; + let newParam = resolveInternal(openapi, param.$ref); + if (!newParam && ref.startsWith('#/')) { + throwOrWarn('Could not resolve reference ' + ref, param, options); + } + else { + if (newParam) param = newParam; // preserve reference + } + } + } + + if (param && (param.name || param.in)) { // if it's a real parameter OR we've dereferenced it + + if (typeof param['x-deprecated'] === 'boolean') { + param.deprecated = param['x-deprecated']; + delete param['x-deprecated']; + } + + if (typeof param['x-example'] !== 'undefined') { + param.example = param['x-example']; + delete param['x-example']; + } + + if ((param.in !== 'body') && (!param.type)) { + if (options.patch) { + options.patches++; + param.type = 'string'; + } + else { + throwError('(Patchable) parameter.type is mandatory for non-body parameters', options); + } + } + if (param.type && typeof param.type === 'object' && param.type.$ref) { + // $ref anywhere sensibility + param.type = resolveInternal(openapi, param.type.$ref); + } + if (param.type === 'file') { + param['x-s2o-originalType'] = param.type; + originalType = param.type; + } + if (param.description && typeof param.description === 'object' && param.description.$ref) { + // $ref anywhere sensibility + param.description = resolveInternal(openapi, param.description.$ref); + } + if (param.description === null) delete param.description; + + let oldCollectionFormat = param.collectionFormat; + if ((param.type === 'array') && !oldCollectionFormat) { + oldCollectionFormat = 'csv'; + } + if (oldCollectionFormat) { + if (param.type !== 'array') { + if (options.patch) { + options.patches++; + delete param.collectionFormat; + } + else { + throwError('(Patchable) collectionFormat is only applicable to param.type array', options); + } + } + if ((oldCollectionFormat === 'csv') && ((param.in === 'query') || (param.in === 'cookie'))) { + param.style = 'form'; + param.explode = false; + } + if ((oldCollectionFormat === 'csv') && ((param.in === 'path') || (param.in === 'header'))) { + param.style = 'simple'; + } + if (oldCollectionFormat === 'ssv') { + if (param.in === 'query') { + param.style = 'spaceDelimited'; + } + else { + throwOrWarn('collectionFormat:ssv is no longer supported except for in:query parameters', param, options); // not lossless + } + } + if (oldCollectionFormat === 'pipes') { + if (param.in === 'query') { + param.style = 'pipeDelimited'; + } + else { + throwOrWarn('collectionFormat:pipes is no longer supported except for in:query parameters', param, options); // not lossless + } + } + if (oldCollectionFormat === 'multi') { + param.explode = true; + } + if (oldCollectionFormat === 'tsv') { + throwOrWarn('collectionFormat:tsv is no longer supported', param, options); // not lossless + param["x-collectionFormat"] = 'tsv'; + } + delete param.collectionFormat; + } + + if (param.type && (param.type !== 'body') && (param.in !== 'formData')) { + if (param.items && param.schema) { + throwOrWarn('parameter has array,items and schema', param, options); + } + else { + if (param.schema) options.patches++; // already present + if ((!param.schema) || (typeof param.schema !== 'object')) param.schema = {}; + param.schema.type = param.type; + if (param.items) { + param.schema.items = param.items; + delete param.items; + recurse(param.schema.items, null, function (obj, key, state) { + if ((key === 'collectionFormat') && (typeof obj[key] === 'string')) { + if (oldCollectionFormat && obj[key] !== oldCollectionFormat) { + throwOrWarn('Nested collectionFormats are not supported', param, options); + } + delete obj[key]; // not lossless + } + // items in 2.0 was a subset of the JSON-Schema items + // object, it gets fixed up below + }); + } + for (let prop of common$2.parameterTypeProperties) { + if (typeof param[prop] !== 'undefined') param.schema[prop] = param[prop]; + delete param[prop]; + } + } + } + + if (param.schema) { + fixUpSchema(param.schema,options); + } + + if (param["x-ms-skip-url-encoding"]) { + if (param.in === 'query') { // might be in:path, not allowed in OAS3 + param.allowReserved = true; + delete param["x-ms-skip-url-encoding"]; + } + } + } + + if (param && param.in === 'formData') { + // convert to requestBody component + singularRequestBody = false; + result.content = {}; + let contentType = 'application/x-www-form-urlencoded'; + if ((consumes.length) && (consumes.indexOf('multipart/form-data') >= 0)) { + contentType = 'multipart/form-data'; + } + + result.content[contentType] = {}; + if (param.schema) { + result.content[contentType].schema = param.schema; + if (param.schema.$ref) { + result['x-s2o-name'] = decodeURIComponent(param.schema.$ref.replace('#/components/schemas/', '')); + } + } + else { + result.content[contentType].schema = {}; + result.content[contentType].schema.type = 'object'; + result.content[contentType].schema.properties = {}; + result.content[contentType].schema.properties[param.name] = {}; + let schema = result.content[contentType].schema; + let target = result.content[contentType].schema.properties[param.name]; + if (param.description) target.description = param.description; + if (param.example) target.example = param.example; + if (param.type) target.type = param.type; + + for (let prop of common$2.parameterTypeProperties) { + if (typeof param[prop] !== 'undefined') target[prop] = param[prop]; + } + if (param.required === true) { + if (!schema.required) schema.required = []; + schema.required.push(param.name); + result.required = true; + } + if (typeof param.default !== 'undefined') target.default = param.default; + if (target.properties) target.properties = param.properties; + if (param.allOf) target.allOf = param.allOf; // new are anyOf, oneOf, not + if ((param.type === 'array') && (param.items)) { + target.items = param.items; + if (target.items.collectionFormat) delete target.items.collectionFormat; + } + if ((originalType === 'file') || (param['x-s2o-originalType'] === 'file')) { + target.type = 'string'; + target.format = 'binary'; + } + + // Copy any extensions on the form param to the target schema property. + copyExtensions(param, target); + } + } + else if (param && (param.type === 'file')) { + // convert to requestBody + if (param.required) result.required = param.required; + result.content = {}; + result.content["application/octet-stream"] = {}; + result.content["application/octet-stream"].schema = {}; + result.content["application/octet-stream"].schema.type = 'string'; + result.content["application/octet-stream"].schema.format = 'binary'; + copyExtensions(param, result); + } + if (param && param.in === 'body') { + result.content = {}; + if (param.name) result['x-s2o-name'] = (op && op.operationId ? common$2.sanitiseAll(op.operationId) : '') + ('_' + param.name).toCamelCase(); + if (param.description) result.description = param.description; + if (param.required) result.required = param.required; + + // Set the "request body name" extension on the operation if requested. + if (op && options.rbname && param.name) { + op[options.rbname] = param.name; + } + if (param.schema && param.schema.$ref) { + result['x-s2o-name'] = decodeURIComponent(param.schema.$ref.replace('#/components/schemas/', '')); + } + else if (param.schema && (param.schema.type === 'array') && param.schema.items && param.schema.items.$ref) { + result['x-s2o-name'] = decodeURIComponent(param.schema.items.$ref.replace('#/components/schemas/', '')) + 'Array'; + } + + if (!consumes.length) { + consumes.push('application/json'); // TODO verify default + } + + for (let mimetype of consumes) { + result.content[mimetype] = {}; + result.content[mimetype].schema = clone$3(param.schema || {}); + fixUpSchema(result.content[mimetype].schema,options); + } + + // Copy any extensions from the original parameter to the new requestBody + copyExtensions(param, result); + } + + if (Object.keys(result).length > 0) { + param["x-s2o-delete"] = true; + // work out where to attach the requestBody + if (op) { + if (op.requestBody && singularRequestBody) { + op.requestBody["x-s2o-overloaded"] = true; + let opId = op.operationId || index; + + throwOrWarn('Operation ' + opId + ' has multiple requestBodies', op, options); + } + else { + if (!op.requestBody) { + op = path[method] = attachRequestBody(op,options); // make sure we have one + } + if ((op.requestBody.content && op.requestBody.content["multipart/form-data"]) + && (op.requestBody.content["multipart/form-data"].schema) && (op.requestBody.content["multipart/form-data"].schema.properties) && (result.content["multipart/form-data"]) && (result.content["multipart/form-data"].schema) && (result.content["multipart/form-data"].schema.properties)) { + op.requestBody.content["multipart/form-data"].schema.properties = + Object.assign(op.requestBody.content["multipart/form-data"].schema.properties, result.content["multipart/form-data"].schema.properties); + op.requestBody.content["multipart/form-data"].schema.required = (op.requestBody.content["multipart/form-data"].schema.required || []).concat(result.content["multipart/form-data"].schema.required||[]); + if (!op.requestBody.content["multipart/form-data"].schema.required.length) { + delete op.requestBody.content["multipart/form-data"].schema.required; + } + } + else if ((op.requestBody.content && op.requestBody.content["application/x-www-form-urlencoded"] && op.requestBody.content["application/x-www-form-urlencoded"].schema && op.requestBody.content["application/x-www-form-urlencoded"].schema.properties) + && result.content["application/x-www-form-urlencoded"] && result.content["application/x-www-form-urlencoded"].schema && result.content["application/x-www-form-urlencoded"].schema.properties) { + op.requestBody.content["application/x-www-form-urlencoded"].schema.properties = + Object.assign(op.requestBody.content["application/x-www-form-urlencoded"].schema.properties, result.content["application/x-www-form-urlencoded"].schema.properties); + op.requestBody.content["application/x-www-form-urlencoded"].schema.required = (op.requestBody.content["application/x-www-form-urlencoded"].schema.required || []).concat(result.content["application/x-www-form-urlencoded"].schema.required||[]); + if (!op.requestBody.content["application/x-www-form-urlencoded"].schema.required.length) { + delete op.requestBody.content["application/x-www-form-urlencoded"].schema.required; + } + } + else { + op.requestBody = Object.assign(op.requestBody, result); + if (!op.requestBody['x-s2o-name']) { + if (op.requestBody.schema && op.requestBody.schema.$ref) { + op.requestBody['x-s2o-name'] = decodeURIComponent(op.requestBody.schema.$ref.replace('#/components/schemas/', '')).split('/').join(''); + } + else if (op.operationId) { + op.requestBody['x-s2o-name'] = common$2.sanitiseAll(op.operationId); + } + } + } + } + } + } + + // tidy up + if (param && !param['x-s2o-delete']) { + delete param.type; + for (let prop of common$2.parameterTypeProperties) { + delete param[prop]; + } + + if ((param.in === 'path') && ((typeof param.required === 'undefined') || (param.required !== true))) { + if (options.patch) { + options.patches++; + param.required = true; + } + else { + throwError('(Patchable) path parameters must be required:true ['+param.name+' in '+index+']', options); + } + } + } + + return op; +} + +function copyExtensions(src, tgt) { + for (let prop in src) { + if (prop.startsWith('x-') && !prop.startsWith('x-s2o')) { + tgt[prop] = src[prop]; + } + } +} + +function processResponse(response, name, op, openapi, options) { + if (!response) return false; + if (response.$ref && (typeof response.$ref === 'string')) { + if (response.$ref.indexOf('#/definitions/') >= 0) { + //response.$ref = '#/components/schemas/'+common.sanitise(response.$ref.replace('#/definitions/','')); + throwOrWarn('definition used as response: ' + response.$ref, response, options); + } + else { + if (response.$ref.startsWith('#/responses/')) { + response.$ref = '#/components/responses/' + common$2.sanitise(decodeURIComponent(response.$ref.replace('#/responses/', ''))); + } + } + } + else { + if ((typeof response.description === 'undefined') || (response.description === null) + || ((response.description === '') && options.patch)) { + if (options.patch) { + if ((typeof response === 'object') && (!Array.isArray(response))) { + options.patches++; + response.description = (statusCodes[response] || ''); + } + } + else { + throwError('(Patchable) response.description is mandatory', options); + } + } + if (typeof response.schema !== 'undefined') { + + fixUpSchema(response.schema,options); + + if (response.schema.$ref && (typeof response.schema.$ref === 'string') && response.schema.$ref.startsWith('#/responses/')) { + response.schema.$ref = '#/components/responses/' + common$2.sanitise(decodeURIComponent(response.schema.$ref.replace('#/responses/', ''))); + } + + if (op && op.produces && (typeof op.produces === 'string')) { + if (options.patch) { + options.patches++; + op.produces = [op.produces]; + } + else { + return throwError('(Patchable) operation.produces must be an array', options); + } + } + if (openapi.produces && !Array.isArray(openapi.produces)) delete openapi.produces; + + let produces = ((op ? op.produces : null) || (openapi.produces || [])).filter(common$2.uniqueOnly); + if (!produces.length) produces.push('*/*'); // TODO verify default + + response.content = {}; + for (let mimetype of produces) { + response.content[mimetype] = {}; + response.content[mimetype].schema = clone$3(response.schema); + if (response.examples && response.examples[mimetype]) { + let example = {}; + example.value = response.examples[mimetype]; + response.content[mimetype].examples = {}; + response.content[mimetype].examples.response = example; + delete response.examples[mimetype]; + } + if (response.content[mimetype].schema.type === 'file') { + response.content[mimetype].schema = { type: 'string', format: 'binary' }; + } + } + delete response.schema; + } + // examples for content-types not listed in produces + for (let mimetype in response.examples) { + if (!response.content) response.content = {}; + if (!response.content[mimetype]) response.content[mimetype] = {}; + response.content[mimetype].examples = {}; + response.content[mimetype].examples.response = {}; + response.content[mimetype].examples.response.value = response.examples[mimetype]; + } + delete response.examples; + + if (response.headers) { + for (let h in response.headers) { + if (h.toLowerCase() === 'status code') { + if (options.patch) { + options.patches++; + delete response.headers[h]; + } + else { + throwError('(Patchable) "Status Code" is not a valid header', options); + } + } + else { + processHeader(response.headers[h], options); + } + } + } + } +} + +function processPaths(container, containerName, options, requestBodyCache, openapi) { + for (let p in container) { + let path = container[p]; + // path.$ref is external only + if (path && (path['x-trace']) && (typeof path['x-trace'] === 'object')) { + path.trace = path['x-trace']; + delete path['x-trace']; + } + if (path && (path['x-summary']) && (typeof path['x-summary'] === 'string')) { + path.summary = path['x-summary']; + delete path['x-summary']; + } + if (path && (path['x-description']) && (typeof path['x-description'] === 'string')) { + path.description = path['x-description']; + delete path['x-description']; + } + if (path && (path['x-servers']) && (Array.isArray(path['x-servers']))) { + path.servers = path['x-servers']; + delete path['x-servers']; + } + for (let method in path) { + if ((common$2.httpMethods.indexOf(method) >= 0) || (method === 'x-amazon-apigateway-any-method')) { + let op = path[method]; + + if (op && op.parameters && Array.isArray(op.parameters)) { + if (path.parameters) { + for (let param of path.parameters) { + if (typeof param.$ref === 'string') { + fixParamRef(param, options); + param = resolveInternal(openapi, param.$ref); + } + let match = op.parameters.find(function (e, i, a) { + return ((e.name === param.name) && (e.in === param.in)); + }); + + if (!match && ((param.in === 'formData') || (param.in === 'body') || (param.type === 'file'))) { + op = processParameter(param, op, path, method, p, openapi, options); + if (options.rbname && op[options.rbname] === '') { + delete op[options.rbname]; + } + } + } + } + for (let param of op.parameters) { + op = processParameter(param, op, path, method, method + ':' + p, openapi, options); + } + if (options.rbname && op[options.rbname] === '') { + delete op[options.rbname]; + } + if (!options.debug) { + if (op.parameters) op.parameters = op.parameters.filter(keepParameters); + } + } + + if (op && op.security) processSecurity(op.security); + + //don't need to remove requestBody for non-supported ops as they "SHALL be ignored" + + // responses + if (typeof op === 'object') { + if (!op.responses) { + let defaultResp = {}; + defaultResp.description = 'Default response'; + op.responses = { default: defaultResp }; + } + for (let r in op.responses) { + let response = op.responses[r]; + processResponse(response, r, op, openapi, options); + } + } + + if (op && (op['x-servers']) && (Array.isArray(op['x-servers']))) { + op.servers = op['x-servers']; + delete op['x-servers']; + } else if (op && op.schemes && op.schemes.length) { + for (let scheme of op.schemes) { + if ((!openapi.schemes) || (openapi.schemes.indexOf(scheme) < 0)) { + if (!op.servers) { + op.servers = []; + } + if (Array.isArray(openapi.servers)) { + for (let server of openapi.servers) { + let newServer = clone$3(server); + let serverUrl = url$1.parse(newServer.url); + serverUrl.protocol = scheme; + newServer.url = serverUrl.format(); + op.servers.push(newServer); + } + } + } + } + } + + if (options.debug) { + op["x-s2o-consumes"] = op.consumes || []; + op["x-s2o-produces"] = op.produces || []; + } + if (op) { + delete op.consumes; + delete op.produces; + delete op.schemes; + + if (op["x-ms-examples"]) { + for (let e in op["x-ms-examples"]) { + let example = op["x-ms-examples"][e]; + let se = common$2.sanitiseAll(e); + if (example.parameters) { + for (let p in example.parameters) { + let value = example.parameters[p]; + for (let param of (op.parameters||[]).concat(path.parameters||[])) { + if (param.$ref) { + param = jptr.jptr(openapi,param.$ref); + } + if ((param.name === p) && (!param.example)) { + if (!param.examples) { + param.examples = {}; + } + param.examples[e] = {value: value}; + } + } + } + } + if (example.responses) { + for (let r in example.responses) { + if (example.responses[r].headers) { + for (let h in example.responses[r].headers) { + let value = example.responses[r].headers[h]; + for (let rh in op.responses[r].headers) { + if (rh === h) { + let header = op.responses[r].headers[rh]; + header.example = value; + } + } + } + } + if (example.responses[r].body) { + openapi.components.examples[se] = { value: clone$3(example.responses[r].body) }; + if (op.responses[r] && op.responses[r].content) { + for (let ct in op.responses[r].content) { + let contentType = op.responses[r].content[ct]; + if (!contentType.examples) { + contentType.examples = {}; + } + contentType.examples[e] = { $ref: '#/components/examples/'+se }; + } + } + } + + } + } + } + delete op["x-ms-examples"]; + } + + if (op.parameters && op.parameters.length === 0) delete op.parameters; + if (op.requestBody) { + let effectiveOperationId = op.operationId ? common$2.sanitiseAll(op.operationId) : common$2.sanitiseAll(method + p).toCamelCase(); + let rbName = common$2.sanitise(op.requestBody['x-s2o-name'] || effectiveOperationId || ''); + delete op.requestBody['x-s2o-name']; + let rbStr = JSON.stringify(op.requestBody); + let rbHash = common$2.hash(rbStr); + if (!requestBodyCache[rbHash]) { + let entry = {}; + entry.name = rbName; + entry.body = op.requestBody; + entry.refs = []; + requestBodyCache[rbHash] = entry; + } + let ptr = '#/'+containerName+'/'+encodeURIComponent(jptr.jpescape(p))+'/'+method+'/requestBody'; + requestBodyCache[rbHash].refs.push(ptr); + } + } + + } + } + if (path && path.parameters) { + for (let p2 in path.parameters) { + let param = path.parameters[p2]; + processParameter(param, null, path, null, p, openapi, options); // index here is the path string + } + if (!options.debug && Array.isArray(path.parameters)) { + path.parameters = path.parameters.filter(keepParameters); + } + } + } +} + +function main$1(openapi, options) { + + let requestBodyCache = {}; + componentNames = { schemas: {} }; + + if (openapi.security) processSecurity(openapi.security); + + for (let s in openapi.components.securitySchemes) { + let sname = common$2.sanitise(s); + if (s !== sname) { + if (openapi.components.securitySchemes[sname]) { + throwError('Duplicate sanitised securityScheme name ' + sname, options); + } + openapi.components.securitySchemes[sname] = openapi.components.securitySchemes[s]; + delete openapi.components.securitySchemes[s]; + } + processSecurityScheme(openapi.components.securitySchemes[sname], options); + } + + for (let s in openapi.components.schemas) { + let sname = common$2.sanitiseAll(s); + let suffix = ''; + if (s !== sname) { + while (openapi.components.schemas[sname + suffix]) { + // @ts-ignore + suffix = (suffix ? ++suffix : 2); + } + openapi.components.schemas[sname + suffix] = openapi.components.schemas[s]; + delete openapi.components.schemas[s]; + } + componentNames.schemas[s] = sname + suffix; + fixUpSchema(openapi.components.schemas[sname+suffix],options); + } + + // fix all $refs to their new locations (and potentially new names) + options.refmap = {}; + recurse(openapi, { payload: { options: options } }, fixupRefs); + dedupeRefs(openapi,options); + + for (let p in openapi.components.parameters) { + let sname = common$2.sanitise(p); + if (p !== sname) { + if (openapi.components.parameters[sname]) { + throwError('Duplicate sanitised parameter name ' + sname, options); + } + openapi.components.parameters[sname] = openapi.components.parameters[p]; + delete openapi.components.parameters[p]; + } + let param = openapi.components.parameters[sname]; + processParameter(param, null, null, null, sname, openapi, options); + } + + for (let r in openapi.components.responses) { + let sname = common$2.sanitise(r); + if (r !== sname) { + if (openapi.components.responses[sname]) { + throwError('Duplicate sanitised response name ' + sname, options); + } + openapi.components.responses[sname] = openapi.components.responses[r]; + delete openapi.components.responses[r]; + } + let response = openapi.components.responses[sname]; + processResponse(response, sname, null, openapi, options); + if (response.headers) { + for (let h in response.headers) { + if (h.toLowerCase() === 'status code') { + if (options.patch) { + options.patches++; + delete response.headers[h]; + } + else { + throwError('(Patchable) "Status Code" is not a valid header', options); + } + } + else { + processHeader(response.headers[h], options); + } + } + } + } + + for (let r in openapi.components.requestBodies) { // converted ones + let rb = openapi.components.requestBodies[r]; + let rbStr = JSON.stringify(rb); + let rbHash = common$2.hash(rbStr); + let entry = {}; + entry.name = r; + entry.body = rb; + entry.refs = []; + requestBodyCache[rbHash] = entry; + } + + processPaths(openapi.paths, 'paths', options, requestBodyCache, openapi); + if (openapi["x-ms-paths"]) { + processPaths(openapi["x-ms-paths"], 'x-ms-paths', options, requestBodyCache, openapi); + } + + if (!options.debug) { + for (let p in openapi.components.parameters) { + let param = openapi.components.parameters[p]; + if (param["x-s2o-delete"]) { + delete openapi.components.parameters[p]; + } + } + } + + if (options.debug) { + openapi["x-s2o-consumes"] = openapi.consumes || []; + openapi["x-s2o-produces"] = openapi.produces || []; + } + delete openapi.consumes; + delete openapi.produces; + delete openapi.schemes; + + let rbNamesGenerated = []; + + openapi.components.requestBodies = {}; // for now as we've dereffed them + + if (!options.resolveInternal) { + let counter = 1; + for (let e in requestBodyCache) { + let entry = requestBodyCache[e]; + if (entry.refs.length > 1) { + // create a shared requestBody + let suffix = ''; + if (!entry.name) { + entry.name = 'requestBody'; + // @ts-ignore + suffix = counter++; + } + while (rbNamesGenerated.indexOf(entry.name + suffix) >= 0) { + // @ts-ignore - this can happen if descriptions are not exactly the same (e.g. bitbucket) + suffix = (suffix ? ++suffix : 2); + } + entry.name = entry.name + suffix; + rbNamesGenerated.push(entry.name); + openapi.components.requestBodies[entry.name] = clone$3(entry.body); + for (let r in entry.refs) { + let ref = {}; + ref.$ref = '#/components/requestBodies/' + entry.name; + jptr.jptr(openapi,entry.refs[r],ref); + } + } + } + } + + if (openapi.components.responses && Object.keys(openapi.components.responses).length === 0) { + delete openapi.components.responses; + } + if (openapi.components.parameters && Object.keys(openapi.components.parameters).length === 0) { + delete openapi.components.parameters; + } + if (openapi.components.examples && Object.keys(openapi.components.examples).length === 0) { + delete openapi.components.examples; + } + if (openapi.components.requestBodies && Object.keys(openapi.components.requestBodies).length === 0) { + delete openapi.components.requestBodies; + } + if (openapi.components.securitySchemes && Object.keys(openapi.components.securitySchemes).length === 0) { + delete openapi.components.securitySchemes; + } + if (openapi.components.headers && Object.keys(openapi.components.headers).length === 0) { + delete openapi.components.headers; + } + if (openapi.components.schemas && Object.keys(openapi.components.schemas).length === 0) { + delete openapi.components.schemas; + } + if (openapi.components && Object.keys(openapi.components).length === 0) { + delete openapi.components; + } + + return openapi; +} + +function extractServerParameters(server) { + if (!server || !server.url || (typeof server.url !== 'string')) return server; + server.url = server.url.split('{{').join('{'); + server.url = server.url.split('}}').join('}'); + server.url.replace(/\{(.+?)\}/g, function (match, group1) { // TODO extend to :parameters (not port)? + if (!server.variables) { + server.variables = {}; + } + server.variables[group1] = { default: 'unknown' }; + }); + return server; +} + +function fixInfo(openapi, options, reject) { + if ((typeof openapi.info === 'undefined') || (openapi.info === null)) { + if (options.patch) { + options.patches++; + openapi.info = { version: '', title: '' }; + } + else { + return reject(new S2OError('(Patchable) info object is mandatory')); + } + } + if ((typeof openapi.info !== 'object') || (Array.isArray(openapi.info))) { + return reject(new S2OError('info must be an object')); + } + if ((typeof openapi.info.title === 'undefined') || (openapi.info.title === null)) { + if (options.patch) { + options.patches++; + openapi.info.title = ''; + } + else { + return reject(new S2OError('(Patchable) info.title cannot be null')); + } + } + if ((typeof openapi.info.version === 'undefined') || (openapi.info.version === null)) { + if (options.patch) { + options.patches++; + openapi.info.version = ''; + } + else { + return reject(new S2OError('(Patchable) info.version cannot be null')); + } + } + if (typeof openapi.info.version !== 'string') { + if (options.patch) { + options.patches++; + openapi.info.version = openapi.info.version.toString(); + } + else { + return reject(new S2OError('(Patchable) info.version must be a string')); + } + } + if (typeof openapi.info.logo !== 'undefined') { + if (options.patch) { + options.patches++; + openapi.info['x-logo'] = openapi.info.logo; + delete openapi.info.logo; + } + else return reject(new S2OError('(Patchable) info should not have logo property')); + } + if (typeof openapi.info.termsOfService !== 'undefined') { + if (openapi.info.termsOfService === null) { + if (options.patch) { + options.patches++; + openapi.info.termsOfService = ''; + } + else { + return reject(new S2OError('(Patchable) info.termsOfService cannot be null')); + } + } + try { + let u = new URL(openapi.info.termsOfService); + } + catch (ex) { + if (options.patch) { + options.patches++; + delete openapi.info.termsOfService; + } + else return reject(new S2OError('(Patchable) info.termsOfService must be a URL')); + } + } +} + +function fixPaths(openapi, options, reject) { + if (typeof openapi.paths === 'undefined') { + if (options.patch) { + options.patches++; + openapi.paths = {}; + } + else { + return reject(new S2OError('(Patchable) paths object is mandatory')); + } + } +} + +function detectObjectReferences(obj, options) { + const seen = new WeakSet(); + recurse(obj, {identityDetection:true}, function (obj, key, state) { + if ((typeof obj[key] === 'object') && (obj[key] !== null)) { + if (seen.has(obj[key])) { + if (options.anchors) { + obj[key] = clone$3(obj[key]); + } + else { + throwError('YAML anchor or merge key at '+state.path, options); + } + } + else { + seen.add(obj[key]); + } + } + }); +} + +function convertObj(swagger, options, callback) { + return maybe(callback, new Promise(function (resolve, reject) { + if (!swagger) swagger = {}; + options.original = swagger; + if (!options.text) options.text = yaml.stringify(swagger); + options.externals = []; + options.externalRefs = {}; + options.rewriteRefs = true; // avoids stack explosions + options.preserveMiro = true; + options.promise = {}; + options.promise.resolve = resolve; + options.promise.reject = reject; + options.patches = 0; + if (!options.cache) options.cache = {}; + if (options.source) options.cache[options.source] = options.original; + + detectObjectReferences(swagger, options); + + if (swagger.openapi && (typeof swagger.openapi === 'string') && swagger.openapi.startsWith('3.')) { + options.openapi = cclone(swagger); + fixInfo(options.openapi, options, reject); + fixPaths(options.openapi, options, reject); + + resolver.optionalResolve(options) // is a no-op if options.resolve is not set + .then(function(){ + if (options.direct) { + return resolve(options.openapi); + } + else { + return resolve(options); + } + }) + .catch(function(ex){ + console.warn(ex); + reject(ex); + }); + return; // we should have resolved or rejected by now + } + + if ((!swagger.swagger) || (swagger.swagger != "2.0")) { + return reject(new S2OError('Unsupported swagger/OpenAPI version: ' + (swagger.openapi ? swagger.openapi : swagger.swagger))); + } + + let openapi = options.openapi = {}; + openapi.openapi = (typeof options.targetVersion === 'string' && options.targetVersion.startsWith('3.')) ? options.targetVersion : targetVersion; // semver + + if (options.origin) { + if (!openapi["x-origin"]) { + openapi["x-origin"] = []; + } + let origin = {}; + origin.url = options.source||options.origin; + origin.format = 'swagger'; + origin.version = swagger.swagger; + origin.converter = {}; + origin.converter.url = 'https://github.com/mermade/oas-kit'; + origin.converter.version = ourVersion; + openapi["x-origin"].push(origin); + } + + // we want the new and existing properties to appear in a sensible order. Not guaranteed + openapi = Object.assign(openapi, cclone(swagger)); + delete openapi.swagger; + recurse(openapi, {}, function(obj, key, state){ + if ((obj[key] === null) && (!key.startsWith('x-')) && key !== 'default' && (state.path.indexOf('/example') < 0)) delete obj[key]; // this saves *so* much grief later + }); + + if (swagger.host) { + for (let s of (Array.isArray(swagger.schemes) ? swagger.schemes : [''])) { + let server = {}; + let basePath = (swagger.basePath || '').replace(/\/$/, ''); // Trailing slashes generally shouldn't be included + server.url = (s ? s+':' : '') + '//' + swagger.host + basePath; + extractServerParameters(server); + if (!openapi.servers) openapi.servers = []; + openapi.servers.push(server); + } + } + else if (swagger.basePath) { + let server = {}; + server.url = swagger.basePath; + extractServerParameters(server); + if (!openapi.servers) openapi.servers = []; + openapi.servers.push(server); + } + delete openapi.host; + delete openapi.basePath; + + if (openapi['x-servers'] && Array.isArray(openapi['x-servers'])) { + openapi.servers = openapi['x-servers']; + delete openapi['x-servers']; + } + + // TODO APIMatic extensions (x-server-configuration) ? + + if (swagger['x-ms-parameterized-host']) { + let xMsPHost = swagger['x-ms-parameterized-host']; + let server = {}; + server.url = xMsPHost.hostTemplate + (swagger.basePath ? swagger.basePath : ''); + server.variables = {}; + const paramNames = server.url.match(/\{\w+\}/g); + for (let msp in xMsPHost.parameters) { + let param = xMsPHost.parameters[msp]; + if (param.$ref) { + param = clone$3(resolveInternal(openapi, param.$ref)); + } + if (!msp.startsWith('x-')) { + delete param.required; // all true + delete param.type; // all strings + delete param.in; // all 'host' + if (typeof param.default === 'undefined') { + if (param.enum) { + param.default = param.enum[0]; + } + else { + param.default = 'none'; + } + } + if (!param.name) { + param.name = paramNames[msp].replace('{','').replace('}',''); + } + server.variables[param.name] = param; + delete param.name; + } + } + if (!openapi.servers) openapi.servers = []; + if (xMsPHost.useSchemePrefix === false) { + // The server URL already includes a protocol scheme + openapi.servers.push(server); + } else { + // Define this server once for each given protocol scheme + swagger.schemes.forEach((scheme) => { + openapi.servers.push( + Object.assign({}, server, { url: scheme + '://' + server.url }) + ); + }); + } + delete openapi['x-ms-parameterized-host']; + } + + fixInfo(openapi, options, reject); + fixPaths(openapi, options, reject); + + if (typeof openapi.consumes === 'string') { + openapi.consumes = [openapi.consumes]; + } + if (typeof openapi.produces === 'string') { + openapi.produces = [openapi.produces]; + } + + openapi.components = {}; + if (openapi['x-callbacks']) { + openapi.components.callbacks = openapi['x-callbacks']; + delete openapi['x-callbacks']; + } + openapi.components.examples = {}; + openapi.components.headers = {}; + if (openapi['x-links']) { + openapi.components.links = openapi['x-links']; + delete openapi['x-links']; + } + openapi.components.parameters = openapi.parameters || {}; + openapi.components.responses = openapi.responses || {}; + openapi.components.requestBodies = {}; + openapi.components.securitySchemes = openapi.securityDefinitions || {}; + openapi.components.schemas = openapi.definitions || {}; + delete openapi.definitions; + delete openapi.responses; + delete openapi.parameters; + delete openapi.securityDefinitions; + + resolver.optionalResolve(options) // is a no-op if options.resolve is not set + .then(function(){ + main$1(options.openapi, options); + if (options.direct) { + resolve(options.openapi); + } + else { + resolve(options); + } + }) + .catch(function(ex){ + console.warn(ex); + reject(ex); + }); + + })); +} + +function convertStr(str, options, callback) { + return maybe(callback, new Promise(function (resolve, reject) { + let obj = null; + let error = null; + try { + obj = JSON.parse(str); + options.text = JSON.stringify(obj,null,2); + } + catch (ex) { + error = ex; + try { + obj = yaml.parse(str, { schema: 'core', prettyErrors: true }); + options.sourceYaml = true; + options.text = str; + } + catch (ex) { + error = ex; + } + } + if (obj) { + convertObj(obj, options) + .then(options => resolve(options)) + .catch(ex => reject(ex)); + } + else { + reject(new S2OError(error ? error.message : 'Could not parse string')); + } + })); +} + +function convertUrl(url, options, callback) { + return maybe(callback, new Promise(function (resolve, reject) { + options.origin = true; + if (!options.source) { + options.source = url; + } + if (options.verbose) { + console.warn('GET ' + url); + } + if (!options.fetch) { + options.fetch = fetch$1; + } + const fetchOptions = Object.assign({}, options.fetchOptions, {agent:options.agent}); + options.fetch(url, fetchOptions).then(function (res) { + if (res.status !== 200) throw new S2OError(`Received status code ${res.status}: ${url}`); + return res.text(); + }).then(function (body) { + convertStr(body, options) + .then(options => resolve(options)) + .catch(ex => reject(ex)); + }).catch(function (err) { + reject(err); + }); + })); +} + +function convertFile(filename, options, callback) { + return maybe(callback, new Promise(function (resolve, reject) { + fs$1.readFile(filename, options.encoding || 'utf8', function (err, s) { + if (err) { + reject(err); + } + else { + options.sourceFile = filename; + convertStr(s, options) + .then(options => resolve(options)) + .catch(ex => reject(ex)); + } + }); + })); +} + +function convertStream(readable, options, callback) { + return maybe(callback, new Promise(function (resolve, reject) { + let data = ''; + readable.on('data', function (chunk) { + data += chunk; + }) + .on('end', function () { + convertStr(data, options) + .then(options => resolve(options)) + .catch(ex => reject(ex)); + }); + })); +} + +var swagger2openapi = { + S2OError: S2OError, + targetVersion: targetVersion, + convert: convertObj, + convertObj: convertObj, + convertUrl: convertUrl, + convertStr: convertStr, + convertFile: convertFile, + convertStream: convertStream +}; + +var converter = /*@__PURE__*/getDefaultExportFromCjs(swagger2openapi); + +var getAPIDefinitionType2$1 = getAPIDefinitionType$1; +var OASNormalize = class _OASNormalize { + constructor(file, opts) { + this.file = file; + this.opts = { + colorizeErrors: false, + enablePaths: false, + ...opts + }; + this.type = getType(this.file); + this.cache = { + load: false, + bundle: false, + deref: false + }; + } + /** + * @private + */ + async load() { + if (this.cache.load) + return Promise.resolve(this.cache.load); + const resolve = (obj) => { + const ret = stringToJSON(obj); + this.cache.load = ret; + return Promise.resolve(ret); + }; + switch (this.type) { + case "json": + case "string-json": + case "string-yaml": + return resolve(this.file); + case "buffer": + return resolve(this.file.toString()); + case "url": + const resp = await fetch(normalizeURL(this.file)).then((res) => res.text()); + return resolve(resp); + case "path": + if (!this.opts.enablePaths) { + return Promise.reject(new Error("Use `opts.enablePaths` to enable accessing local files.")); + } + const contents = require$$0$8.readFileSync(this.file).toString(); + if (!contents.trim()) { + return Promise.reject(new Error("No file contents found.")); + } + return resolve(contents); + default: + return Promise.reject(new Error("Could not load this file.")); + } + } + /** + * @private + */ + static convertPostmanToOpenAPI(schema) { + return postmanToOpenAPI$1(JSON.stringify(schema), null, { outputFormat: "json", replaceVars: true }).then(JSON.parse); + } + /** + * Bundle up the given API definition, resolving any external `$ref` pointers in the process. + * + */ + async bundle() { + if (this.cache.bundle) + return Promise.resolve(this.cache.bundle); + return this.load().then((schema) => { + if (isPostman$1(schema)) { + return _OASNormalize.convertPostmanToOpenAPI(schema); + } + return schema; + }).then((schema) => openapiParser.bundle(schema)).then((bundle) => { + this.cache.bundle = bundle; + return bundle; + }); + } + /** + * Dereference the given API definition. + * + */ + async deref() { + if (this.cache.deref) + return Promise.resolve(this.cache.deref); + return this.load().then((schema) => { + if (isPostman$1(schema)) { + return _OASNormalize.convertPostmanToOpenAPI(schema); + } + return schema; + }).then((schema) => openapiParser.dereference(schema)).then((dereferenced) => { + this.cache.deref = dereferenced; + return dereferenced; + }); + } + /** + * Validate, and potentially convert to OpenAPI, a given API definition. + * + */ + async validate(opts = { convertToLatest: false }) { + const convertToLatest = opts.convertToLatest; + const parserOptions = opts.parser || {}; + if (!parserOptions.validate) { + parserOptions.validate = {}; + } + parserOptions.validate.colorizeErrors = this.opts.colorizeErrors; + return this.load().then(async (schema) => { + if (!isPostman$1(schema)) { + return schema; + } + return _OASNormalize.convertPostmanToOpenAPI(schema); + }).then(async (schema) => { + if (!isSwagger$1(schema) && !isOpenAPI$1(schema)) { + return Promise.reject(new Error("The supplied API definition is unsupported.")); + } else if (isSwagger$1(schema)) { + const baseVersion = parseInt(schema.swagger, 10); + if (baseVersion === 1) { + return Promise.reject(new Error("Swagger v1.2 is unsupported.")); + } + } + const clonedSchema = JSON.parse(JSON.stringify(schema)); + return openapiParser.validate(clonedSchema, parserOptions).then(() => { + if (!convertToLatest) { + return schema; + } + return converter.convertObj(schema, { anchors: true }).then((options) => options.openapi); + }).catch((err) => Promise.reject(err)); + }); + } + /** + * Retrieve OpenAPI, Swagger, or Postman version information about the supplied API definition. + * + */ + version() { + return this.load().then((schema) => { + switch (getAPIDefinitionType2$1(schema)) { + case "openapi": + return { + specification: "openapi", + version: schema.openapi + }; + case "postman": + let version = "unknown"; + if (schema?.info?.schema) { + const match = schema.info.schema.match( + /http(s?):\/\/schema.getpostman.com\/json\/collection\/v([0-9.]+)\// + ); + if (match) { + version = match[2]; + } + } + return { + specification: "postman", + version + }; + case "swagger": + return { + specification: "swagger", + version: schema.swagger + }; + default: + throw new Error("Unknown file detected."); + } + }); + } +}; + +const restoreCursor = onetime$3(() => { + signalExit(() => { + process$3.stderr.write('\u001B[?25h'); + }, {alwaysLast: true}); +}); + +let isHidden = false; + +const cliCursor = {}; + +cliCursor.show = (writableStream = process$3.stderr) => { + if (!writableStream.isTTY) { + return; + } + + isHidden = false; + writableStream.write('\u001B[?25h'); +}; + +cliCursor.hide = (writableStream = process$3.stderr) => { + if (!writableStream.isTTY) { + return; + } + + restoreCursor(); + isHidden = true; + writableStream.write('\u001B[?25l'); +}; + +cliCursor.toggle = (force, writableStream) => { + if (force !== undefined) { + isHidden = force; + } + + if (isHidden) { + cliCursor.show(writableStream); + } else { + cliCursor.hide(writableStream); + } +}; + +var dots = { + interval: 80, + frames: [ + "⠋", + "⠙", + "⠹", + "⠸", + "⠼", + "⠴", + "⠦", + "⠧", + "⠇", + "⠏" + ] +}; +var dots2 = { + interval: 80, + frames: [ + "⣾", + "⣽", + "⣻", + "⢿", + "⡿", + "⣟", + "⣯", + "⣷" + ] +}; +var dots3 = { + interval: 80, + frames: [ + "⠋", + "⠙", + "⠚", + "⠞", + "⠖", + "⠦", + "⠴", + "⠲", + "⠳", + "⠓" + ] +}; +var dots4 = { + interval: 80, + frames: [ + "⠄", + "⠆", + "⠇", + "⠋", + "⠙", + "⠸", + "⠰", + "⠠", + "⠰", + "⠸", + "⠙", + "⠋", + "⠇", + "⠆" + ] +}; +var dots5 = { + interval: 80, + frames: [ + "⠋", + "⠙", + "⠚", + "⠒", + "⠂", + "⠂", + "⠒", + "⠲", + "⠴", + "⠦", + "⠖", + "⠒", + "⠐", + "⠐", + "⠒", + "⠓", + "⠋" + ] +}; +var dots6 = { + interval: 80, + frames: [ + "⠁", + "⠉", + "⠙", + "⠚", + "⠒", + "⠂", + "⠂", + "⠒", + "⠲", + "⠴", + "⠤", + "⠄", + "⠄", + "⠤", + "⠴", + "⠲", + "⠒", + "⠂", + "⠂", + "⠒", + "⠚", + "⠙", + "⠉", + "⠁" + ] +}; +var dots7 = { + interval: 80, + frames: [ + "⠈", + "⠉", + "⠋", + "⠓", + "⠒", + "⠐", + "⠐", + "⠒", + "⠖", + "⠦", + "⠤", + "⠠", + "⠠", + "⠤", + "⠦", + "⠖", + "⠒", + "⠐", + "⠐", + "⠒", + "⠓", + "⠋", + "⠉", + "⠈" + ] +}; +var dots8 = { + interval: 80, + frames: [ + "⠁", + "⠁", + "⠉", + "⠙", + "⠚", + "⠒", + "⠂", + "⠂", + "⠒", + "⠲", + "⠴", + "⠤", + "⠄", + "⠄", + "⠤", + "⠠", + "⠠", + "⠤", + "⠦", + "⠖", + "⠒", + "⠐", + "⠐", + "⠒", + "⠓", + "⠋", + "⠉", + "⠈", + "⠈" + ] +}; +var dots9 = { + interval: 80, + frames: [ + "⢹", + "⢺", + "⢼", + "⣸", + "⣇", + "⡧", + "⡗", + "⡏" + ] +}; +var dots10 = { + interval: 80, + frames: [ + "⢄", + "⢂", + "⢁", + "⡁", + "⡈", + "⡐", + "⡠" + ] +}; +var dots11 = { + interval: 100, + frames: [ + "⠁", + "⠂", + "⠄", + "⡀", + "⢀", + "⠠", + "⠐", + "⠈" + ] +}; +var dots12 = { + interval: 80, + frames: [ + "⢀⠀", + "⡀⠀", + "⠄⠀", + "⢂⠀", + "⡂⠀", + "⠅⠀", + "⢃⠀", + "⡃⠀", + "⠍⠀", + "⢋⠀", + "⡋⠀", + "⠍⠁", + "⢋⠁", + "⡋⠁", + "⠍⠉", + "⠋⠉", + "⠋⠉", + "⠉⠙", + "⠉⠙", + "⠉⠩", + "⠈⢙", + "⠈⡙", + "⢈⠩", + "⡀⢙", + "⠄⡙", + "⢂⠩", + "⡂⢘", + "⠅⡘", + "⢃⠨", + "⡃⢐", + "⠍⡐", + "⢋⠠", + "⡋⢀", + "⠍⡁", + "⢋⠁", + "⡋⠁", + "⠍⠉", + "⠋⠉", + "⠋⠉", + "⠉⠙", + "⠉⠙", + "⠉⠩", + "⠈⢙", + "⠈⡙", + "⠈⠩", + "⠀⢙", + "⠀⡙", + "⠀⠩", + "⠀⢘", + "⠀⡘", + "⠀⠨", + "⠀⢐", + "⠀⡐", + "⠀⠠", + "⠀⢀", + "⠀⡀" + ] +}; +var dots13 = { + interval: 80, + frames: [ + "⣼", + "⣹", + "⢻", + "⠿", + "⡟", + "⣏", + "⣧", + "⣶" + ] +}; +var dots8Bit = { + interval: 80, + frames: [ + "⠀", + "⠁", + "⠂", + "⠃", + "⠄", + "⠅", + "⠆", + "⠇", + "⡀", + "⡁", + "⡂", + "⡃", + "⡄", + "⡅", + "⡆", + "⡇", + "⠈", + "⠉", + "⠊", + "⠋", + "⠌", + "⠍", + "⠎", + "⠏", + "⡈", + "⡉", + "⡊", + "⡋", + "⡌", + "⡍", + "⡎", + "⡏", + "⠐", + "⠑", + "⠒", + "⠓", + "⠔", + "⠕", + "⠖", + "⠗", + "⡐", + "⡑", + "⡒", + "⡓", + "⡔", + "⡕", + "⡖", + "⡗", + "⠘", + "⠙", + "⠚", + "⠛", + "⠜", + "⠝", + "⠞", + "⠟", + "⡘", + "⡙", + "⡚", + "⡛", + "⡜", + "⡝", + "⡞", + "⡟", + "⠠", + "⠡", + "⠢", + "⠣", + "⠤", + "⠥", + "⠦", + "⠧", + "⡠", + "⡡", + "⡢", + "⡣", + "⡤", + "⡥", + "⡦", + "⡧", + "⠨", + "⠩", + "⠪", + "⠫", + "⠬", + "⠭", + "⠮", + "⠯", + "⡨", + "⡩", + "⡪", + "⡫", + "⡬", + "⡭", + "⡮", + "⡯", + "⠰", + "⠱", + "⠲", + "⠳", + "⠴", + "⠵", + "⠶", + "⠷", + "⡰", + "⡱", + "⡲", + "⡳", + "⡴", + "⡵", + "⡶", + "⡷", + "⠸", + "⠹", + "⠺", + "⠻", + "⠼", + "⠽", + "⠾", + "⠿", + "⡸", + "⡹", + "⡺", + "⡻", + "⡼", + "⡽", + "⡾", + "⡿", + "⢀", + "⢁", + "⢂", + "⢃", + "⢄", + "⢅", + "⢆", + "⢇", + "⣀", + "⣁", + "⣂", + "⣃", + "⣄", + "⣅", + "⣆", + "⣇", + "⢈", + "⢉", + "⢊", + "⢋", + "⢌", + "⢍", + "⢎", + "⢏", + "⣈", + "⣉", + "⣊", + "⣋", + "⣌", + "⣍", + "⣎", + "⣏", + "⢐", + "⢑", + "⢒", + "⢓", + "⢔", + "⢕", + "⢖", + "⢗", + "⣐", + "⣑", + "⣒", + "⣓", + "⣔", + "⣕", + "⣖", + "⣗", + "⢘", + "⢙", + "⢚", + "⢛", + "⢜", + "⢝", + "⢞", + "⢟", + "⣘", + "⣙", + "⣚", + "⣛", + "⣜", + "⣝", + "⣞", + "⣟", + "⢠", + "⢡", + "⢢", + "⢣", + "⢤", + "⢥", + "⢦", + "⢧", + "⣠", + "⣡", + "⣢", + "⣣", + "⣤", + "⣥", + "⣦", + "⣧", + "⢨", + "⢩", + "⢪", + "⢫", + "⢬", + "⢭", + "⢮", + "⢯", + "⣨", + "⣩", + "⣪", + "⣫", + "⣬", + "⣭", + "⣮", + "⣯", + "⢰", + "⢱", + "⢲", + "⢳", + "⢴", + "⢵", + "⢶", + "⢷", + "⣰", + "⣱", + "⣲", + "⣳", + "⣴", + "⣵", + "⣶", + "⣷", + "⢸", + "⢹", + "⢺", + "⢻", + "⢼", + "⢽", + "⢾", + "⢿", + "⣸", + "⣹", + "⣺", + "⣻", + "⣼", + "⣽", + "⣾", + "⣿" + ] +}; +var sand = { + interval: 80, + frames: [ + "⠁", + "⠂", + "⠄", + "⡀", + "⡈", + "⡐", + "⡠", + "⣀", + "⣁", + "⣂", + "⣄", + "⣌", + "⣔", + "⣤", + "⣥", + "⣦", + "⣮", + "⣶", + "⣷", + "⣿", + "⡿", + "⠿", + "⢟", + "⠟", + "⡛", + "⠛", + "⠫", + "⢋", + "⠋", + "⠍", + "⡉", + "⠉", + "⠑", + "⠡", + "⢁" + ] +}; +var line = { + interval: 130, + frames: [ + "-", + "\\", + "|", + "/" + ] +}; +var line2 = { + interval: 100, + frames: [ + "⠂", + "-", + "–", + "—", + "–", + "-" + ] +}; +var pipe = { + interval: 100, + frames: [ + "┤", + "┘", + "┴", + "└", + "├", + "┌", + "┬", + "┐" + ] +}; +var simpleDots = { + interval: 400, + frames: [ + ". ", + ".. ", + "...", + " " + ] +}; +var simpleDotsScrolling = { + interval: 200, + frames: [ + ". ", + ".. ", + "...", + " ..", + " .", + " " + ] +}; +var star = { + interval: 70, + frames: [ + "✶", + "✸", + "✹", + "✺", + "✹", + "✷" + ] +}; +var star2 = { + interval: 80, + frames: [ + "+", + "x", + "*" + ] +}; +var flip = { + interval: 70, + frames: [ + "_", + "_", + "_", + "-", + "`", + "`", + "'", + "´", + "-", + "_", + "_", + "_" + ] +}; +var hamburger = { + interval: 100, + frames: [ + "☱", + "☲", + "☴" + ] +}; +var growVertical = { + interval: 120, + frames: [ + "▁", + "▃", + "▄", + "▅", + "▆", + "▇", + "▆", + "▅", + "▄", + "▃" + ] +}; +var growHorizontal = { + interval: 120, + frames: [ + "▏", + "▎", + "▍", + "▌", + "▋", + "▊", + "▉", + "▊", + "▋", + "▌", + "▍", + "▎" + ] +}; +var balloon = { + interval: 140, + frames: [ + " ", + ".", + "o", + "O", + "@", + "*", + " " + ] +}; +var balloon2 = { + interval: 120, + frames: [ + ".", + "o", + "O", + "°", + "O", + "o", + "." + ] +}; +var noise = { + interval: 100, + frames: [ + "▓", + "▒", + "░" + ] +}; +var bounce = { + interval: 120, + frames: [ + "⠁", + "⠂", + "⠄", + "⠂" + ] +}; +var boxBounce = { + interval: 120, + frames: [ + "▖", + "▘", + "▝", + "▗" + ] +}; +var boxBounce2 = { + interval: 100, + frames: [ + "▌", + "▀", + "▐", + "▄" + ] +}; +var triangle = { + interval: 50, + frames: [ + "◢", + "◣", + "◤", + "◥" + ] +}; +var binary = { + interval: 80, + frames: [ + "010010", + "001100", + "100101", + "111010", + "111101", + "010111", + "101011", + "111000", + "110011", + "110101" + ] +}; +var arc = { + interval: 100, + frames: [ + "◜", + "◠", + "◝", + "◞", + "◡", + "◟" + ] +}; +var circle = { + interval: 120, + frames: [ + "◡", + "⊙", + "◠" + ] +}; +var squareCorners = { + interval: 180, + frames: [ + "◰", + "◳", + "◲", + "◱" + ] +}; +var circleQuarters = { + interval: 120, + frames: [ + "◴", + "◷", + "◶", + "◵" + ] +}; +var circleHalves = { + interval: 50, + frames: [ + "◐", + "◓", + "◑", + "◒" + ] +}; +var squish = { + interval: 100, + frames: [ + "╫", + "╪" + ] +}; +var toggle = { + interval: 250, + frames: [ + "⊶", + "⊷" + ] +}; +var toggle2 = { + interval: 80, + frames: [ + "▫", + "▪" + ] +}; +var toggle3 = { + interval: 120, + frames: [ + "□", + "■" + ] +}; +var toggle4 = { + interval: 100, + frames: [ + "■", + "□", + "▪", + "▫" + ] +}; +var toggle5 = { + interval: 100, + frames: [ + "▮", + "▯" + ] +}; +var toggle6 = { + interval: 300, + frames: [ + "ဝ", + "၀" + ] +}; +var toggle7 = { + interval: 80, + frames: [ + "⦾", + "⦿" + ] +}; +var toggle8 = { + interval: 100, + frames: [ + "◍", + "◌" + ] +}; +var toggle9 = { + interval: 100, + frames: [ + "◉", + "◎" + ] +}; +var toggle10 = { + interval: 100, + frames: [ + "㊂", + "㊀", + "㊁" + ] +}; +var toggle11 = { + interval: 50, + frames: [ + "⧇", + "⧆" + ] +}; +var toggle12 = { + interval: 120, + frames: [ + "☗", + "☖" + ] +}; +var toggle13 = { + interval: 80, + frames: [ + "=", + "*", + "-" + ] +}; +var arrow = { + interval: 100, + frames: [ + "←", + "↖", + "↑", + "↗", + "→", + "↘", + "↓", + "↙" + ] +}; +var arrow2 = { + interval: 80, + frames: [ + "⬆️ ", + "↗️ ", + "➡️ ", + "↘️ ", + "⬇️ ", + "↙️ ", + "⬅️ ", + "↖️ " + ] +}; +var arrow3 = { + interval: 120, + frames: [ + "▹▹▹▹▹", + "▸▹▹▹▹", + "▹▸▹▹▹", + "▹▹▸▹▹", + "▹▹▹▸▹", + "▹▹▹▹▸" + ] +}; +var bouncingBar = { + interval: 80, + frames: [ + "[ ]", + "[= ]", + "[== ]", + "[=== ]", + "[====]", + "[ ===]", + "[ ==]", + "[ =]", + "[ ]", + "[ =]", + "[ ==]", + "[ ===]", + "[====]", + "[=== ]", + "[== ]", + "[= ]" + ] +}; +var bouncingBall = { + interval: 80, + frames: [ + "( ● )", + "( ● )", + "( ● )", + "( ● )", + "( ●)", + "( ● )", + "( ● )", + "( ● )", + "( ● )", + "(● )" + ] +}; +var smiley = { + interval: 200, + frames: [ + "😄 ", + "😝 " + ] +}; +var monkey = { + interval: 300, + frames: [ + "🙈 ", + "🙈 ", + "🙉 ", + "🙊 " + ] +}; +var hearts = { + interval: 100, + frames: [ + "💛 ", + "💙 ", + "💜 ", + "💚 ", + "❤️ " + ] +}; +var clock = { + interval: 100, + frames: [ + "🕛 ", + "🕐 ", + "🕑 ", + "🕒 ", + "🕓 ", + "🕔 ", + "🕕 ", + "🕖 ", + "🕗 ", + "🕘 ", + "🕙 ", + "🕚 " + ] +}; +var earth = { + interval: 180, + frames: [ + "🌍 ", + "🌎 ", + "🌏 " + ] +}; +var material = { + interval: 17, + frames: [ + "█▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", + "██▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", + "███▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", + "████▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", + "██████▁▁▁▁▁▁▁▁▁▁▁▁▁▁", + "██████▁▁▁▁▁▁▁▁▁▁▁▁▁▁", + "███████▁▁▁▁▁▁▁▁▁▁▁▁▁", + "████████▁▁▁▁▁▁▁▁▁▁▁▁", + "█████████▁▁▁▁▁▁▁▁▁▁▁", + "█████████▁▁▁▁▁▁▁▁▁▁▁", + "██████████▁▁▁▁▁▁▁▁▁▁", + "███████████▁▁▁▁▁▁▁▁▁", + "█████████████▁▁▁▁▁▁▁", + "██████████████▁▁▁▁▁▁", + "██████████████▁▁▁▁▁▁", + "▁██████████████▁▁▁▁▁", + "▁██████████████▁▁▁▁▁", + "▁██████████████▁▁▁▁▁", + "▁▁██████████████▁▁▁▁", + "▁▁▁██████████████▁▁▁", + "▁▁▁▁█████████████▁▁▁", + "▁▁▁▁██████████████▁▁", + "▁▁▁▁██████████████▁▁", + "▁▁▁▁▁██████████████▁", + "▁▁▁▁▁██████████████▁", + "▁▁▁▁▁██████████████▁", + "▁▁▁▁▁▁██████████████", + "▁▁▁▁▁▁██████████████", + "▁▁▁▁▁▁▁█████████████", + "▁▁▁▁▁▁▁█████████████", + "▁▁▁▁▁▁▁▁████████████", + "▁▁▁▁▁▁▁▁████████████", + "▁▁▁▁▁▁▁▁▁███████████", + "▁▁▁▁▁▁▁▁▁███████████", + "▁▁▁▁▁▁▁▁▁▁██████████", + "▁▁▁▁▁▁▁▁▁▁██████████", + "▁▁▁▁▁▁▁▁▁▁▁▁████████", + "▁▁▁▁▁▁▁▁▁▁▁▁▁███████", + "▁▁▁▁▁▁▁▁▁▁▁▁▁▁██████", + "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█████", + "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█████", + "█▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████", + "██▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███", + "██▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███", + "███▁▁▁▁▁▁▁▁▁▁▁▁▁▁███", + "████▁▁▁▁▁▁▁▁▁▁▁▁▁▁██", + "█████▁▁▁▁▁▁▁▁▁▁▁▁▁▁█", + "█████▁▁▁▁▁▁▁▁▁▁▁▁▁▁█", + "██████▁▁▁▁▁▁▁▁▁▁▁▁▁█", + "████████▁▁▁▁▁▁▁▁▁▁▁▁", + "█████████▁▁▁▁▁▁▁▁▁▁▁", + "█████████▁▁▁▁▁▁▁▁▁▁▁", + "█████████▁▁▁▁▁▁▁▁▁▁▁", + "█████████▁▁▁▁▁▁▁▁▁▁▁", + "███████████▁▁▁▁▁▁▁▁▁", + "████████████▁▁▁▁▁▁▁▁", + "████████████▁▁▁▁▁▁▁▁", + "██████████████▁▁▁▁▁▁", + "██████████████▁▁▁▁▁▁", + "▁██████████████▁▁▁▁▁", + "▁██████████████▁▁▁▁▁", + "▁▁▁█████████████▁▁▁▁", + "▁▁▁▁▁████████████▁▁▁", + "▁▁▁▁▁████████████▁▁▁", + "▁▁▁▁▁▁███████████▁▁▁", + "▁▁▁▁▁▁▁▁█████████▁▁▁", + "▁▁▁▁▁▁▁▁█████████▁▁▁", + "▁▁▁▁▁▁▁▁▁█████████▁▁", + "▁▁▁▁▁▁▁▁▁█████████▁▁", + "▁▁▁▁▁▁▁▁▁▁█████████▁", + "▁▁▁▁▁▁▁▁▁▁▁████████▁", + "▁▁▁▁▁▁▁▁▁▁▁████████▁", + "▁▁▁▁▁▁▁▁▁▁▁▁███████▁", + "▁▁▁▁▁▁▁▁▁▁▁▁███████▁", + "▁▁▁▁▁▁▁▁▁▁▁▁▁███████", + "▁▁▁▁▁▁▁▁▁▁▁▁▁███████", + "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█████", + "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████", + "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████", + "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████", + "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███", + "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███", + "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁██", + "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁██", + "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁██", + "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█", + "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█", + "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█", + "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", + "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", + "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", + "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁" + ] +}; +var moon = { + interval: 80, + frames: [ + "🌑 ", + "🌒 ", + "🌓 ", + "🌔 ", + "🌕 ", + "🌖 ", + "🌗 ", + "🌘 " + ] +}; +var runner = { + interval: 140, + frames: [ + "🚶 ", + "🏃 " + ] +}; +var pong = { + interval: 80, + frames: [ + "▐⠂ ▌", + "▐⠈ ▌", + "▐ ⠂ ▌", + "▐ ⠠ ▌", + "▐ ⡀ ▌", + "▐ ⠠ ▌", + "▐ ⠂ ▌", + "▐ ⠈ ▌", + "▐ ⠂ ▌", + "▐ ⠠ ▌", + "▐ ⡀ ▌", + "▐ ⠠ ▌", + "▐ ⠂ ▌", + "▐ ⠈ ▌", + "▐ ⠂▌", + "▐ ⠠▌", + "▐ ⡀▌", + "▐ ⠠ ▌", + "▐ ⠂ ▌", + "▐ ⠈ ▌", + "▐ ⠂ ▌", + "▐ ⠠ ▌", + "▐ ⡀ ▌", + "▐ ⠠ ▌", + "▐ ⠂ ▌", + "▐ ⠈ ▌", + "▐ ⠂ ▌", + "▐ ⠠ ▌", + "▐ ⡀ ▌", + "▐⠠ ▌" + ] +}; +var shark = { + interval: 120, + frames: [ + "▐|\\____________▌", + "▐_|\\___________▌", + "▐__|\\__________▌", + "▐___|\\_________▌", + "▐____|\\________▌", + "▐_____|\\_______▌", + "▐______|\\______▌", + "▐_______|\\_____▌", + "▐________|\\____▌", + "▐_________|\\___▌", + "▐__________|\\__▌", + "▐___________|\\_▌", + "▐____________|\\▌", + "▐____________/|▌", + "▐___________/|_▌", + "▐__________/|__▌", + "▐_________/|___▌", + "▐________/|____▌", + "▐_______/|_____▌", + "▐______/|______▌", + "▐_____/|_______▌", + "▐____/|________▌", + "▐___/|_________▌", + "▐__/|__________▌", + "▐_/|___________▌", + "▐/|____________▌" + ] +}; +var dqpb = { + interval: 100, + frames: [ + "d", + "q", + "p", + "b" + ] +}; +var weather = { + interval: 100, + frames: [ + "☀️ ", + "☀️ ", + "☀️ ", + "🌤 ", + "⛅️ ", + "🌥 ", + "☁️ ", + "🌧 ", + "🌨 ", + "🌧 ", + "🌨 ", + "🌧 ", + "🌨 ", + "⛈ ", + "🌨 ", + "🌧 ", + "🌨 ", + "☁️ ", + "🌥 ", + "⛅️ ", + "🌤 ", + "☀️ ", + "☀️ " + ] +}; +var christmas = { + interval: 400, + frames: [ + "🌲", + "🎄" + ] +}; +var grenade = { + interval: 80, + frames: [ + "، ", + "′ ", + " ´ ", + " ‾ ", + " ⸌", + " ⸊", + " |", + " ⁎", + " ⁕", + " ෴ ", + " ⁓", + " ", + " ", + " " + ] +}; +var point = { + interval: 125, + frames: [ + "∙∙∙", + "●∙∙", + "∙●∙", + "∙∙●", + "∙∙∙" + ] +}; +var layer = { + interval: 150, + frames: [ + "-", + "=", + "≡" + ] +}; +var betaWave = { + interval: 80, + frames: [ + "ρββββββ", + "βρβββββ", + "ββρββββ", + "βββρβββ", + "ββββρββ", + "βββββρβ", + "ββββββρ" + ] +}; +var fingerDance = { + interval: 160, + frames: [ + "🤘 ", + "🤟 ", + "🖖 ", + "✋ ", + "🤚 ", + "👆 " + ] +}; +var fistBump = { + interval: 80, + frames: [ + "🤜    🤛 ", + "🤜    🤛 ", + "🤜    🤛 ", + " 🤜  🤛  ", + "  🤜🤛   ", + " 🤜✨🤛   ", + "🤜 ✨ 🤛  " + ] +}; +var soccerHeader = { + interval: 80, + frames: [ + " 🧑⚽️ 🧑 ", + "🧑 ⚽️ 🧑 ", + "🧑 ⚽️ 🧑 ", + "🧑 ⚽️ 🧑 ", + "🧑 ⚽️ 🧑 ", + "🧑 ⚽️ 🧑 ", + "🧑 ⚽️🧑 ", + "🧑 ⚽️ 🧑 ", + "🧑 ⚽️ 🧑 ", + "🧑 ⚽️ 🧑 ", + "🧑 ⚽️ 🧑 ", + "🧑 ⚽️ 🧑 " + ] +}; +var mindblown = { + interval: 160, + frames: [ + "😐 ", + "😐 ", + "😮 ", + "😮 ", + "😦 ", + "😦 ", + "😧 ", + "😧 ", + "🤯 ", + "💥 ", + "✨ ", + "  ", + "  ", + "  " + ] +}; +var speaker = { + interval: 160, + frames: [ + "🔈 ", + "🔉 ", + "🔊 ", + "🔉 " + ] +}; +var orangePulse = { + interval: 100, + frames: [ + "🔸 ", + "🔶 ", + "🟠 ", + "🟠 ", + "🔶 " + ] +}; +var bluePulse = { + interval: 100, + frames: [ + "🔹 ", + "🔷 ", + "🔵 ", + "🔵 ", + "🔷 " + ] +}; +var orangeBluePulse = { + interval: 100, + frames: [ + "🔸 ", + "🔶 ", + "🟠 ", + "🟠 ", + "🔶 ", + "🔹 ", + "🔷 ", + "🔵 ", + "🔵 ", + "🔷 " + ] +}; +var timeTravel = { + interval: 100, + frames: [ + "🕛 ", + "🕚 ", + "🕙 ", + "🕘 ", + "🕗 ", + "🕖 ", + "🕕 ", + "🕔 ", + "🕓 ", + "🕒 ", + "🕑 ", + "🕐 " + ] +}; +var aesthetic = { + interval: 80, + frames: [ + "▰▱▱▱▱▱▱", + "▰▰▱▱▱▱▱", + "▰▰▰▱▱▱▱", + "▰▰▰▰▱▱▱", + "▰▰▰▰▰▱▱", + "▰▰▰▰▰▰▱", + "▰▰▰▰▰▰▰", + "▰▱▱▱▱▱▱" + ] +}; +var dwarfFortress = { + interval: 80, + frames: [ + " ██████£££ ", + "☺██████£££ ", + "☺██████£££ ", + "☺▓█████£££ ", + "☺▓█████£££ ", + "☺▒█████£££ ", + "☺▒█████£££ ", + "☺░█████£££ ", + "☺░█████£££ ", + "☺ █████£££ ", + " ☺█████£££ ", + " ☺█████£££ ", + " ☺▓████£££ ", + " ☺▓████£££ ", + " ☺▒████£££ ", + " ☺▒████£££ ", + " ☺░████£££ ", + " ☺░████£££ ", + " ☺ ████£££ ", + " ☺████£££ ", + " ☺████£££ ", + " ☺▓███£££ ", + " ☺▓███£££ ", + " ☺▒███£££ ", + " ☺▒███£££ ", + " ☺░███£££ ", + " ☺░███£££ ", + " ☺ ███£££ ", + " ☺███£££ ", + " ☺███£££ ", + " ☺▓██£££ ", + " ☺▓██£££ ", + " ☺▒██£££ ", + " ☺▒██£££ ", + " ☺░██£££ ", + " ☺░██£££ ", + " ☺ ██£££ ", + " ☺██£££ ", + " ☺██£££ ", + " ☺▓█£££ ", + " ☺▓█£££ ", + " ☺▒█£££ ", + " ☺▒█£££ ", + " ☺░█£££ ", + " ☺░█£££ ", + " ☺ █£££ ", + " ☺█£££ ", + " ☺█£££ ", + " ☺▓£££ ", + " ☺▓£££ ", + " ☺▒£££ ", + " ☺▒£££ ", + " ☺░£££ ", + " ☺░£££ ", + " ☺ £££ ", + " ☺£££ ", + " ☺£££ ", + " ☺▓££ ", + " ☺▓££ ", + " ☺▒££ ", + " ☺▒££ ", + " ☺░££ ", + " ☺░££ ", + " ☺ ££ ", + " ☺££ ", + " ☺££ ", + " ☺▓£ ", + " ☺▓£ ", + " ☺▒£ ", + " ☺▒£ ", + " ☺░£ ", + " ☺░£ ", + " ☺ £ ", + " ☺£ ", + " ☺£ ", + " ☺▓ ", + " ☺▓ ", + " ☺▒ ", + " ☺▒ ", + " ☺░ ", + " ☺░ ", + " ☺ ", + " ☺ &", + " ☺ ☼&", + " ☺ ☼ &", + " ☺☼ &", + " ☺☼ & ", + " ‼ & ", + " ☺ & ", + " ‼ & ", + " ☺ & ", + " ‼ & ", + " ☺ & ", + "‼ & ", + " & ", + " & ", + " & ░ ", + " & ▒ ", + " & ▓ ", + " & £ ", + " & ░£ ", + " & ▒£ ", + " & ▓£ ", + " & ££ ", + " & ░££ ", + " & ▒££ ", + "& ▓££ ", + "& £££ ", + " ░£££ ", + " ▒£££ ", + " ▓£££ ", + " █£££ ", + " ░█£££ ", + " ▒█£££ ", + " ▓█£££ ", + " ██£££ ", + " ░██£££ ", + " ▒██£££ ", + " ▓██£££ ", + " ███£££ ", + " ░███£££ ", + " ▒███£££ ", + " ▓███£££ ", + " ████£££ ", + " ░████£££ ", + " ▒████£££ ", + " ▓████£££ ", + " █████£££ ", + " ░█████£££ ", + " ▒█████£££ ", + " ▓█████£££ ", + " ██████£££ ", + " ██████£££ " + ] +}; +var require$$0 = { + dots: dots, + dots2: dots2, + dots3: dots3, + dots4: dots4, + dots5: dots5, + dots6: dots6, + dots7: dots7, + dots8: dots8, + dots9: dots9, + dots10: dots10, + dots11: dots11, + dots12: dots12, + dots13: dots13, + dots8Bit: dots8Bit, + sand: sand, + line: line, + line2: line2, + pipe: pipe, + simpleDots: simpleDots, + simpleDotsScrolling: simpleDotsScrolling, + star: star, + star2: star2, + flip: flip, + hamburger: hamburger, + growVertical: growVertical, + growHorizontal: growHorizontal, + balloon: balloon, + balloon2: balloon2, + noise: noise, + bounce: bounce, + boxBounce: boxBounce, + boxBounce2: boxBounce2, + triangle: triangle, + binary: binary, + arc: arc, + circle: circle, + squareCorners: squareCorners, + circleQuarters: circleQuarters, + circleHalves: circleHalves, + squish: squish, + toggle: toggle, + toggle2: toggle2, + toggle3: toggle3, + toggle4: toggle4, + toggle5: toggle5, + toggle6: toggle6, + toggle7: toggle7, + toggle8: toggle8, + toggle9: toggle9, + toggle10: toggle10, + toggle11: toggle11, + toggle12: toggle12, + toggle13: toggle13, + arrow: arrow, + arrow2: arrow2, + arrow3: arrow3, + bouncingBar: bouncingBar, + bouncingBall: bouncingBall, + smiley: smiley, + monkey: monkey, + hearts: hearts, + clock: clock, + earth: earth, + material: material, + moon: moon, + runner: runner, + pong: pong, + shark: shark, + dqpb: dqpb, + weather: weather, + christmas: christmas, + grenade: grenade, + point: point, + layer: layer, + betaWave: betaWave, + fingerDance: fingerDance, + fistBump: fistBump, + soccerHeader: soccerHeader, + mindblown: mindblown, + speaker: speaker, + orangePulse: orangePulse, + bluePulse: bluePulse, + orangeBluePulse: orangeBluePulse, + timeTravel: timeTravel, + aesthetic: aesthetic, + dwarfFortress: dwarfFortress +}; + +const spinners = Object.assign({}, require$$0); // eslint-disable-line import/extensions + +const spinnersList = Object.keys(spinners); + +Object.defineProperty(spinners, 'random', { + get() { + const randomIndex = Math.floor(Math.random() * spinnersList.length); + const spinnerName = spinnersList[randomIndex]; + return spinners[spinnerName]; + } +}); + +var cliSpinners = spinners; + +var cliSpinners$1 = /*@__PURE__*/getDefaultExportFromCjs(cliSpinners); + +function isUnicodeSupported() { + if (process$3.platform !== 'win32') { + return process$3.env.TERM !== 'linux'; // Linux console (kernel) + } + + return Boolean(process$3.env.CI) + || Boolean(process$3.env.WT_SESSION) // Windows Terminal + || Boolean(process$3.env.TERMINUS_SUBLIME) // Terminus (<0.2.27) + || process$3.env.ConEmuTask === '{cmd::Cmder}' // ConEmu and cmder + || process$3.env.TERM_PROGRAM === 'Terminus-Sublime' + || process$3.env.TERM_PROGRAM === 'vscode' + || process$3.env.TERM === 'xterm-256color' + || process$3.env.TERM === 'alacritty' + || process$3.env.TERMINAL_EMULATOR === 'JetBrains-JediTerm'; +} + +const main = { + info: chalk$5.blue('ℹ'), + success: chalk$5.green('✔'), + warning: chalk$5.yellow('⚠'), + error: chalk$5.red('✖'), +}; + +const fallback = { + info: chalk$5.blue('i'), + success: chalk$5.green('√'), + warning: chalk$5.yellow('‼'), + error: chalk$5.red('×'), +}; + +const logSymbols = isUnicodeSupported() ? main : fallback; + +function ansiRegex({onlyFirst = false} = {}) { + const pattern = [ + '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)', + '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))' + ].join('|'); + + return new RegExp(pattern, onlyFirst ? undefined : 'g'); +} + +const regex$1 = ansiRegex(); + +function stripAnsi$1(string) { + if (typeof string !== 'string') { + throw new TypeError(`Expected a \`string\`, got \`${typeof string}\``); + } + + // Even though the regex is global, we don't need to reset the `.lastIndex` + // because unlike `.exec()` and `.test()`, `.replace()` does it automatically + // and doing it manually has a performance penalty. + return string.replace(regex$1, ''); +} + +var wcwidth$2 = {exports: {}}; + +var clone$2 = {exports: {}}; + +(function (module) { + var clone = (function() { + + /** + * Clones (copies) an Object using deep copying. + * + * This function supports circular references by default, but if you are certain + * there are no circular references in your object, you can save some CPU time + * by calling clone(obj, false). + * + * Caution: if `circular` is false and `parent` contains circular references, + * your program may enter an infinite loop and crash. + * + * @param `parent` - the object to be cloned + * @param `circular` - set to true if the object to be cloned may contain + * circular references. (optional - true by default) + * @param `depth` - set to a number if the object is only to be cloned to + * a particular depth. (optional - defaults to Infinity) + * @param `prototype` - sets the prototype to be used when cloning an object. + * (optional - defaults to parent prototype). + */ + function clone(parent, circular, depth, prototype) { + if (typeof circular === 'object') { + depth = circular.depth; + prototype = circular.prototype; + circular.filter; + circular = circular.circular; + } + // maintain two arrays for circular references, where corresponding parents + // and children have the same index + var allParents = []; + var allChildren = []; + + var useBuffer = typeof Buffer != 'undefined'; + + if (typeof circular == 'undefined') + circular = true; + + if (typeof depth == 'undefined') + depth = Infinity; + + // recurse this function so we don't reset allParents and allChildren + function _clone(parent, depth) { + // cloning null always returns null + if (parent === null) + return null; + + if (depth == 0) + return parent; + + var child; + var proto; + if (typeof parent != 'object') { + return parent; + } + + if (clone.__isArray(parent)) { + child = []; + } else if (clone.__isRegExp(parent)) { + child = new RegExp(parent.source, __getRegExpFlags(parent)); + if (parent.lastIndex) child.lastIndex = parent.lastIndex; + } else if (clone.__isDate(parent)) { + child = new Date(parent.getTime()); + } else if (useBuffer && Buffer.isBuffer(parent)) { + if (Buffer.allocUnsafe) { + // Node.js >= 4.5.0 + child = Buffer.allocUnsafe(parent.length); + } else { + // Older Node.js versions + child = new Buffer(parent.length); + } + parent.copy(child); + return child; + } else { + if (typeof prototype == 'undefined') { + proto = Object.getPrototypeOf(parent); + child = Object.create(proto); + } + else { + child = Object.create(prototype); + proto = prototype; + } + } + + if (circular) { + var index = allParents.indexOf(parent); + + if (index != -1) { + return allChildren[index]; + } + allParents.push(parent); + allChildren.push(child); + } + + for (var i in parent) { + var attrs; + if (proto) { + attrs = Object.getOwnPropertyDescriptor(proto, i); + } + + if (attrs && attrs.set == null) { + continue; + } + child[i] = _clone(parent[i], depth - 1); + } + + return child; + } + + return _clone(parent, depth); + } + + /** + * Simple flat clone using prototype, accepts only objects, usefull for property + * override on FLAT configuration object (no nested props). + * + * USE WITH CAUTION! This may not behave as you wish if you do not know how this + * works. + */ + clone.clonePrototype = function clonePrototype(parent) { + if (parent === null) + return null; + + var c = function () {}; + c.prototype = parent; + return new c(); + }; + + // private utility functions + + function __objToStr(o) { + return Object.prototype.toString.call(o); + } clone.__objToStr = __objToStr; + + function __isDate(o) { + return typeof o === 'object' && __objToStr(o) === '[object Date]'; + } clone.__isDate = __isDate; + + function __isArray(o) { + return typeof o === 'object' && __objToStr(o) === '[object Array]'; + } clone.__isArray = __isArray; + + function __isRegExp(o) { + return typeof o === 'object' && __objToStr(o) === '[object RegExp]'; + } clone.__isRegExp = __isRegExp; + + function __getRegExpFlags(re) { + var flags = ''; + if (re.global) flags += 'g'; + if (re.ignoreCase) flags += 'i'; + if (re.multiline) flags += 'm'; + return flags; + } clone.__getRegExpFlags = __getRegExpFlags; + + return clone; + })(); + + if (module.exports) { + module.exports = clone; + } +} (clone$2)); + +var cloneExports = clone$2.exports; + +var clone$1 = cloneExports; + +var defaults$4 = function(options, defaults) { + options = options || {}; + + Object.keys(defaults).forEach(function(key) { + if (typeof options[key] === 'undefined') { + options[key] = clone$1(defaults[key]); + } + }); + + return options; +}; + +var combining$1 = [ + [ 0x0300, 0x036F ], [ 0x0483, 0x0486 ], [ 0x0488, 0x0489 ], + [ 0x0591, 0x05BD ], [ 0x05BF, 0x05BF ], [ 0x05C1, 0x05C2 ], + [ 0x05C4, 0x05C5 ], [ 0x05C7, 0x05C7 ], [ 0x0600, 0x0603 ], + [ 0x0610, 0x0615 ], [ 0x064B, 0x065E ], [ 0x0670, 0x0670 ], + [ 0x06D6, 0x06E4 ], [ 0x06E7, 0x06E8 ], [ 0x06EA, 0x06ED ], + [ 0x070F, 0x070F ], [ 0x0711, 0x0711 ], [ 0x0730, 0x074A ], + [ 0x07A6, 0x07B0 ], [ 0x07EB, 0x07F3 ], [ 0x0901, 0x0902 ], + [ 0x093C, 0x093C ], [ 0x0941, 0x0948 ], [ 0x094D, 0x094D ], + [ 0x0951, 0x0954 ], [ 0x0962, 0x0963 ], [ 0x0981, 0x0981 ], + [ 0x09BC, 0x09BC ], [ 0x09C1, 0x09C4 ], [ 0x09CD, 0x09CD ], + [ 0x09E2, 0x09E3 ], [ 0x0A01, 0x0A02 ], [ 0x0A3C, 0x0A3C ], + [ 0x0A41, 0x0A42 ], [ 0x0A47, 0x0A48 ], [ 0x0A4B, 0x0A4D ], + [ 0x0A70, 0x0A71 ], [ 0x0A81, 0x0A82 ], [ 0x0ABC, 0x0ABC ], + [ 0x0AC1, 0x0AC5 ], [ 0x0AC7, 0x0AC8 ], [ 0x0ACD, 0x0ACD ], + [ 0x0AE2, 0x0AE3 ], [ 0x0B01, 0x0B01 ], [ 0x0B3C, 0x0B3C ], + [ 0x0B3F, 0x0B3F ], [ 0x0B41, 0x0B43 ], [ 0x0B4D, 0x0B4D ], + [ 0x0B56, 0x0B56 ], [ 0x0B82, 0x0B82 ], [ 0x0BC0, 0x0BC0 ], + [ 0x0BCD, 0x0BCD ], [ 0x0C3E, 0x0C40 ], [ 0x0C46, 0x0C48 ], + [ 0x0C4A, 0x0C4D ], [ 0x0C55, 0x0C56 ], [ 0x0CBC, 0x0CBC ], + [ 0x0CBF, 0x0CBF ], [ 0x0CC6, 0x0CC6 ], [ 0x0CCC, 0x0CCD ], + [ 0x0CE2, 0x0CE3 ], [ 0x0D41, 0x0D43 ], [ 0x0D4D, 0x0D4D ], + [ 0x0DCA, 0x0DCA ], [ 0x0DD2, 0x0DD4 ], [ 0x0DD6, 0x0DD6 ], + [ 0x0E31, 0x0E31 ], [ 0x0E34, 0x0E3A ], [ 0x0E47, 0x0E4E ], + [ 0x0EB1, 0x0EB1 ], [ 0x0EB4, 0x0EB9 ], [ 0x0EBB, 0x0EBC ], + [ 0x0EC8, 0x0ECD ], [ 0x0F18, 0x0F19 ], [ 0x0F35, 0x0F35 ], + [ 0x0F37, 0x0F37 ], [ 0x0F39, 0x0F39 ], [ 0x0F71, 0x0F7E ], + [ 0x0F80, 0x0F84 ], [ 0x0F86, 0x0F87 ], [ 0x0F90, 0x0F97 ], + [ 0x0F99, 0x0FBC ], [ 0x0FC6, 0x0FC6 ], [ 0x102D, 0x1030 ], + [ 0x1032, 0x1032 ], [ 0x1036, 0x1037 ], [ 0x1039, 0x1039 ], + [ 0x1058, 0x1059 ], [ 0x1160, 0x11FF ], [ 0x135F, 0x135F ], + [ 0x1712, 0x1714 ], [ 0x1732, 0x1734 ], [ 0x1752, 0x1753 ], + [ 0x1772, 0x1773 ], [ 0x17B4, 0x17B5 ], [ 0x17B7, 0x17BD ], + [ 0x17C6, 0x17C6 ], [ 0x17C9, 0x17D3 ], [ 0x17DD, 0x17DD ], + [ 0x180B, 0x180D ], [ 0x18A9, 0x18A9 ], [ 0x1920, 0x1922 ], + [ 0x1927, 0x1928 ], [ 0x1932, 0x1932 ], [ 0x1939, 0x193B ], + [ 0x1A17, 0x1A18 ], [ 0x1B00, 0x1B03 ], [ 0x1B34, 0x1B34 ], + [ 0x1B36, 0x1B3A ], [ 0x1B3C, 0x1B3C ], [ 0x1B42, 0x1B42 ], + [ 0x1B6B, 0x1B73 ], [ 0x1DC0, 0x1DCA ], [ 0x1DFE, 0x1DFF ], + [ 0x200B, 0x200F ], [ 0x202A, 0x202E ], [ 0x2060, 0x2063 ], + [ 0x206A, 0x206F ], [ 0x20D0, 0x20EF ], [ 0x302A, 0x302F ], + [ 0x3099, 0x309A ], [ 0xA806, 0xA806 ], [ 0xA80B, 0xA80B ], + [ 0xA825, 0xA826 ], [ 0xFB1E, 0xFB1E ], [ 0xFE00, 0xFE0F ], + [ 0xFE20, 0xFE23 ], [ 0xFEFF, 0xFEFF ], [ 0xFFF9, 0xFFFB ], + [ 0x10A01, 0x10A03 ], [ 0x10A05, 0x10A06 ], [ 0x10A0C, 0x10A0F ], + [ 0x10A38, 0x10A3A ], [ 0x10A3F, 0x10A3F ], [ 0x1D167, 0x1D169 ], + [ 0x1D173, 0x1D182 ], [ 0x1D185, 0x1D18B ], [ 0x1D1AA, 0x1D1AD ], + [ 0x1D242, 0x1D244 ], [ 0xE0001, 0xE0001 ], [ 0xE0020, 0xE007F ], + [ 0xE0100, 0xE01EF ] +]; + +var defaults$3 = defaults$4; +var combining = combining$1; + +var DEFAULTS = { + nul: 0, + control: 0 +}; + +wcwidth$2.exports = function wcwidth(str) { + return wcswidth(str, DEFAULTS) +}; + +wcwidth$2.exports.config = function(opts) { + opts = defaults$3(opts || {}, DEFAULTS); + return function wcwidth(str) { + return wcswidth(str, opts) + } +}; + +/* + * The following functions define the column width of an ISO 10646 + * character as follows: + * - The null character (U+0000) has a column width of 0. + * - Other C0/C1 control characters and DEL will lead to a return value + * of -1. + * - Non-spacing and enclosing combining characters (general category + * code Mn or Me in the + * Unicode database) have a column width of 0. + * - SOFT HYPHEN (U+00AD) has a column width of 1. + * - Other format characters (general category code Cf in the Unicode + * database) and ZERO WIDTH + * SPACE (U+200B) have a column width of 0. + * - Hangul Jamo medial vowels and final consonants (U+1160-U+11FF) + * have a column width of 0. + * - Spacing characters in the East Asian Wide (W) or East Asian + * Full-width (F) category as + * defined in Unicode Technical Report #11 have a column width of 2. + * - All remaining characters (including all printable ISO 8859-1 and + * WGL4 characters, Unicode control characters, etc.) have a column + * width of 1. + * This implementation assumes that characters are encoded in ISO 10646. +*/ + +function wcswidth(str, opts) { + if (typeof str !== 'string') return wcwidth(str, opts) + + var s = 0; + for (var i = 0; i < str.length; i++) { + var n = wcwidth(str.charCodeAt(i), opts); + if (n < 0) return -1 + s += n; + } + + return s +} + +function wcwidth(ucs, opts) { + // test for 8-bit control characters + if (ucs === 0) return opts.nul + if (ucs < 32 || (ucs >= 0x7f && ucs < 0xa0)) return opts.control + + // binary search in table of non-spacing characters + if (bisearch(ucs)) return 0 + + // if we arrive here, ucs is not a combining or C0/C1 control character + return 1 + + (ucs >= 0x1100 && + (ucs <= 0x115f || // Hangul Jamo init. consonants + ucs == 0x2329 || ucs == 0x232a || + (ucs >= 0x2e80 && ucs <= 0xa4cf && + ucs != 0x303f) || // CJK ... Yi + (ucs >= 0xac00 && ucs <= 0xd7a3) || // Hangul Syllables + (ucs >= 0xf900 && ucs <= 0xfaff) || // CJK Compatibility Ideographs + (ucs >= 0xfe10 && ucs <= 0xfe19) || // Vertical forms + (ucs >= 0xfe30 && ucs <= 0xfe6f) || // CJK Compatibility Forms + (ucs >= 0xff00 && ucs <= 0xff60) || // Fullwidth Forms + (ucs >= 0xffe0 && ucs <= 0xffe6) || + (ucs >= 0x20000 && ucs <= 0x2fffd) || + (ucs >= 0x30000 && ucs <= 0x3fffd))); +} + +function bisearch(ucs) { + var min = 0; + var max = combining.length - 1; + var mid; + + if (ucs < combining[0][0] || ucs > combining[max][1]) return false + + while (max >= min) { + mid = Math.floor((min + max) / 2); + if (ucs > combining[mid][1]) min = mid + 1; + else if (ucs < combining[mid][0]) max = mid - 1; + else return true + } + + return false +} + +var wcwidthExports = wcwidth$2.exports; +var wcwidth$1 = /*@__PURE__*/getDefaultExportFromCjs(wcwidthExports); + +function isInteractive({stream = process.stdout} = {}) { + return Boolean( + stream && stream.isTTY && + process.env.TERM !== 'dumb' && + !('CI' in process.env) + ); +} + +var bl = {exports: {}}; + +var readable = {exports: {}}; + +var stream; +var hasRequiredStream; + +function requireStream () { + if (hasRequiredStream) return stream; + hasRequiredStream = 1; + stream = Stream$3; + return stream; +} + +var buffer_list; +var hasRequiredBuffer_list; + +function requireBuffer_list () { + if (hasRequiredBuffer_list) return buffer_list; + hasRequiredBuffer_list = 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) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } + function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } + function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } + function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } + var _require = require$$0$d, + Buffer = _require.Buffer; + var _require2 = require$$0$9, + inspect = _require2.inspect; + var custom = inspect && inspect.custom || 'inspect'; + function copyBuffer(src, target, offset) { + Buffer.prototype.copy.call(src, target, offset); + } + buffer_list = /*#__PURE__*/function () { + function BufferList() { + _classCallCheck(this, BufferList); + this.head = null; + this.tail = null; + this.length = 0; + } + _createClass(BufferList, [{ + key: "push", + value: function push(v) { + var entry = { + data: v, + next: null + }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + } + }, { + key: "unshift", + value: function unshift(v) { + var entry = { + data: v, + next: this.head + }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + } + }, { + key: "shift", + value: function shift() { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + } + }, { + key: "clear", + value: function clear() { + this.head = this.tail = null; + this.length = 0; + } + }, { + key: "join", + value: function join(s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) ret += s + p.data; + return ret; + } + }, { + key: "concat", + value: function concat(n) { + if (this.length === 0) return Buffer.alloc(0); + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + copyBuffer(p.data, ret, i); + i += p.data.length; + p = p.next; + } + return ret; + } + + // Consumes a specified amount of bytes or characters from the buffered data. + }, { + key: "consume", + value: function consume(n, hasStrings) { + var ret; + if (n < this.head.data.length) { + // `slice` is the same for buffers and strings. + ret = this.head.data.slice(0, n); + this.head.data = this.head.data.slice(n); + } else if (n === this.head.data.length) { + // First chunk is a perfect match. + ret = this.shift(); + } else { + // Result spans more than one buffer. + ret = hasStrings ? this._getString(n) : this._getBuffer(n); + } + return ret; + } + }, { + key: "first", + value: function first() { + return this.head.data; + } + + // Consumes a specified amount of characters from the buffered data. + }, { + key: "_getString", + value: function _getString(n) { + var p = this.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) this.head = p.next;else this.head = this.tail = null; + } else { + this.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + this.length -= c; + return ret; + } + + // Consumes a specified amount of bytes from the buffered data. + }, { + key: "_getBuffer", + value: function _getBuffer(n) { + var ret = Buffer.allocUnsafe(n); + var p = this.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) this.head = p.next;else this.head = this.tail = null; + } else { + this.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + this.length -= c; + return ret; + } + + // Make sure the linked list only shows the minimal necessary information. + }, { + key: custom, + value: function value(_, options) { + return inspect(this, _objectSpread(_objectSpread({}, options), {}, { + // Only inspect one level. + depth: 0, + // It should not recurse. + customInspect: false + })); + } + }]); + return BufferList; + }(); + return buffer_list; +} + +var destroy_1; +var hasRequiredDestroy; + +function requireDestroy () { + if (hasRequiredDestroy) return destroy_1; + hasRequiredDestroy = 1; + + // undocumented cb() API, needed for core, not for public API + function destroy(err, cb) { + var _this = this; + var readableDestroyed = this._readableState && this._readableState.destroyed; + var writableDestroyed = this._writableState && this._writableState.destroyed; + if (readableDestroyed || writableDestroyed) { + if (cb) { + cb(err); + } else if (err) { + if (!this._writableState) { + process.nextTick(emitErrorNT, this, err); + } else if (!this._writableState.errorEmitted) { + this._writableState.errorEmitted = true; + process.nextTick(emitErrorNT, this, err); + } + } + return this; + } + + // we set destroyed to true before firing error callbacks in order + // to make it re-entrance safe in case destroy() is called within callbacks + + if (this._readableState) { + this._readableState.destroyed = true; + } + + // if this is a duplex stream mark the writable part as destroyed as well + if (this._writableState) { + this._writableState.destroyed = true; + } + this._destroy(err || null, function (err) { + if (!cb && err) { + if (!_this._writableState) { + process.nextTick(emitErrorAndCloseNT, _this, err); + } else if (!_this._writableState.errorEmitted) { + _this._writableState.errorEmitted = true; + process.nextTick(emitErrorAndCloseNT, _this, err); + } else { + process.nextTick(emitCloseNT, _this); + } + } else if (cb) { + process.nextTick(emitCloseNT, _this); + cb(err); + } else { + process.nextTick(emitCloseNT, _this); + } + }); + return this; + } + function emitErrorAndCloseNT(self, err) { + emitErrorNT(self, err); + emitCloseNT(self); + } + function emitCloseNT(self) { + if (self._writableState && !self._writableState.emitClose) return; + if (self._readableState && !self._readableState.emitClose) return; + self.emit('close'); + } + function undestroy() { + if (this._readableState) { + this._readableState.destroyed = false; + this._readableState.reading = false; + this._readableState.ended = false; + this._readableState.endEmitted = false; + } + if (this._writableState) { + this._writableState.destroyed = false; + this._writableState.ended = false; + this._writableState.ending = false; + this._writableState.finalCalled = false; + this._writableState.prefinished = false; + this._writableState.finished = false; + this._writableState.errorEmitted = false; + } + } + function emitErrorNT(self, err) { + self.emit('error', err); + } + function errorOrDestroy(stream, err) { + // We have tests that rely on errors being emitted + // in the same tick, so changing this is semver major. + // For now when you opt-in to autoDestroy we allow + // the error to be emitted nextTick. In a future + // semver major update we should change the default to this. + + var rState = stream._readableState; + var wState = stream._writableState; + if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err); + } + destroy_1 = { + destroy: destroy, + undestroy: undestroy, + errorOrDestroy: errorOrDestroy + }; + return destroy_1; +} + +var errors = {}; + +var hasRequiredErrors; + +function requireErrors () { + if (hasRequiredErrors) return errors; + hasRequiredErrors = 1; + + const codes = {}; + + function createErrorType(code, message, Base) { + if (!Base) { + Base = Error; + } + + function getMessage (arg1, arg2, arg3) { + if (typeof message === 'string') { + return message + } else { + return message(arg1, arg2, arg3) + } + } + + class NodeError extends Base { + constructor (arg1, arg2, arg3) { + super(getMessage(arg1, arg2, arg3)); + } + } + + NodeError.prototype.name = Base.name; + NodeError.prototype.code = code; + + codes[code] = NodeError; + } + + // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js + function oneOf(expected, thing) { + if (Array.isArray(expected)) { + const len = expected.length; + expected = expected.map((i) => String(i)); + if (len > 2) { + return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or ` + + expected[len - 1]; + } else if (len === 2) { + return `one of ${thing} ${expected[0]} or ${expected[1]}`; + } else { + return `of ${thing} ${expected[0]}`; + } + } else { + return `of ${thing} ${String(expected)}`; + } + } + + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith + function startsWith(str, search, pos) { + return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; + } + + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith + function endsWith(str, search, this_len) { + if (this_len === undefined || this_len > str.length) { + this_len = str.length; + } + return str.substring(this_len - search.length, this_len) === search; + } + + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes + function includes(str, search, start) { + if (typeof start !== 'number') { + start = 0; + } + + if (start + search.length > str.length) { + return false; + } else { + return str.indexOf(search, start) !== -1; + } + } + + createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { + return 'The value "' + value + '" is invalid for option "' + name + '"' + }, TypeError); + createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { + // determiner: 'must be' or 'must not be' + let determiner; + if (typeof expected === 'string' && startsWith(expected, 'not ')) { + determiner = 'must not be'; + expected = expected.replace(/^not /, ''); + } else { + determiner = 'must be'; + } + + let msg; + if (endsWith(name, ' argument')) { + // For cases like 'first argument' + msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`; + } else { + const type = includes(name, '.') ? 'property' : 'argument'; + msg = `The "${name}" ${type} ${determiner} ${oneOf(expected, 'type')}`; + } + + msg += `. Received type ${typeof actual}`; + return msg; + }, TypeError); + createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); + createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { + return 'The ' + name + ' method is not implemented' + }); + createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); + createErrorType('ERR_STREAM_DESTROYED', function (name) { + return 'Cannot call ' + name + ' after a stream was destroyed'; + }); + createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times'); + createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable'); + createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end'); + createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError); + createErrorType('ERR_UNKNOWN_ENCODING', function (arg) { + return 'Unknown encoding: ' + arg + }, TypeError); + createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); + + errors.codes = codes; + return errors; +} + +var state; +var hasRequiredState; + +function requireState () { + if (hasRequiredState) return state; + hasRequiredState = 1; + + var ERR_INVALID_OPT_VALUE = requireErrors().codes.ERR_INVALID_OPT_VALUE; + function highWaterMarkFrom(options, isDuplex, duplexKey) { + return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; + } + function getHighWaterMark(state, options, duplexKey, isDuplex) { + var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); + if (hwm != null) { + if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { + var name = isDuplex ? duplexKey : 'highWaterMark'; + throw new ERR_INVALID_OPT_VALUE(name, hwm); + } + return Math.floor(hwm); + } + + // Default value + return state.objectMode ? 16 : 16 * 1024; + } + state = { + getHighWaterMark: getHighWaterMark + }; + return state; +} + +var inherits$1 = {exports: {}}; + +var inherits_browser = {exports: {}}; + +var hasRequiredInherits_browser; + +function requireInherits_browser () { + if (hasRequiredInherits_browser) return inherits_browser.exports; + hasRequiredInherits_browser = 1; + if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + inherits_browser.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + } + }; + } else { + // old school shim for old browsers + inherits_browser.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + } + }; + } + return inherits_browser.exports; +} + +try { + var util$1 = require('util'); + /* istanbul ignore next */ + if (typeof util$1.inherits !== 'function') throw ''; + inherits$1.exports = util$1.inherits; +} catch (e) { + /* istanbul ignore next */ + inherits$1.exports = requireInherits_browser(); +} + +var inheritsExports = inherits$1.exports; + +var node; +var hasRequiredNode; + +function requireNode () { + if (hasRequiredNode) return node; + hasRequiredNode = 1; + /** + * For Node.js, simply re-export the core `util.deprecate` function. + */ + + node = require$$0$9.deprecate; + return node; +} + +var _stream_writable; +var hasRequired_stream_writable; + +function require_stream_writable () { + if (hasRequired_stream_writable) return _stream_writable; + hasRequired_stream_writable = 1; + + _stream_writable = Writable; + + // It seems a linked list but it is not + // there will be only 2 of these for each stream + function CorkedRequest(state) { + var _this = this; + this.next = null; + this.entry = null; + this.finish = function () { + onCorkedFinish(_this, state); + }; + } + /* </replacement> */ + + /*<replacement>*/ + var Duplex; + /*</replacement>*/ + + Writable.WritableState = WritableState; + + /*<replacement>*/ + var internalUtil = { + deprecate: requireNode() + }; + /*</replacement>*/ + + /*<replacement>*/ + var Stream = requireStream(); + /*</replacement>*/ + + var Buffer = require$$0$d.Buffer; + var OurUint8Array = (typeof commonjsGlobal !== 'undefined' ? commonjsGlobal : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {}; + function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); + } + function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; + } + var destroyImpl = requireDestroy(); + var _require = requireState(), + getHighWaterMark = _require.getHighWaterMark; + var _require$codes = requireErrors().codes, + ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, + ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE, + ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED, + ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES, + ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END, + ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING; + var errorOrDestroy = destroyImpl.errorOrDestroy; + inheritsExports(Writable, Stream); + function nop() {} + function WritableState(options, stream, isDuplex) { + Duplex = Duplex || require_stream_duplex(); + options = options || {}; + + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream, + // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); + + // if _final has been called + this.finalCalled = false; + + // drain event flag. + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // has it been destroyed + this.destroyed = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // when true all writes will be buffered until .uncork() call + this.corked = 0; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + this.bufferedRequest = null; + this.lastBufferedRequest = null; + + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; + + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; + + // Should close be emitted on destroy. Defaults to true. + this.emitClose = options.emitClose !== false; + + // Should .destroy() be called after 'finish' (and potentially 'end') + this.autoDestroy = !!options.autoDestroy; + + // count buffered requests + this.bufferedRequestCount = 0; + + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); + } + WritableState.prototype.getBuffer = function getBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; + }; + (function () { + try { + Object.defineProperty(WritableState.prototype, 'buffer', { + get: internalUtil.deprecate(function writableStateBufferGetter() { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') + }); + } catch (_) {} + })(); + + // Test _writableState for inheritance to account for Duplex streams, + // whose prototype chain only points to Readable. + var realHasInstance; + if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { + realHasInstance = Function.prototype[Symbol.hasInstance]; + Object.defineProperty(Writable, Symbol.hasInstance, { + value: function value(object) { + if (realHasInstance.call(this, object)) return true; + if (this !== Writable) return false; + return object && object._writableState instanceof WritableState; + } + }); + } else { + realHasInstance = function realHasInstance(object) { + return object instanceof this; + }; + } + function Writable(options) { + Duplex = Duplex || require_stream_duplex(); + + // Writable ctor is applied to Duplexes, too. + // `realHasInstance` is necessary because using plain `instanceof` + // would return false, as no `_writableState` property is attached. + + // Trying to use the custom `instanceof` for Writable here will also break the + // Node.js LazyTransform implementation, which has a non-trivial getter for + // `_writableState` that would lead to infinite recursion. + + // Checking for a Stream.Duplex instance is faster here instead of inside + // the WritableState constructor, at least with V8 6.5 + var isDuplex = this instanceof Duplex; + if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options); + this._writableState = new WritableState(options, this, isDuplex); + + // legacy. + this.writable = true; + if (options) { + if (typeof options.write === 'function') this._write = options.write; + if (typeof options.writev === 'function') this._writev = options.writev; + if (typeof options.destroy === 'function') this._destroy = options.destroy; + if (typeof options.final === 'function') this._final = options.final; + } + Stream.call(this); + } + + // Otherwise people can pipe Writable streams, which is just wrong. + Writable.prototype.pipe = function () { + errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); + }; + function writeAfterEnd(stream, cb) { + var er = new ERR_STREAM_WRITE_AFTER_END(); + // TODO: defer error events consistently everywhere, not just the cb + errorOrDestroy(stream, er); + process.nextTick(cb, er); + } + + // Checks that a user-supplied chunk is valid, especially for the particular + // mode the stream is in. Currently this means that `null` is never accepted + // and undefined/non-string values are only allowed in object mode. + function validChunk(stream, state, chunk, cb) { + var er; + if (chunk === null) { + er = new ERR_STREAM_NULL_VALUES(); + } else if (typeof chunk !== 'string' && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk); + } + if (er) { + errorOrDestroy(stream, er); + process.nextTick(cb, er); + return false; + } + return true; + } + Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + var isBuf = !state.objectMode && _isUint8Array(chunk); + if (isBuf && !Buffer.isBuffer(chunk)) { + chunk = _uint8ArrayToBuffer(chunk); + } + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + if (typeof cb !== 'function') cb = nop; + if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); + } + return ret; + }; + Writable.prototype.cork = function () { + this._writableState.corked++; + }; + Writable.prototype.uncork = function () { + var state = this._writableState; + if (state.corked) { + state.corked--; + if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } + }; + Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); + this._writableState.defaultEncoding = encoding; + return this; + }; + Object.defineProperty(Writable.prototype, 'writableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState && this._writableState.getBuffer(); + } + }); + function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + return chunk; + } + Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.highWaterMark; + } + }); + + // if we're already writing something, then just put this + // in the queue, and wait our turn. Otherwise, call _write + // If we return false, then we need a drain event, so set that flag. + function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { + if (!isBuf) { + var newChunk = decodeChunk(state, chunk, encoding); + if (chunk !== newChunk) { + isBuf = true; + encoding = 'buffer'; + chunk = newChunk; + } + } + var len = state.objectMode ? 1 : chunk.length; + state.length += len; + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = { + chunk: chunk, + encoding: encoding, + isBuf: isBuf, + callback: cb, + next: null + }; + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + return ret; + } + function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; + } + function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + if (sync) { + // defer the callback if we are being called synchronously + // to avoid piling up things on the stack + process.nextTick(cb, er); + // this can emit finish, and it will always happen + // after error + process.nextTick(finishMaybe, stream, state); + stream._writableState.errorEmitted = true; + errorOrDestroy(stream, er); + } else { + // the caller expect this to happen before if + // it is async + cb(er); + stream._writableState.errorEmitted = true; + errorOrDestroy(stream, er); + // this can emit finish, but finish must + // always follow error + finishMaybe(stream, state); + } + } + function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; + } + function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK(); + onwriteStateUpdate(state); + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state) || stream.destroyed; + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + if (sync) { + process.nextTick(afterWrite, stream, state, finished, cb); + } else { + afterWrite(stream, state, finished, cb); + } + } + } + function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); + } + + // Must force callback to be called on nextTick, so that we don't + // emit 'drain' before the write() consumer gets the 'false' return + // value, and has a chance to attach a 'drain' listener. + function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } + } + + // if there's something in the buffer waiting, then process it + function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + var count = 0; + var allBuffers = true; + while (entry) { + buffer[count] = entry; + if (!entry.isBuf) allBuffers = false; + entry = entry.next; + count += 1; + } + buffer.allBuffers = allBuffers; + doWrite(stream, state, true, state.length, buffer, '', holder.finish); + + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + state.bufferedRequestCount = 0; + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + state.bufferedRequestCount--; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } + if (entry === null) state.lastBufferedRequest = null; + } + state.bufferedRequest = entry; + state.bufferProcessing = false; + } + Writable.prototype._write = function (chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()')); + }; + Writable.prototype._writev = null; + Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } + + // ignore unnecessary end() calls. + if (!state.ending) endWritable(this, state, cb); + return this; + }; + Object.defineProperty(Writable.prototype, 'writableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.length; + } + }); + function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; + } + function callFinal(stream, state) { + stream._final(function (err) { + state.pendingcb--; + if (err) { + errorOrDestroy(stream, err); + } + state.prefinished = true; + stream.emit('prefinish'); + finishMaybe(stream, state); + }); + } + function prefinish(stream, state) { + if (!state.prefinished && !state.finalCalled) { + if (typeof stream._final === 'function' && !state.destroyed) { + state.pendingcb++; + state.finalCalled = true; + process.nextTick(callFinal, stream, state); + } else { + state.prefinished = true; + stream.emit('prefinish'); + } + } + } + function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + prefinish(stream, state); + if (state.pendingcb === 0) { + state.finished = true; + stream.emit('finish'); + if (state.autoDestroy) { + // In case of duplex streams we need a way to detect + // if the readable side is ready for autoDestroy as well + var rState = stream._readableState; + if (!rState || rState.autoDestroy && rState.endEmitted) { + stream.destroy(); + } + } + } + } + return need; + } + function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) process.nextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; + } + function onCorkedFinish(corkReq, state, err) { + var entry = corkReq.entry; + corkReq.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + + // reuse the free corkReq. + state.corkedRequestsFree.next = corkReq; + } + Object.defineProperty(Writable.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._writableState === undefined) { + return false; + } + return this._writableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._writableState) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._writableState.destroyed = value; + } + }); + Writable.prototype.destroy = destroyImpl.destroy; + Writable.prototype._undestroy = destroyImpl.undestroy; + Writable.prototype._destroy = function (err, cb) { + cb(err); + }; + return _stream_writable; +} + +var _stream_duplex; +var hasRequired_stream_duplex; + +function require_stream_duplex () { + if (hasRequired_stream_duplex) return _stream_duplex; + hasRequired_stream_duplex = 1; + + /*<replacement>*/ + var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) keys.push(key); + return keys; + }; + /*</replacement>*/ + + _stream_duplex = Duplex; + var Readable = require_stream_readable(); + var Writable = require_stream_writable(); + inheritsExports(Duplex, Readable); + { + // Allow the keys array to be GC'ed. + var keys = objectKeys(Writable.prototype); + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + } + } + function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + Readable.call(this, options); + Writable.call(this, options); + this.allowHalfOpen = true; + if (options) { + if (options.readable === false) this.readable = false; + if (options.writable === false) this.writable = false; + if (options.allowHalfOpen === false) { + this.allowHalfOpen = false; + this.once('end', onend); + } + } + } + Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.highWaterMark; + } + }); + Object.defineProperty(Duplex.prototype, 'writableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState && this._writableState.getBuffer(); + } + }); + Object.defineProperty(Duplex.prototype, 'writableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.length; + } + }); + + // the no-half-open enforcer + function onend() { + // If the writable side ended, then we're ok. + if (this._writableState.ended) return; + + // no more data can be written. + // But allow more writes to happen in this tick. + process.nextTick(onEndNT, this); + } + function onEndNT(self) { + self.end(); + } + Object.defineProperty(Duplex.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._readableState === undefined || this._writableState === undefined) { + return false; + } + return this._readableState.destroyed && this._writableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (this._readableState === undefined || this._writableState === undefined) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + this._writableState.destroyed = value; + } + }); + return _stream_duplex; +} + +var string_decoder = {}; + +var safeBuffer = {exports: {}}; + +/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */ + +var hasRequiredSafeBuffer; + +function requireSafeBuffer () { + if (hasRequiredSafeBuffer) return safeBuffer.exports; + hasRequiredSafeBuffer = 1; + (function (module, exports) { + /* eslint-disable node/no-deprecated-api */ + var buffer = require$$0$d; + var Buffer = buffer.Buffer; + + // alternative to using Object.keys for old browsers + function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key]; + } + } + if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer; + } else { + // Copy properties from require('buffer') + copyProps(buffer, exports); + exports.Buffer = SafeBuffer; + } + + function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) + } + + SafeBuffer.prototype = Object.create(Buffer.prototype); + + // Copy static methods from Buffer + copyProps(Buffer, SafeBuffer); + + SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) + }; + + SafeBuffer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + var buf = Buffer(size); + if (fill !== undefined) { + if (typeof encoding === 'string') { + buf.fill(fill, encoding); + } else { + buf.fill(fill); + } + } else { + buf.fill(0); + } + return buf + }; + + SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) + }; + + SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) + }; + } (safeBuffer, safeBuffer.exports)); + return safeBuffer.exports; +} + +var hasRequiredString_decoder; + +function requireString_decoder () { + if (hasRequiredString_decoder) return string_decoder; + hasRequiredString_decoder = 1; + + /*<replacement>*/ + + var Buffer = requireSafeBuffer().Buffer; + /*</replacement>*/ + + var isEncoding = Buffer.isEncoding || function (encoding) { + encoding = '' + encoding; + switch (encoding && encoding.toLowerCase()) { + case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': + return true; + default: + return false; + } + }; + + function _normalizeEncoding(enc) { + if (!enc) return 'utf8'; + var retried; + while (true) { + switch (enc) { + case 'utf8': + case 'utf-8': + return 'utf8'; + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return 'utf16le'; + case 'latin1': + case 'binary': + return 'latin1'; + case 'base64': + case 'ascii': + case 'hex': + return enc; + default: + if (retried) return; // undefined + enc = ('' + enc).toLowerCase(); + retried = true; + } + } + } + // Do not cache `Buffer.isEncoding` when checking encoding names as some + // modules monkey-patch it to support additional encodings + function normalizeEncoding(enc) { + var nenc = _normalizeEncoding(enc); + if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); + return nenc || enc; + } + + // StringDecoder provides an interface for efficiently splitting a series of + // buffers into a series of JS strings without breaking apart multi-byte + // characters. + string_decoder.StringDecoder = StringDecoder; + function StringDecoder(encoding) { + this.encoding = normalizeEncoding(encoding); + var nb; + switch (this.encoding) { + case 'utf16le': + this.text = utf16Text; + this.end = utf16End; + nb = 4; + break; + case 'utf8': + this.fillLast = utf8FillLast; + nb = 4; + break; + case 'base64': + this.text = base64Text; + this.end = base64End; + nb = 3; + break; + default: + this.write = simpleWrite; + this.end = simpleEnd; + return; + } + this.lastNeed = 0; + this.lastTotal = 0; + this.lastChar = Buffer.allocUnsafe(nb); + } + + StringDecoder.prototype.write = function (buf) { + if (buf.length === 0) return ''; + var r; + var i; + if (this.lastNeed) { + r = this.fillLast(buf); + if (r === undefined) return ''; + i = this.lastNeed; + this.lastNeed = 0; + } else { + i = 0; + } + if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); + return r || ''; + }; + + StringDecoder.prototype.end = utf8End; + + // Returns only complete characters in a Buffer + StringDecoder.prototype.text = utf8Text; + + // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer + StringDecoder.prototype.fillLast = function (buf) { + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); + this.lastNeed -= buf.length; + }; + + // Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a + // continuation byte. If an invalid byte is detected, -2 is returned. + function utf8CheckByte(byte) { + if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; + return byte >> 6 === 0x02 ? -1 : -2; + } + + // Checks at most 3 bytes at the end of a Buffer in order to detect an + // incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) + // needed to complete the UTF-8 character (if applicable) are returned. + function utf8CheckIncomplete(self, buf, i) { + var j = buf.length - 1; + if (j < i) return 0; + var nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 1; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 2; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) { + if (nb === 2) nb = 0;else self.lastNeed = nb - 3; + } + return nb; + } + return 0; + } + + // Validates as many continuation bytes for a multi-byte UTF-8 character as + // needed or are available. If we see a non-continuation byte where we expect + // one, we "replace" the validated continuation bytes we've seen so far with + // a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding + // behavior. The continuation byte check is included three times in the case + // where all of the continuation bytes for a character exist in the same buffer. + // It is also done this way as a slight performance increase instead of using a + // loop. + function utf8CheckExtraBytes(self, buf, p) { + if ((buf[0] & 0xC0) !== 0x80) { + self.lastNeed = 0; + return '\ufffd'; + } + if (self.lastNeed > 1 && buf.length > 1) { + if ((buf[1] & 0xC0) !== 0x80) { + self.lastNeed = 1; + return '\ufffd'; + } + if (self.lastNeed > 2 && buf.length > 2) { + if ((buf[2] & 0xC0) !== 0x80) { + self.lastNeed = 2; + return '\ufffd'; + } + } + } + } + + // Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. + function utf8FillLast(buf) { + var p = this.lastTotal - this.lastNeed; + var r = utf8CheckExtraBytes(this, buf); + if (r !== undefined) return r; + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, p, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, p, 0, buf.length); + this.lastNeed -= buf.length; + } + + // Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a + // partial character, the character's bytes are buffered until the required + // number of bytes are available. + function utf8Text(buf, i) { + var total = utf8CheckIncomplete(this, buf, i); + if (!this.lastNeed) return buf.toString('utf8', i); + this.lastTotal = total; + var end = buf.length - (total - this.lastNeed); + buf.copy(this.lastChar, 0, end); + return buf.toString('utf8', i, end); + } + + // For UTF-8, a replacement character is added when ending on a partial + // character. + function utf8End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + '\ufffd'; + return r; + } + + // UTF-16LE typically needs two bytes per character, but even if we have an even + // number of bytes available, we need to check if we end on a leading/high + // surrogate. In that case, we need to wait for the next two bytes in order to + // decode the last character properly. + function utf16Text(buf, i) { + if ((buf.length - i) % 2 === 0) { + var r = buf.toString('utf16le', i); + if (r) { + var c = r.charCodeAt(r.length - 1); + if (c >= 0xD800 && c <= 0xDBFF) { + this.lastNeed = 2; + this.lastTotal = 4; + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + return r.slice(0, -1); + } + } + return r; + } + this.lastNeed = 1; + this.lastTotal = 2; + this.lastChar[0] = buf[buf.length - 1]; + return buf.toString('utf16le', i, buf.length - 1); + } + + // For UTF-16LE we do not explicitly append special replacement characters if we + // end on a partial character, we simply let v8 handle that. + function utf16End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) { + var end = this.lastTotal - this.lastNeed; + return r + this.lastChar.toString('utf16le', 0, end); + } + return r; + } + + function base64Text(buf, i) { + var n = (buf.length - i) % 3; + if (n === 0) return buf.toString('base64', i); + this.lastNeed = 3 - n; + this.lastTotal = 3; + if (n === 1) { + this.lastChar[0] = buf[buf.length - 1]; + } else { + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + } + return buf.toString('base64', i, buf.length - n); + } + + function base64End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); + return r; + } + + // Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) + function simpleWrite(buf) { + return buf.toString(this.encoding); + } + + function simpleEnd(buf) { + return buf && buf.length ? this.write(buf) : ''; + } + return string_decoder; +} + +var endOfStream; +var hasRequiredEndOfStream; + +function requireEndOfStream () { + if (hasRequiredEndOfStream) return endOfStream; + hasRequiredEndOfStream = 1; + + var ERR_STREAM_PREMATURE_CLOSE = requireErrors().codes.ERR_STREAM_PREMATURE_CLOSE; + function once(callback) { + var called = false; + return function () { + if (called) return; + called = true; + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + callback.apply(this, args); + }; + } + function noop() {} + function isRequest(stream) { + return stream.setHeader && typeof stream.abort === 'function'; + } + function eos(stream, opts, callback) { + if (typeof opts === 'function') return eos(stream, null, opts); + if (!opts) opts = {}; + callback = once(callback || noop); + var readable = opts.readable || opts.readable !== false && stream.readable; + var writable = opts.writable || opts.writable !== false && stream.writable; + var onlegacyfinish = function onlegacyfinish() { + if (!stream.writable) onfinish(); + }; + var writableEnded = stream._writableState && stream._writableState.finished; + var onfinish = function onfinish() { + writable = false; + writableEnded = true; + if (!readable) callback.call(stream); + }; + var readableEnded = stream._readableState && stream._readableState.endEmitted; + var onend = function onend() { + readable = false; + readableEnded = true; + if (!writable) callback.call(stream); + }; + var onerror = function onerror(err) { + callback.call(stream, err); + }; + var onclose = function onclose() { + var err; + if (readable && !readableEnded) { + if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); + } + if (writable && !writableEnded) { + if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); + } + }; + var onrequest = function onrequest() { + stream.req.on('finish', onfinish); + }; + if (isRequest(stream)) { + stream.on('complete', onfinish); + stream.on('abort', onclose); + if (stream.req) onrequest();else stream.on('request', onrequest); + } else if (writable && !stream._writableState) { + // legacy streams + stream.on('end', onlegacyfinish); + stream.on('close', onlegacyfinish); + } + stream.on('end', onend); + stream.on('finish', onfinish); + if (opts.error !== false) stream.on('error', onerror); + stream.on('close', onclose); + return function () { + stream.removeListener('complete', onfinish); + stream.removeListener('abort', onclose); + stream.removeListener('request', onrequest); + if (stream.req) stream.req.removeListener('finish', onfinish); + stream.removeListener('end', onlegacyfinish); + stream.removeListener('close', onlegacyfinish); + stream.removeListener('finish', onfinish); + stream.removeListener('end', onend); + stream.removeListener('error', onerror); + stream.removeListener('close', onclose); + }; + } + endOfStream = eos; + return endOfStream; +} + +var async_iterator; +var hasRequiredAsync_iterator; + +function requireAsync_iterator () { + if (hasRequiredAsync_iterator) return async_iterator; + hasRequiredAsync_iterator = 1; + + var _Object$setPrototypeO; + function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } + function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } + var finished = requireEndOfStream(); + var kLastResolve = Symbol('lastResolve'); + var kLastReject = Symbol('lastReject'); + var kError = Symbol('error'); + var kEnded = Symbol('ended'); + var kLastPromise = Symbol('lastPromise'); + var kHandlePromise = Symbol('handlePromise'); + var kStream = Symbol('stream'); + function createIterResult(value, done) { + return { + value: value, + done: done + }; + } + function readAndResolve(iter) { + var resolve = iter[kLastResolve]; + if (resolve !== null) { + var data = iter[kStream].read(); + // we defer if data is null + // we can be expecting either 'end' or + // 'error' + if (data !== null) { + iter[kLastPromise] = null; + iter[kLastResolve] = null; + iter[kLastReject] = null; + resolve(createIterResult(data, false)); + } + } + } + function onReadable(iter) { + // we wait for the next tick, because it might + // emit an error with process.nextTick + process.nextTick(readAndResolve, iter); + } + function wrapForNext(lastPromise, iter) { + return function (resolve, reject) { + lastPromise.then(function () { + if (iter[kEnded]) { + resolve(createIterResult(undefined, true)); + return; + } + iter[kHandlePromise](resolve, reject); + }, reject); + }; + } + var AsyncIteratorPrototype = Object.getPrototypeOf(function () {}); + var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { + get stream() { + return this[kStream]; + }, + next: function next() { + var _this = this; + // if we have detected an error in the meanwhile + // reject straight away + var error = this[kError]; + if (error !== null) { + return Promise.reject(error); + } + if (this[kEnded]) { + return Promise.resolve(createIterResult(undefined, true)); + } + if (this[kStream].destroyed) { + // We need to defer via nextTick because if .destroy(err) is + // called, the error will be emitted via nextTick, and + // we cannot guarantee that there is no error lingering around + // waiting to be emitted. + return new Promise(function (resolve, reject) { + process.nextTick(function () { + if (_this[kError]) { + reject(_this[kError]); + } else { + resolve(createIterResult(undefined, true)); + } + }); + }); + } + + // if we have multiple next() calls + // we will wait for the previous Promise to finish + // this logic is optimized to support for await loops, + // where next() is only called once at a time + var lastPromise = this[kLastPromise]; + var promise; + if (lastPromise) { + promise = new Promise(wrapForNext(lastPromise, this)); + } else { + // fast path needed to support multiple this.push() + // without triggering the next() queue + var data = this[kStream].read(); + if (data !== null) { + return Promise.resolve(createIterResult(data, false)); + } + promise = new Promise(this[kHandlePromise]); + } + this[kLastPromise] = promise; + return promise; + } + }, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () { + return this; + }), _defineProperty(_Object$setPrototypeO, "return", function _return() { + var _this2 = this; + // destroy(err, cb) is a private API + // we can guarantee we have that here, because we control the + // Readable class this is attached to + return new Promise(function (resolve, reject) { + _this2[kStream].destroy(null, function (err) { + if (err) { + reject(err); + return; + } + resolve(createIterResult(undefined, true)); + }); + }); + }), _Object$setPrototypeO), AsyncIteratorPrototype); + var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) { + var _Object$create; + var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { + value: stream, + writable: true + }), _defineProperty(_Object$create, kLastResolve, { + value: null, + writable: true + }), _defineProperty(_Object$create, kLastReject, { + value: null, + writable: true + }), _defineProperty(_Object$create, kError, { + value: null, + writable: true + }), _defineProperty(_Object$create, kEnded, { + value: stream._readableState.endEmitted, + writable: true + }), _defineProperty(_Object$create, kHandlePromise, { + value: function value(resolve, reject) { + var data = iterator[kStream].read(); + if (data) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(data, false)); + } else { + iterator[kLastResolve] = resolve; + iterator[kLastReject] = reject; + } + }, + writable: true + }), _Object$create)); + iterator[kLastPromise] = null; + finished(stream, function (err) { + if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { + var reject = iterator[kLastReject]; + // reject if we are waiting for data in the Promise + // returned by next() and store the error + if (reject !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + reject(err); + } + iterator[kError] = err; + return; + } + var resolve = iterator[kLastResolve]; + if (resolve !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(undefined, true)); + } + iterator[kEnded] = true; + }); + stream.on('readable', onReadable.bind(null, iterator)); + return iterator; + }; + async_iterator = createReadableStreamAsyncIterator; + return async_iterator; +} + +var from_1; +var hasRequiredFrom$1; + +function requireFrom$1 () { + if (hasRequiredFrom$1) return from_1; + hasRequiredFrom$1 = 1; + + function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } + function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } + function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); 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) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } + function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } + var ERR_INVALID_ARG_TYPE = requireErrors().codes.ERR_INVALID_ARG_TYPE; + function from(Readable, iterable, opts) { + var iterator; + if (iterable && typeof iterable.next === 'function') { + iterator = iterable; + } else if (iterable && iterable[Symbol.asyncIterator]) iterator = iterable[Symbol.asyncIterator]();else if (iterable && iterable[Symbol.iterator]) iterator = iterable[Symbol.iterator]();else throw new ERR_INVALID_ARG_TYPE('iterable', ['Iterable'], iterable); + var readable = new Readable(_objectSpread({ + objectMode: true + }, opts)); + // Reading boolean to protect against _read + // being called before last iteration completion. + var reading = false; + readable._read = function () { + if (!reading) { + reading = true; + next(); + } + }; + function next() { + return _next2.apply(this, arguments); + } + function _next2() { + _next2 = _asyncToGenerator(function* () { + try { + var _yield$iterator$next = yield iterator.next(), + value = _yield$iterator$next.value, + done = _yield$iterator$next.done; + if (done) { + readable.push(null); + } else if (readable.push(yield value)) { + next(); + } else { + reading = false; + } + } catch (err) { + readable.destroy(err); + } + }); + return _next2.apply(this, arguments); + } + return readable; + } + from_1 = from; + return from_1; +} + +var _stream_readable; +var hasRequired_stream_readable; + +function require_stream_readable () { + if (hasRequired_stream_readable) return _stream_readable; + hasRequired_stream_readable = 1; + + _stream_readable = Readable; + + /*<replacement>*/ + var Duplex; + /*</replacement>*/ + + Readable.ReadableState = ReadableState; + + /*<replacement>*/ + require$$2$3.EventEmitter; + var EElistenerCount = function EElistenerCount(emitter, type) { + return emitter.listeners(type).length; + }; + /*</replacement>*/ + + /*<replacement>*/ + var Stream = requireStream(); + /*</replacement>*/ + + var Buffer = require$$0$d.Buffer; + var OurUint8Array = (typeof commonjsGlobal !== 'undefined' ? commonjsGlobal : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {}; + function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); + } + function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; + } + + /*<replacement>*/ + var debugUtil = require$$0$9; + var debug; + if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog('stream'); + } else { + debug = function debug() {}; + } + /*</replacement>*/ + + var BufferList = requireBuffer_list(); + var destroyImpl = requireDestroy(); + var _require = requireState(), + getHighWaterMark = _require.getHighWaterMark; + var _require$codes = requireErrors().codes, + ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, + ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; + + // Lazy loaded to improve the startup performance. + var StringDecoder; + var createReadableStreamAsyncIterator; + var from; + inheritsExports(Readable, Stream); + var errorOrDestroy = destroyImpl.errorOrDestroy; + var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; + function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); + + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; + } + function ReadableState(options, stream, isDuplex) { + Duplex = Duplex || require_stream_duplex(); + options = options || {}; + + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); + + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // a flag to be able to tell if the event 'readable'/'data' is emitted + // immediately, or on a later tick. We set this to true at first, because + // any actions that shouldn't happen until "later" should generally also + // not happen before the first read call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + this.paused = true; + + // Should close be emitted on destroy. Defaults to true. + this.emitClose = options.emitClose !== false; + + // Should .destroy() be called after 'end' (and potentially 'finish') + this.autoDestroy = !!options.autoDestroy; + + // has it been destroyed + this.destroyed = false; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + this.decoder = null; + this.encoding = null; + if (options.encoding) { + if (!StringDecoder) StringDecoder = requireString_decoder().StringDecoder; + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } + } + function Readable(options) { + Duplex = Duplex || require_stream_duplex(); + if (!(this instanceof Readable)) return new Readable(options); + + // Checking for a Stream.Duplex instance is faster here instead of inside + // the ReadableState constructor, at least with V8 6.5 + var isDuplex = this instanceof Duplex; + this._readableState = new ReadableState(options, this, isDuplex); + + // legacy + this.readable = true; + if (options) { + if (typeof options.read === 'function') this._read = options.read; + if (typeof options.destroy === 'function') this._destroy = options.destroy; + } + Stream.call(this); + } + Object.defineProperty(Readable.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._readableState === undefined) { + return false; + } + return this._readableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._readableState) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + } + }); + Readable.prototype.destroy = destroyImpl.destroy; + Readable.prototype._undestroy = destroyImpl.undestroy; + Readable.prototype._destroy = function (err, cb) { + cb(err); + }; + + // Manually shove something into the read() buffer. + // This returns true if the highWaterMark has not been hit yet, + // similar to how Writable.write() returns true if you should + // write() some more. + Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + var skipChunkCheck; + if (!state.objectMode) { + if (typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + skipChunkCheck = true; + } + } else { + skipChunkCheck = true; + } + return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); + }; + + // Unshift should *always* be something directly out of read() + Readable.prototype.unshift = function (chunk) { + return readableAddChunk(this, chunk, null, true, false); + }; + function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { + debug('readableAddChunk', chunk); + var state = stream._readableState; + if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else { + var er; + if (!skipChunkCheck) er = chunkInvalid(state, chunk); + if (er) { + errorOrDestroy(stream, er); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { + chunk = _uint8ArrayToBuffer(chunk); + } + if (addToFront) { + if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true); + } else if (state.ended) { + errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); + } else if (state.destroyed) { + return false; + } else { + state.reading = false; + if (state.decoder && !encoding) { + chunk = state.decoder.write(chunk); + if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); + } else { + addChunk(stream, state, chunk, false); + } + } + } else if (!addToFront) { + state.reading = false; + maybeReadMore(stream, state); + } + } + + // We can push more data if we are below the highWaterMark. + // Also, if we have no data yet, we can stand some more bytes. + // This is to work around cases where hwm=0, such as the repl. + return !state.ended && (state.length < state.highWaterMark || state.length === 0); + } + function addChunk(stream, state, chunk, addToFront) { + if (state.flowing && state.length === 0 && !state.sync) { + state.awaitDrain = 0; + stream.emit('data', chunk); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + if (state.needReadable) emitReadable(stream); + } + maybeReadMore(stream, state); + } + function chunkInvalid(state, chunk) { + var er; + if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); + } + return er; + } + Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; + }; + + // backwards compatibility. + Readable.prototype.setEncoding = function (enc) { + if (!StringDecoder) StringDecoder = requireString_decoder().StringDecoder; + var decoder = new StringDecoder(enc); + this._readableState.decoder = decoder; + // If setEncoding(null), decoder.encoding equals utf8 + this._readableState.encoding = this._readableState.decoder.encoding; + + // Iterate over current buffer to convert already stored Buffers: + var p = this._readableState.buffer.head; + var content = ''; + while (p !== null) { + content += decoder.write(p.data); + p = p.next; + } + this._readableState.buffer.clear(); + if (content !== '') this._readableState.buffer.push(content); + this._readableState.length = content.length; + return this; + }; + + // Don't raise the hwm > 1GB + var MAX_HWM = 0x40000000; + function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE. + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; + } + + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; + } + + // you can override either this method, or the async _read(n) below. + Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + if (n !== 0) state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); + + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); + } + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + if (ret === null) { + state.needReadable = state.length <= state.highWaterMark; + n = 0; + } else { + state.length -= n; + state.awaitDrain = 0; + } + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; + + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } + if (ret !== null) this.emit('data', ret); + return ret; + }; + function onEofChunk(stream, state) { + debug('onEofChunk'); + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + if (state.sync) { + // if we are sync, wait until next tick to emit the data. + // Otherwise we risk emitting data in the flow() + // the readable code triggers during a read() call + emitReadable(stream); + } else { + // emit 'readable' now to make sure it gets picked up. + state.needReadable = false; + if (!state.emittedReadable) { + state.emittedReadable = true; + emitReadable_(stream); + } + } + } + + // Don't emit readable right away in sync mode, because this can trigger + // another read() call => stack overflow. This way, it might trigger + // a nextTick recursion warning, but that's not so bad. + function emitReadable(stream) { + var state = stream._readableState; + debug('emitReadable', state.needReadable, state.emittedReadable); + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + process.nextTick(emitReadable_, stream); + } + } + function emitReadable_(stream) { + var state = stream._readableState; + debug('emitReadable_', state.destroyed, state.length, state.ended); + if (!state.destroyed && (state.length || state.ended)) { + stream.emit('readable'); + state.emittedReadable = false; + } + + // The stream needs another readable event if + // 1. It is not flowing, as the flow mechanism will take + // care of it. + // 2. It is not ended. + // 3. It is below the highWaterMark, so we can schedule + // another readable later. + state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; + flow(stream); + } + + // at this point, the user has presumably seen the 'readable' event, + // and called read() to consume some data. that may have triggered + // in turn another _read(n) call, in which case reading = true if + // it's in progress. + // However, if we're not ended, or reading, and the length < hwm, + // then go ahead and try to read some more preemptively. + function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + process.nextTick(maybeReadMore_, stream, state); + } + } + function maybeReadMore_(stream, state) { + // Attempt to read more data if we should. + // + // The conditions for reading more data are (one of): + // - Not enough data buffered (state.length < state.highWaterMark). The loop + // is responsible for filling the buffer with enough data if such data + // is available. If highWaterMark is 0 and we are not in the flowing mode + // we should _not_ attempt to buffer any extra data. We'll get more data + // when the stream consumer calls read() instead. + // - No data in the buffer, and the stream is in flowing mode. In this mode + // the loop below is responsible for ensuring read() is called. Failing to + // call read here would abort the flow and there's no other mechanism for + // continuing the flow if the stream consumer has just subscribed to the + // 'data' event. + // + // In addition to the above conditions to keep reading data, the following + // conditions prevent the data from being read: + // - The stream has ended (state.ended). + // - There is already a pending 'read' operation (state.reading). This is a + // case where the the stream has called the implementation defined _read() + // method, but they are processing the call asynchronously and have _not_ + // called push() with new data. In this case we skip performing more + // read()s. The execution ends in this method again after the _read() ends + // up calling push() with more data. + while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { + var len = state.length; + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break; + } + state.readingMore = false; + } + + // abstract method. to be overridden in specific implementation classes. + // call cb(er, data) where data is <= n in length. + // for virtual (non-string, non-buffer) streams, "length" is somewhat + // arbitrary, and perhaps not very meaningful. + Readable.prototype._read = function (n) { + errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()')); + }; + Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; + var endFn = doEnd ? onend : unpipe; + if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn); + dest.on('unpipe', onunpipe); + function onunpipe(readable, unpipeInfo) { + debug('onunpipe'); + if (readable === src) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); + } + } + } + function onend() { + debug('onend'); + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + var cleanedUp = false; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', unpipe); + src.removeListener('data', ondata); + cleanedUp = true; + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + var ret = dest.write(chunk); + debug('dest.write', ret); + if (ret === false) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', state.awaitDrain); + state.awaitDrain++; + } + src.pause(); + } + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er); + } + + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + return dest; + }; + function pipeOnDrain(src) { + return function pipeOnDrainFunctionResult() { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { + state.flowing = true; + flow(src); + } + }; + } + Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + var unpipeInfo = { + hasUnpiped: false + }; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; + + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + if (!dest) dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this, unpipeInfo); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + for (var i = 0; i < len; i++) dests[i].emit('unpipe', this, { + hasUnpiped: false + }); + return this; + } + + // try to find the right one. + var index = indexOf(state.pipes, dest); + if (index === -1) return this; + state.pipes.splice(index, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + dest.emit('unpipe', this, unpipeInfo); + return this; + }; + + // set up data events if they are asked for + // Ensure readable listeners eventually get something + Readable.prototype.on = function (ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); + var state = this._readableState; + if (ev === 'data') { + // update readableListening so that resume() may be a no-op + // a few lines down. This is needed to support once('readable'). + state.readableListening = this.listenerCount('readable') > 0; + + // Try start flowing on next tick if stream isn't explicitly paused + if (state.flowing !== false) this.resume(); + } else if (ev === 'readable') { + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.flowing = false; + state.emittedReadable = false; + debug('on readable', state.length, state.reading); + if (state.length) { + emitReadable(this); + } else if (!state.reading) { + process.nextTick(nReadingNextTick, this); + } + } + } + return res; + }; + Readable.prototype.addListener = Readable.prototype.on; + Readable.prototype.removeListener = function (ev, fn) { + var res = Stream.prototype.removeListener.call(this, ev, fn); + if (ev === 'readable') { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + process.nextTick(updateReadableListening, this); + } + return res; + }; + Readable.prototype.removeAllListeners = function (ev) { + var res = Stream.prototype.removeAllListeners.apply(this, arguments); + if (ev === 'readable' || ev === undefined) { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + process.nextTick(updateReadableListening, this); + } + return res; + }; + function updateReadableListening(self) { + var state = self._readableState; + state.readableListening = self.listenerCount('readable') > 0; + if (state.resumeScheduled && !state.paused) { + // flowing needs to be set to true now, otherwise + // the upcoming resume will not flow. + state.flowing = true; + + // crude way to check if we should resume + } else if (self.listenerCount('data') > 0) { + self.resume(); + } + } + function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); + } + + // pause() and resume() are remnants of the legacy readable stream API + // If the user uses them, then switch into old mode. + Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + // we flow only if there is no one listening + // for readable, but we still have to call + // resume() + state.flowing = !state.readableListening; + resume(this, state); + } + state.paused = false; + return this; + }; + function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + process.nextTick(resume_, stream, state); + } + } + function resume_(stream, state) { + debug('resume', state.reading); + if (!state.reading) { + stream.read(0); + } + state.resumeScheduled = false; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); + } + Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + if (this._readableState.flowing !== false) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + this._readableState.paused = true; + return this; + }; + function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + while (state.flowing && stream.read() !== null); + } + + // wrap an old-style stream as the async data source. + // This is *not* part of the readable stream interface. + // It is an ugly unfortunate mess of history. + Readable.prototype.wrap = function (stream) { + var _this = this; + var state = this._readableState; + var paused = false; + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) _this.push(chunk); + } + _this.push(null); + }); + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); + + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + var ret = _this.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function methodWrap(method) { + return function methodWrapReturnFunction() { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } + + // proxy certain important events. + for (var n = 0; n < kProxyEvents.length; n++) { + stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); + } + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + this._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; + return this; + }; + if (typeof Symbol === 'function') { + Readable.prototype[Symbol.asyncIterator] = function () { + if (createReadableStreamAsyncIterator === undefined) { + createReadableStreamAsyncIterator = requireAsync_iterator(); + } + return createReadableStreamAsyncIterator(this); + }; + } + Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.highWaterMark; + } + }); + Object.defineProperty(Readable.prototype, 'readableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState && this._readableState.buffer; + } + }); + Object.defineProperty(Readable.prototype, 'readableFlowing', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.flowing; + }, + set: function set(state) { + if (this._readableState) { + this._readableState.flowing = state; + } + } + }); + + // exposed for testing purposes only. + Readable._fromList = fromList; + Object.defineProperty(Readable.prototype, 'readableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.length; + } + }); + + // Pluck off n bytes from an array of buffers. + // Length is the combined lengths of all the buffers in the list. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = state.buffer.consume(n, state.decoder); + } + return ret; + } + function endReadable(stream) { + var state = stream._readableState; + debug('endReadable', state.endEmitted); + if (!state.endEmitted) { + state.ended = true; + process.nextTick(endReadableNT, state, stream); + } + } + function endReadableNT(state, stream) { + debug('endReadableNT', state.endEmitted, state.length); + + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + if (state.autoDestroy) { + // In case of duplex streams we need a way to detect + // if the writable side is ready for autoDestroy as well + var wState = stream._writableState; + if (!wState || wState.autoDestroy && wState.finished) { + stream.destroy(); + } + } + } + } + if (typeof Symbol === 'function') { + Readable.from = function (iterable, opts) { + if (from === undefined) { + from = requireFrom$1(); + } + return from(Readable, iterable, opts); + }; + } + function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; + } + return _stream_readable; +} + +var _stream_transform; +var hasRequired_stream_transform; + +function require_stream_transform () { + if (hasRequired_stream_transform) return _stream_transform; + hasRequired_stream_transform = 1; + + _stream_transform = Transform; + var _require$codes = requireErrors().codes, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, + ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING, + ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0; + var Duplex = require_stream_duplex(); + inheritsExports(Transform, Duplex); + function afterTransform(er, data) { + var ts = this._transformState; + ts.transforming = false; + var cb = ts.writecb; + if (cb === null) { + return this.emit('error', new ERR_MULTIPLE_CALLBACK()); + } + ts.writechunk = null; + ts.writecb = null; + if (data != null) + // single equals check for both `null` and `undefined` + this.push(data); + cb(er); + var rs = this._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + this._read(rs.highWaterMark); + } + } + function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + Duplex.call(this, options); + this._transformState = { + afterTransform: afterTransform.bind(this), + needTransform: false, + transforming: false, + writecb: null, + writechunk: null, + writeencoding: null + }; + + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + if (typeof options.flush === 'function') this._flush = options.flush; + } + + // When the writable side finishes, then flush out anything remaining. + this.on('prefinish', prefinish); + } + function prefinish() { + var _this = this; + if (typeof this._flush === 'function' && !this._readableState.destroyed) { + this._flush(function (er, data) { + done(_this, er, data); + }); + } else { + done(this, null, null); + } + } + Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); + }; + + // This is the part where you do stuff! + // override this function in implementation classes. + // 'chunk' is an input chunk. + // + // Call `push(newChunk)` to pass along transformed output + // to the readable side. You may call 'push' zero or more times. + // + // Call `cb(err)` when you are done with this chunk. If you pass + // an error, then that'll put the hurt on the whole operation. If you + // never call cb(), then you'll never get another chunk. + Transform.prototype._transform = function (chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()')); + }; + Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } + }; + + // Doesn't matter what the args are here. + // _transform does all the work. + // That we got here means that the readable side wants more data. + Transform.prototype._read = function (n) { + var ts = this._transformState; + if (ts.writechunk !== null && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } + }; + Transform.prototype._destroy = function (err, cb) { + Duplex.prototype._destroy.call(this, err, function (err2) { + cb(err2); + }); + }; + function done(stream, er, data) { + if (er) return stream.emit('error', er); + if (data != null) + // single equals check for both `null` and `undefined` + stream.push(data); + + // TODO(BridgeAR): Write a test for these two error cases + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); + if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); + return stream.push(null); + } + return _stream_transform; +} + +var _stream_passthrough; +var hasRequired_stream_passthrough; + +function require_stream_passthrough () { + if (hasRequired_stream_passthrough) return _stream_passthrough; + hasRequired_stream_passthrough = 1; + + _stream_passthrough = PassThrough; + var Transform = require_stream_transform(); + inheritsExports(PassThrough, Transform); + function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + Transform.call(this, options); + } + PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); + }; + return _stream_passthrough; +} + +var pipeline_1; +var hasRequiredPipeline; + +function requirePipeline () { + if (hasRequiredPipeline) return pipeline_1; + hasRequiredPipeline = 1; + + var eos; + function once(callback) { + var called = false; + return function () { + if (called) return; + called = true; + callback.apply(void 0, arguments); + }; + } + var _require$codes = requireErrors().codes, + ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, + ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; + function noop(err) { + // Rethrow the error if it exists to avoid swallowing it + if (err) throw err; + } + function isRequest(stream) { + return stream.setHeader && typeof stream.abort === 'function'; + } + function destroyer(stream, reading, writing, callback) { + callback = once(callback); + var closed = false; + stream.on('close', function () { + closed = true; + }); + if (eos === undefined) eos = requireEndOfStream(); + eos(stream, { + readable: reading, + writable: writing + }, function (err) { + if (err) return callback(err); + closed = true; + callback(); + }); + var destroyed = false; + return function (err) { + if (closed) return; + if (destroyed) return; + destroyed = true; + + // request.destroy just do .end - .abort is what we want + if (isRequest(stream)) return stream.abort(); + if (typeof stream.destroy === 'function') return stream.destroy(); + callback(err || new ERR_STREAM_DESTROYED('pipe')); + }; + } + function call(fn) { + fn(); + } + function pipe(from, to) { + return from.pipe(to); + } + function popCallback(streams) { + if (!streams.length) return noop; + if (typeof streams[streams.length - 1] !== 'function') return noop; + return streams.pop(); + } + function pipeline() { + for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { + streams[_key] = arguments[_key]; + } + var callback = popCallback(streams); + if (Array.isArray(streams[0])) streams = streams[0]; + if (streams.length < 2) { + throw new ERR_MISSING_ARGS('streams'); + } + var error; + var destroys = streams.map(function (stream, i) { + var reading = i < streams.length - 1; + var writing = i > 0; + return destroyer(stream, reading, writing, function (err) { + if (!error) error = err; + if (err) destroys.forEach(call); + if (reading) return; + destroys.forEach(call); + callback(error); + }); + }); + return streams.reduce(pipe); + } + pipeline_1 = pipeline; + return pipeline_1; +} + +(function (module, exports) { + var Stream = Stream$3; + if (process.env.READABLE_STREAM === 'disable' && Stream) { + module.exports = Stream.Readable; + Object.assign(module.exports, Stream); + module.exports.Stream = Stream; + } else { + exports = module.exports = require_stream_readable(); + exports.Stream = Stream || exports; + exports.Readable = exports; + exports.Writable = require_stream_writable(); + exports.Duplex = require_stream_duplex(); + exports.Transform = require_stream_transform(); + exports.PassThrough = require_stream_passthrough(); + exports.finished = requireEndOfStream(); + exports.pipeline = requirePipeline(); + } +} (readable, readable.exports)); + +var readableExports = readable.exports; + +const { Buffer: Buffer$1 } = require$$0$d; +const symbol = Symbol.for('BufferList'); + +function BufferList$1 (buf) { + if (!(this instanceof BufferList$1)) { + return new BufferList$1(buf) + } + + BufferList$1._init.call(this, buf); +} + +BufferList$1._init = function _init (buf) { + Object.defineProperty(this, symbol, { value: true }); + + this._bufs = []; + this.length = 0; + + if (buf) { + this.append(buf); + } +}; + +BufferList$1.prototype._new = function _new (buf) { + return new BufferList$1(buf) +}; + +BufferList$1.prototype._offset = function _offset (offset) { + if (offset === 0) { + return [0, 0] + } + + let tot = 0; + + for (let i = 0; i < this._bufs.length; i++) { + const _t = tot + this._bufs[i].length; + if (offset < _t || i === this._bufs.length - 1) { + return [i, offset - tot] + } + tot = _t; + } +}; + +BufferList$1.prototype._reverseOffset = function (blOffset) { + const bufferId = blOffset[0]; + let offset = blOffset[1]; + + for (let i = 0; i < bufferId; i++) { + offset += this._bufs[i].length; + } + + return offset +}; + +BufferList$1.prototype.get = function get (index) { + if (index > this.length || index < 0) { + return undefined + } + + const offset = this._offset(index); + + return this._bufs[offset[0]][offset[1]] +}; + +BufferList$1.prototype.slice = function slice (start, end) { + if (typeof start === 'number' && start < 0) { + start += this.length; + } + + if (typeof end === 'number' && end < 0) { + end += this.length; + } + + return this.copy(null, 0, start, end) +}; + +BufferList$1.prototype.copy = function copy (dst, dstStart, srcStart, srcEnd) { + if (typeof srcStart !== 'number' || srcStart < 0) { + srcStart = 0; + } + + if (typeof srcEnd !== 'number' || srcEnd > this.length) { + srcEnd = this.length; + } + + if (srcStart >= this.length) { + return dst || Buffer$1.alloc(0) + } + + if (srcEnd <= 0) { + return dst || Buffer$1.alloc(0) + } + + const copy = !!dst; + const off = this._offset(srcStart); + const len = srcEnd - srcStart; + let bytes = len; + let bufoff = (copy && dstStart) || 0; + let start = off[1]; + + // copy/slice everything + if (srcStart === 0 && srcEnd === this.length) { + if (!copy) { + // slice, but full concat if multiple buffers + return this._bufs.length === 1 + ? this._bufs[0] + : Buffer$1.concat(this._bufs, this.length) + } + + // copy, need to copy individual buffers + for (let i = 0; i < this._bufs.length; i++) { + this._bufs[i].copy(dst, bufoff); + bufoff += this._bufs[i].length; + } + + return dst + } + + // easy, cheap case where it's a subset of one of the buffers + if (bytes <= this._bufs[off[0]].length - start) { + return copy + ? this._bufs[off[0]].copy(dst, dstStart, start, start + bytes) + : this._bufs[off[0]].slice(start, start + bytes) + } + + if (!copy) { + // a slice, we need something to copy in to + dst = Buffer$1.allocUnsafe(len); + } + + for (let i = off[0]; i < this._bufs.length; i++) { + const l = this._bufs[i].length - start; + + if (bytes > l) { + this._bufs[i].copy(dst, bufoff, start); + bufoff += l; + } else { + this._bufs[i].copy(dst, bufoff, start, start + bytes); + bufoff += l; + break + } + + bytes -= l; + + if (start) { + start = 0; + } + } + + // safeguard so that we don't return uninitialized memory + if (dst.length > bufoff) return dst.slice(0, bufoff) + + return dst +}; + +BufferList$1.prototype.shallowSlice = function shallowSlice (start, end) { + start = start || 0; + end = typeof end !== 'number' ? this.length : end; + + if (start < 0) { + start += this.length; + } + + if (end < 0) { + end += this.length; + } + + if (start === end) { + return this._new() + } + + const startOffset = this._offset(start); + const endOffset = this._offset(end); + const buffers = this._bufs.slice(startOffset[0], endOffset[0] + 1); + + if (endOffset[1] === 0) { + buffers.pop(); + } else { + buffers[buffers.length - 1] = buffers[buffers.length - 1].slice(0, endOffset[1]); + } + + if (startOffset[1] !== 0) { + buffers[0] = buffers[0].slice(startOffset[1]); + } + + return this._new(buffers) +}; + +BufferList$1.prototype.toString = function toString (encoding, start, end) { + return this.slice(start, end).toString(encoding) +}; + +BufferList$1.prototype.consume = function consume (bytes) { + // first, normalize the argument, in accordance with how Buffer does it + bytes = Math.trunc(bytes); + // do nothing if not a positive number + if (Number.isNaN(bytes) || bytes <= 0) return this + + while (this._bufs.length) { + if (bytes >= this._bufs[0].length) { + bytes -= this._bufs[0].length; + this.length -= this._bufs[0].length; + this._bufs.shift(); + } else { + this._bufs[0] = this._bufs[0].slice(bytes); + this.length -= bytes; + break + } + } + + return this +}; + +BufferList$1.prototype.duplicate = function duplicate () { + const copy = this._new(); + + for (let i = 0; i < this._bufs.length; i++) { + copy.append(this._bufs[i]); + } + + return copy +}; + +BufferList$1.prototype.append = function append (buf) { + if (buf == null) { + return this + } + + if (buf.buffer) { + // append a view of the underlying ArrayBuffer + this._appendBuffer(Buffer$1.from(buf.buffer, buf.byteOffset, buf.byteLength)); + } else if (Array.isArray(buf)) { + for (let i = 0; i < buf.length; i++) { + this.append(buf[i]); + } + } else if (this._isBufferList(buf)) { + // unwrap argument into individual BufferLists + for (let i = 0; i < buf._bufs.length; i++) { + this.append(buf._bufs[i]); + } + } else { + // coerce number arguments to strings, since Buffer(number) does + // uninitialized memory allocation + if (typeof buf === 'number') { + buf = buf.toString(); + } + + this._appendBuffer(Buffer$1.from(buf)); + } + + return this +}; + +BufferList$1.prototype._appendBuffer = function appendBuffer (buf) { + this._bufs.push(buf); + this.length += buf.length; +}; + +BufferList$1.prototype.indexOf = function (search, offset, encoding) { + if (encoding === undefined && typeof offset === 'string') { + encoding = offset; + offset = undefined; + } + + if (typeof search === 'function' || Array.isArray(search)) { + throw new TypeError('The "value" argument must be one of type string, Buffer, BufferList, or Uint8Array.') + } else if (typeof search === 'number') { + search = Buffer$1.from([search]); + } else if (typeof search === 'string') { + search = Buffer$1.from(search, encoding); + } else if (this._isBufferList(search)) { + search = search.slice(); + } else if (Array.isArray(search.buffer)) { + search = Buffer$1.from(search.buffer, search.byteOffset, search.byteLength); + } else if (!Buffer$1.isBuffer(search)) { + search = Buffer$1.from(search); + } + + offset = Number(offset || 0); + + if (isNaN(offset)) { + offset = 0; + } + + if (offset < 0) { + offset = this.length + offset; + } + + if (offset < 0) { + offset = 0; + } + + if (search.length === 0) { + return offset > this.length ? this.length : offset + } + + const blOffset = this._offset(offset); + let blIndex = blOffset[0]; // index of which internal buffer we're working on + let buffOffset = blOffset[1]; // offset of the internal buffer we're working on + + // scan over each buffer + for (; blIndex < this._bufs.length; blIndex++) { + const buff = this._bufs[blIndex]; + + while (buffOffset < buff.length) { + const availableWindow = buff.length - buffOffset; + + if (availableWindow >= search.length) { + const nativeSearchResult = buff.indexOf(search, buffOffset); + + if (nativeSearchResult !== -1) { + return this._reverseOffset([blIndex, nativeSearchResult]) + } + + buffOffset = buff.length - search.length + 1; // end of native search window + } else { + const revOffset = this._reverseOffset([blIndex, buffOffset]); + + if (this._match(revOffset, search)) { + return revOffset + } + + buffOffset++; + } + } + + buffOffset = 0; + } + + return -1 +}; + +BufferList$1.prototype._match = function (offset, search) { + if (this.length - offset < search.length) { + return false + } + + for (let searchOffset = 0; searchOffset < search.length; searchOffset++) { + if (this.get(offset + searchOffset) !== search[searchOffset]) { + return false + } + } + return true +} + +;(function () { + const methods = { + readDoubleBE: 8, + readDoubleLE: 8, + readFloatBE: 4, + readFloatLE: 4, + readInt32BE: 4, + readInt32LE: 4, + readUInt32BE: 4, + readUInt32LE: 4, + readInt16BE: 2, + readInt16LE: 2, + readUInt16BE: 2, + readUInt16LE: 2, + readInt8: 1, + readUInt8: 1, + readIntBE: null, + readIntLE: null, + readUIntBE: null, + readUIntLE: null + }; + + for (const m in methods) { + (function (m) { + if (methods[m] === null) { + BufferList$1.prototype[m] = function (offset, byteLength) { + return this.slice(offset, offset + byteLength)[m](0, byteLength) + }; + } else { + BufferList$1.prototype[m] = function (offset = 0) { + return this.slice(offset, offset + methods[m])[m](0) + }; + } + }(m)); + } +}()); + +// Used internally by the class and also as an indicator of this object being +// a `BufferList`. It's not possible to use `instanceof BufferList` in a browser +// environment because there could be multiple different copies of the +// BufferList class and some `BufferList`s might be `BufferList`s. +BufferList$1.prototype._isBufferList = function _isBufferList (b) { + return b instanceof BufferList$1 || BufferList$1.isBufferList(b) +}; + +BufferList$1.isBufferList = function isBufferList (b) { + return b != null && b[symbol] +}; + +var BufferList_1 = BufferList$1; + +const DuplexStream = readableExports.Duplex; +const inherits = inheritsExports; +const BufferList = BufferList_1; + +function BufferListStream (callback) { + if (!(this instanceof BufferListStream)) { + return new BufferListStream(callback) + } + + if (typeof callback === 'function') { + this._callback = callback; + + const piper = function piper (err) { + if (this._callback) { + this._callback(err); + this._callback = null; + } + }.bind(this); + + this.on('pipe', function onPipe (src) { + src.on('error', piper); + }); + this.on('unpipe', function onUnpipe (src) { + src.removeListener('error', piper); + }); + + callback = null; + } + + BufferList._init.call(this, callback); + DuplexStream.call(this); +} + +inherits(BufferListStream, DuplexStream); +Object.assign(BufferListStream.prototype, BufferList.prototype); + +BufferListStream.prototype._new = function _new (callback) { + return new BufferListStream(callback) +}; + +BufferListStream.prototype._write = function _write (buf, encoding, callback) { + this._appendBuffer(buf); + + if (typeof callback === 'function') { + callback(); + } +}; + +BufferListStream.prototype._read = function _read (size) { + if (!this.length) { + return this.push(null) + } + + size = Math.min(size, this.length); + this.push(this.slice(0, size)); + this.consume(size); +}; + +BufferListStream.prototype.end = function end (chunk) { + DuplexStream.prototype.end.call(this, chunk); + + if (this._callback) { + this._callback(null, this.slice()); + this._callback = null; + } +}; + +BufferListStream.prototype._destroy = function _destroy (err, cb) { + this._bufs.length = 0; + this.length = 0; + cb(err); +}; + +BufferListStream.prototype._isBufferList = function _isBufferList (b) { + return b instanceof BufferListStream || b instanceof BufferList || BufferListStream.isBufferList(b) +}; + +BufferListStream.isBufferList = BufferList.isBufferList; + +bl.exports = BufferListStream; +var BufferListStream_1 = bl.exports.BufferListStream = BufferListStream; +bl.exports.BufferList = BufferList; + +const ASCII_ETX_CODE = 0x03; // Ctrl+C emits this code + +class StdinDiscarder { + #requests = 0; + #mutedStream = new BufferListStream_1(); + #ourEmit; + #rl; + + constructor() { + this.#mutedStream.pipe(process$3.stdout); + + const self = this; // eslint-disable-line unicorn/no-this-assignment + this.#ourEmit = function (event, data, ...arguments_) { + const {stdin} = process$3; + if (self.#requests > 0 || stdin.emit === self.#ourEmit) { + if (event === 'keypress') { // Fixes readline behavior + return; + } + + if (event === 'data' && data.includes(ASCII_ETX_CODE)) { + process$3.emit('SIGINT'); + } + + Reflect.apply(self.#ourEmit, this, [event, data, ...arguments_]); + } else { + Reflect.apply(process$3.stdin.emit, this, [event, data, ...arguments_]); + } + }; + } + + start() { + this.#requests++; + + if (this.#requests === 1) { + this._realStart(); + } + } + + stop() { + if (this.#requests <= 0) { + throw new Error('`stop` called more times than `start`'); + } + + this.#requests--; + + if (this.#requests === 0) { + this._realStop(); + } + } + + // TODO: Use private methods when targeting Node.js 14. + _realStart() { + // No known way to make it work reliably on Windows + if (process$3.platform === 'win32') { + return; + } + + this.#rl = readline.createInterface({ + input: process$3.stdin, + output: this.#mutedStream, + }); + + this.#rl.on('SIGINT', () => { + if (process$3.listenerCount('SIGINT') === 0) { + process$3.emit('SIGINT'); + } else { + this.#rl.close(); + process$3.kill(process$3.pid, 'SIGINT'); + } + }); + } + + _realStop() { + if (process$3.platform === 'win32') { + return; + } + + this.#rl.close(); + this.#rl = undefined; + } +} + +const stdinDiscarder = new StdinDiscarder(); + +class Ora { + #linesToClear = 0; + #isDiscardingStdin = false; + #lineCount = 0; + #frameIndex = 0; + #options; + #spinner; + #stream; + #id; + #initialInterval; + #isEnabled; + #isSilent; + #indent; + #text; + #prefixText; + #suffixText; + + color; + + constructor(options) { + if (typeof options === 'string') { + options = { + text: options, + }; + } + + this.#options = { + color: 'cyan', + stream: process$3.stderr, + discardStdin: true, + hideCursor: true, + ...options, + }; + + // Public + this.color = this.#options.color; + + // It's important that these use the public setters. + this.spinner = this.#options.spinner; + + this.#initialInterval = this.#options.interval; + this.#stream = this.#options.stream; + this.#isEnabled = typeof this.#options.isEnabled === 'boolean' ? this.#options.isEnabled : isInteractive({stream: this.#stream}); + this.#isSilent = typeof this.#options.isSilent === 'boolean' ? this.#options.isSilent : false; + + // Set *after* `this.#stream`. + // It's important that these use the public setters. + this.text = this.#options.text; + this.prefixText = this.#options.prefixText; + this.suffixText = this.#options.suffixText; + this.indent = this.#options.indent; + + if (process$3.env.NODE_ENV === 'test') { + this._stream = this.#stream; + this._isEnabled = this.#isEnabled; + + Object.defineProperty(this, '_linesToClear', { + get() { + return this.#linesToClear; + }, + set(newValue) { + this.#linesToClear = newValue; + }, + }); + + Object.defineProperty(this, '_frameIndex', { + get() { + return this.#frameIndex; + }, + }); + + Object.defineProperty(this, '_lineCount', { + get() { + return this.#lineCount; + }, + }); + } + } + + get indent() { + return this.#indent; + } + + set indent(indent = 0) { + if (!(indent >= 0 && Number.isInteger(indent))) { + throw new Error('The `indent` option must be an integer from 0 and up'); + } + + this.#indent = indent; + this.updateLineCount(); + } + + get interval() { + return this.#initialInterval || this.#spinner.interval || 100; + } + + get spinner() { + return this.#spinner; + } + + set spinner(spinner) { + this.#frameIndex = 0; + this.#initialInterval = undefined; + + if (typeof spinner === 'object') { + if (spinner.frames === undefined) { + throw new Error('The given spinner must have a `frames` property'); + } + + this.#spinner = spinner; + } else if (!isUnicodeSupported()) { + this.#spinner = cliSpinners$1.line; + } else if (spinner === undefined) { + // Set default spinner + this.#spinner = cliSpinners$1.dots; + } else if (spinner !== 'default' && cliSpinners$1[spinner]) { + this.#spinner = cliSpinners$1[spinner]; + } else { + throw new Error(`There is no built-in spinner named '${spinner}'. See https://github.com/sindresorhus/cli-spinners/blob/main/spinners.json for a full list.`); + } + } + + get text() { + return this.#text; + } + + set text(value) { + this.#text = value || ''; + this.updateLineCount(); + } + + get prefixText() { + return this.#prefixText; + } + + set prefixText(value) { + this.#prefixText = value || ''; + this.updateLineCount(); + } + + get suffixText() { + return this.#suffixText; + } + + set suffixText(value) { + this.#suffixText = value || ''; + this.updateLineCount(); + } + + get isSpinning() { + return this.#id !== undefined; + } + + // TODO: Use private methods when targeting Node.js 14. + getFullPrefixText(prefixText = this.#prefixText, postfix = ' ') { + if (typeof prefixText === 'string' && prefixText !== '') { + return prefixText + postfix; + } + + if (typeof prefixText === 'function') { + return prefixText() + postfix; + } + + return ''; + } + + getFullSuffixText(suffixText = this.#suffixText, prefix = ' ') { + if (typeof suffixText === 'string' && suffixText !== '') { + return prefix + suffixText; + } + + if (typeof suffixText === 'function') { + return prefix + suffixText(); + } + + return ''; + } + + updateLineCount() { + const columns = this.#stream.columns || 80; + const fullPrefixText = this.getFullPrefixText(this.#prefixText, '-'); + const fullSuffixText = this.getFullSuffixText(this.#suffixText, '-'); + const fullText = ' '.repeat(this.#indent) + fullPrefixText + '--' + this.#text + '--' + fullSuffixText; + + this.#lineCount = 0; + for (const line of stripAnsi$1(fullText).split('\n')) { + this.#lineCount += Math.max(1, Math.ceil(wcwidth$1(line) / columns)); + } + } + + get isEnabled() { + return this.#isEnabled && !this.#isSilent; + } + + set isEnabled(value) { + if (typeof value !== 'boolean') { + throw new TypeError('The `isEnabled` option must be a boolean'); + } + + this.#isEnabled = value; + } + + get isSilent() { + return this.#isSilent; + } + + set isSilent(value) { + if (typeof value !== 'boolean') { + throw new TypeError('The `isSilent` option must be a boolean'); + } + + this.#isSilent = value; + } + + frame() { + const {frames} = this.#spinner; + let frame = frames[this.#frameIndex]; + + if (this.color) { + frame = chalk$5[this.color](frame); + } + + this.#frameIndex = ++this.#frameIndex % frames.length; + const fullPrefixText = (typeof this.#prefixText === 'string' && this.#prefixText !== '') ? this.#prefixText + ' ' : ''; + const fullText = typeof this.text === 'string' ? ' ' + this.text : ''; + const fullSuffixText = (typeof this.#suffixText === 'string' && this.#suffixText !== '') ? ' ' + this.#suffixText : ''; + + return fullPrefixText + frame + fullText + fullSuffixText; + } + + clear() { + if (!this.#isEnabled || !this.#stream.isTTY) { + return this; + } + + this.#stream.cursorTo(0); + + for (let index = 0; index < this.#linesToClear; index++) { + if (index > 0) { + this.#stream.moveCursor(0, -1); + } + + this.#stream.clearLine(1); + } + + if (this.#indent || this.lastIndent !== this.#indent) { + this.#stream.cursorTo(this.#indent); + } + + this.lastIndent = this.#indent; + this.#linesToClear = 0; + + return this; + } + + render() { + if (this.#isSilent) { + return this; + } + + this.clear(); + this.#stream.write(this.frame()); + this.#linesToClear = this.#lineCount; + + return this; + } + + start(text) { + if (text) { + this.text = text; + } + + if (this.#isSilent) { + return this; + } + + if (!this.#isEnabled) { + if (this.text) { + this.#stream.write(`- ${this.text}\n`); + } + + return this; + } + + if (this.isSpinning) { + return this; + } + + if (this.#options.hideCursor) { + cliCursor.hide(this.#stream); + } + + if (this.#options.discardStdin && process$3.stdin.isTTY) { + this.#isDiscardingStdin = true; + stdinDiscarder.start(); + } + + this.render(); + this.#id = setInterval(this.render.bind(this), this.interval); + + return this; + } + + stop() { + if (!this.#isEnabled) { + return this; + } + + clearInterval(this.#id); + this.#id = undefined; + this.#frameIndex = 0; + this.clear(); + if (this.#options.hideCursor) { + cliCursor.show(this.#stream); + } + + if (this.#options.discardStdin && process$3.stdin.isTTY && this.#isDiscardingStdin) { + stdinDiscarder.stop(); + this.#isDiscardingStdin = false; + } + + return this; + } + + succeed(text) { + return this.stopAndPersist({symbol: logSymbols.success, text}); + } + + fail(text) { + return this.stopAndPersist({symbol: logSymbols.error, text}); + } + + warn(text) { + return this.stopAndPersist({symbol: logSymbols.warning, text}); + } + + info(text) { + return this.stopAndPersist({symbol: logSymbols.info, text}); + } + + stopAndPersist(options = {}) { + if (this.#isSilent) { + return this; + } + + const prefixText = options.prefixText || this.#prefixText; + const fullPrefixText = this.getFullPrefixText(prefixText, ' '); + + const symbolText = options.symbol || ' '; + + const text = options.text || this.text; + const fullText = (typeof text === 'string') ? ' ' + text : ''; + + const suffixText = options.suffixText !== undefined ? options.suffixText : this.#suffixText; + const fullSuffixText = this.getFullSuffixText(suffixText, ' '); + + const textToWrite = fullPrefixText + symbolText + fullText + fullSuffixText + '\n'; + + this.stop(); + this.#stream.write(textToWrite); + + return this; + } +} + +function ora(options) { + return new Ora(options); +} + +const capitalizeSpecType = (type) => type === 'openapi' ? 'OpenAPI' : type.charAt(0).toUpperCase() + type.slice(1); +/** + * Normalizes, validates, and (optionally) bundles an OpenAPI definition. + * + * @param path Path to a spec file. If this is missing, the current directory is searched for + * certain file names. + * @param command The command context in which this is being run within (uploading a spec, + * validation, or reducing one). + */ +async function prepareOas(path, command, opts = { + convertToLatest: false, +}) { + let specPath = path; + if (!specPath) { + /** + * Scans working directory for a potential OpenAPI or Swagger file. + * Any files in the `.git` directory or defined in a top-level `.gitignore` file + * are skipped. + * + * A "potential OpenAPI or Swagger file" is defined as a YAML or JSON file + * that has an `openapi` or `swagger` property defined at the top-level. + * + * If multiple potential files are found, the user must select a single file. + * + * An error is thrown in the following cases: + * - if in a CI environment and multiple files are found + * - no files are found + */ + const fileFindingSpinner = ora({ text: 'Looking for API definitions...', ...oraOptions() }).start(); + let action; + switch (command) { + case 'openapi': + action = 'upload'; + break; + default: + action = command.split(':')[1]; + } + const jsonAndYamlFiles = readdirRecursive('.', true).filter(file => file.toLowerCase().endsWith('.json') || + file.toLowerCase().endsWith('.yaml') || + file.toLowerCase().endsWith('.yml')); + debug(`number of JSON or YAML files found: ${jsonAndYamlFiles.length}`); + const possibleSpecFiles = (await Promise.all(jsonAndYamlFiles.map(file => { + debug(`attempting to oas-normalize ${file}`); + const oas = new OASNormalize(file, { enablePaths: true }); + return oas + .version() + .then(({ specification, version }) => { + debug(`specification type for ${file}: ${specification}`); + debug(`version for ${file}: ${version}`); + return ['openapi', 'swagger', 'postman'].includes(specification) + ? { filePath: file, specType: capitalizeSpecType(specification), version } + : null; + }) + .catch(e => { + debug(`error extracting API definition specification version for ${file}: ${e.message}`); + return null; + }); + }))).filter(Boolean); + debug(`number of possible OpenAPI/Swagger files found: ${possibleSpecFiles.length}`); + if (!possibleSpecFiles.length) { + fileFindingSpinner.fail(); + throw new Error(`We couldn't find an OpenAPI or Swagger definition.\n\nPlease specify the path to your definition with \`rdme ${command} ./path/to/api/definition\`.`); + } + specPath = possibleSpecFiles[0].filePath; + if (possibleSpecFiles.length === 1) { + fileFindingSpinner.stop(); + info(chalk$5.yellow(`We found ${specPath} and are attempting to ${action} it.`)); + } + else if (possibleSpecFiles.length > 1) { + if (isCI()) { + fileFindingSpinner.fail(); + throw new Error('Multiple API definitions found in current directory. Please specify file.'); + } + fileFindingSpinner.stop(); + const selection = await promptTerminal({ + name: 'file', + message: `Multiple potential API definitions found! Which one would you like to ${action}?`, + type: 'select', + choices: possibleSpecFiles.map(file => ({ + title: file.filePath, + value: file.filePath, + description: `${file.specType} ${file.version}`, + })), + }); + specPath = selection.file; + } + } + const spinner = ora({ text: `Validating the API definition located at ${specPath}...`, ...oraOptions() }).start(); + debug(`about to normalize spec located at ${specPath}`); + const oas = new OASNormalize(specPath, { colorizeErrors: true, enablePaths: true }); + debug('spec normalized'); + // We're retrieving the original specification type here instead of after validation because if + // they give us a Postman collection we should tell them that we handled a Postman collection, not + // an OpenAPI definition (eventhough we'll actually convert it to OpenAPI under the hood). + // + // And though `.validate()` will run `.load()` itself running `.load()` here will not have any + // performance implications as `oas-normalizes` caches the result of `.load()` the first time you + // run it. + const { specType, definitionVersion } = await oas.load().then(async (schema) => { + const type = getAPIDefinitionType2$1(schema); + return { + specType: capitalizeSpecType(type), + definitionVersion: await oas.version(), + }; + }); + // If we were supplied a Postman collection this will **always** convert it to OpenAPI 3.0. + let api = await oas.validate({ convertToLatest: opts.convertToLatest }).catch((err) => { + spinner.fail(); + debug(`raw validation error object: ${JSON.stringify(err)}`); + throw err; + }); + spinner.stop(); + debug('👇👇👇👇👇 spec validated! logging spec below 👇👇👇👇👇'); + debug(api); + debug('👆👆👆👆👆 finished logging spec 👆👆👆👆👆'); + debug(`spec type: ${specType}`); + if (opts.title) { + debug(`renaming title field to ${opts.title}`); + api.info.title = opts.title; + } + const specFileType = oas.type; + // No need to optional chain here since `info.version` is required to pass validation + const specVersion = api.info.version; + debug(`version in spec: ${specVersion}`); + if (['openapi', 'openapi:inspect', 'openapi:reduce'].includes(command)) { + api = await oas.bundle(); + debug('spec bundled'); + } + return { + preparedSpec: JSON.stringify(api), + /** A string indicating whether the spec file is a local path, a URL, etc. */ + specFileType, + /** The path/URL to the spec file */ + specPath, + /** A string indicating whether the spec file is OpenAPI, Swagger, etc. */ + specType, + /** + * The `info.version` field, extracted from the normalized spec. + * This is **not** the OpenAPI version (e.g., 3.1, 3.0), + * this is a user input that we use to specify the version in ReadMe + * (if they use the `useSpecVersion` flag) + */ + specVersion, + /** + * This is the `openapi`, `swagger`, or `postman` specification version of their API definition. + */ + definitionVersion, + }; +} + +class OpenAPIConvertCommand extends Command { + constructor() { + super(); + this.command = 'openapi:convert'; + this.usage = 'openapi:convert [file|url] [options]'; + this.description = 'Convert a Swagger or Postman Collection to OpenAPI.'; + this.cmdCategory = CommandCategories.APIS; + this.hiddenArgs = ['spec']; + this.args = [ + { + name: 'spec', + type: String, + defaultOption: true, + }, + { + name: 'out', + type: String, + description: 'Output file path to write converted file to', + }, + this.getWorkingDirArg(), + ]; + } + async run(opts) { + await super.run(opts); + const { spec, workingDirectory } = opts; + if (workingDirectory) { + const previousWorkingDirectory = process.cwd(); + process.chdir(workingDirectory); + Command.debug(`switching working directory from ${previousWorkingDirectory} to ${process.cwd()}`); + } + const { preparedSpec, specPath, specType } = await prepareOas(spec, 'openapi:convert', { convertToLatest: true }); + const parsedPreparedSpec = JSON.parse(preparedSpec); + if (specType === 'OpenAPI') { + throw new Error("Sorry, this API definition is already an OpenAPI definition and doesn't need to be converted."); + } + prompts$1.override({ + outputPath: opts.out, + }); + const promptResults = await promptTerminal([ + { + type: 'text', + name: 'outputPath', + message: 'Enter the path to save your converted API definition to:', + initial: () => { + const extension = path$c.extname(specPath); + return `${path$c.basename(specPath).split(extension)[0]}.openapi${extension}`; + }, + validate: value => validateFilePath(value), + }, + ]); + Command.debug(`saving converted spec to ${promptResults.outputPath}`); + fs$i.writeFileSync(promptResults.outputPath, JSON.stringify(parsedPreparedSpec, null, 2)); + Command.debug('converted spec saved'); + return Promise.resolve(chalk$5.green(`Your converted API definition has been saved to ${promptResults.outputPath}!`)); + } +} + +var immutable = extend; + +var hasOwnProperty$g = Object.prototype.hasOwnProperty; + +function extend() { + var target = {}; + + for (var i = 0; i < arguments.length; i++) { + var source = arguments[i]; + + for (var key in source) { + if (hasOwnProperty$g.call(source, key)) { + target[key] = source[key]; + } + } + } + + return target +} + +var qs = require$$0$i + , url = require$$0$e + , xtend = immutable; + +const PARSE_LINK_HEADER_MAXLEN = parseInt(process.env.PARSE_LINK_HEADER_MAXLEN) || 2000; +const PARSE_LINK_HEADER_THROW_ON_MAXLEN_EXCEEDED = process.env.PARSE_LINK_HEADER_THROW_ON_MAXLEN_EXCEEDED != null; + +function hasRel(x) { + return x && x.rel; +} + +function intoRels (acc, x) { + function splitRel (rel) { + acc[rel] = xtend(x, { rel: rel }); + } + + x.rel.split(/\s+/).forEach(splitRel); + + return acc; +} + +function createObjects (acc, p) { + // rel="next" => 1: rel 2: next + var m = p.match(/\s*(.+)\s*=\s*"?([^"]+)"?/); + if (m) acc[m[1]] = m[2]; + return acc; +} + +function parseLink(link) { + try { + var m = link.match(/<?([^>]*)>(.*)/) + , linkUrl = m[1] + , parts = m[2].split(';') + , parsedUrl = url.parse(linkUrl) + , qry = qs.parse(parsedUrl.query); + + parts.shift(); + + var info = parts + .reduce(createObjects, {}); + + info = xtend(qry, info); + info.url = linkUrl; + return info; + } catch (e) { + return null; + } +} + +function checkHeader(linkHeader){ + if (!linkHeader) return false; + + if (linkHeader.length > PARSE_LINK_HEADER_MAXLEN) { + if (PARSE_LINK_HEADER_THROW_ON_MAXLEN_EXCEEDED) { + throw new Error('Input string too long, it should be under ' + PARSE_LINK_HEADER_MAXLEN + ' characters.'); + } else { + return false; + } + } + return true; +} + +var parseLinkHeader = function (linkHeader) { + if (!checkHeader(linkHeader)) return null; + + return linkHeader.split(/,\s*</) + .map(parseLink) + .filter(hasRel) + .reduce(intoRels, {}); +}; + +var parse$1 = /*@__PURE__*/getDefaultExportFromCjs(parseLinkHeader); + +function specOptions(specList, parsedDocs, currPage, totalPages) { + const specs = specList.map(s => { + return { + description: `API Definition ID: ${s._id}`, + title: s.title, + value: s._id, // eslint-disable-line no-underscore-dangle + }; + }); + if (parsedDocs?.prev?.page) { + specs.push({ + description: 'Go to the previous page', + title: `< Prev (page ${currPage - 1} of ${totalPages})`, + value: 'prev', + }); + } + if (parsedDocs?.next?.page) { + specs.push({ + description: 'Go to the next page', + title: `Next (page ${currPage + 1} of ${totalPages}) >`, + value: 'next', + }); + } + return specs; +} +const updateOasPrompt = (specList, parsedDocs, currPage, totalPages, getSpecs) => [ + { + type: 'select', + name: 'specId', + message: 'Select your desired file to update', + choices: specOptions(specList, parsedDocs, currPage, totalPages), + async format(spec) { + if (spec === 'prev') { + try { + const newSpecs = await getSpecs(`${parsedDocs.prev.url}`); + const newParsedDocs = parse$1(newSpecs.headers.get('link')); + const newSpecList = await handleRes(newSpecs); + // @todo: figure out how to add a stricter type here, see: + // https://github.com/readmeio/rdme/pull/570#discussion_r949715913 + const { specId } = await promptTerminal(updateOasPrompt(newSpecList, newParsedDocs, currPage - 1, totalPages, getSpecs)); + return specId; + } + catch (e) { + return null; + } + } + else if (spec === 'next') { + try { + const newSpecs = await getSpecs(`${parsedDocs.next.url}`); + const newParsedDocs = parse$1(newSpecs.headers.get('link')); + const newSpecList = await handleRes(newSpecs); + // @todo: figure out how to add a stricter type here, see: + // https://github.com/readmeio/rdme/pull/570#discussion_r949715913 + const { specId } = await promptTerminal(updateOasPrompt(newSpecList, newParsedDocs, currPage + 1, totalPages, getSpecs)); + return specId; + } + catch (e) { + return null; + } + } + return spec; + }, + }, +]; +function createOasPrompt(specList, parsedDocs, totalPages, getSpecs) { + return [ + { + type: 'select', + name: 'option', + message: 'Would you like to update an existing OAS file or create a new one?', + choices: [ + { title: 'Update existing', value: 'update' }, + { title: 'Create a new spec', value: 'create' }, + ], + async format(picked) { + if (picked === 'update') { + // @todo: figure out how to add a stricter type here, see: + // https://github.com/readmeio/rdme/pull/570#discussion_r949715913 + const { specId } = await promptTerminal(updateOasPrompt(specList, parsedDocs, 1, totalPages, getSpecs)); + return specId; + } + return picked; + }, + }, + ]; +} +/** + * Series of prompts to construct a version object, + * used in our `versions:create` and `versions:update` commands + */ +function versionPrompt( +/** list of versions, used for prompt about which version to fork */ +versionList, +/** existing version if we're performing an update */ +isUpdate) { + return [ + { + // only runs for versions:create command + type: isUpdate ? null : 'select', + name: 'from', + message: 'Which version would you like to fork from?', + choices: versionList.map(v => { + return { + title: v.version, + value: v.version, + }; + }), + }, + { + // only runs for versions:update command + type: !isUpdate ? null : 'text', + name: 'newVersion', + message: 'What should the version be renamed to?', + hint: '1.0.0', + validate(val) { + // allow empty string, in which case the version won't be renamed + if (!val) + return true; + return semver$1.valid(semver$1.coerce(val)) ? true : 'Please specify a semantic version.'; + }, + }, + { + // if the existing version being updated is already the main version, + // we can't switch that so we skip this question + type: isUpdate?.is_stable ? null : 'confirm', + name: 'is_stable', + message: 'Would you like to make this version the main version for this project?', + }, + { + type: 'confirm', + name: 'is_beta', + message: 'Should this version be in beta?', + }, + { + type: (prev, values) => { + // if user wants this version to be the main version + // it can't also be hidden. + return values.is_stable ? null : 'confirm'; + }, + name: 'is_public', + message: 'Would you like to make this version public?', + }, + { + type: (prev, values) => { + // if user wants this version to be the main version + // it can't also be deprecated. + return values.is_stable ? null : 'confirm'; + }, + name: 'is_deprecated', + message: 'Would you like to deprecate this version?', + }, + ]; +} + +const isFunction$b = (value) => (typeof value === "function"); + +/** + * @license + * web-streams-polyfill v4.0.0-beta.3 + * Copyright 2021 Mattias Buelens, Diwank Singh Tomer and other contributors. + * This code is released under the MIT license. + * SPDX-License-Identifier: MIT + */ +const e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol:e=>`Symbol(${e})`;function t$2(){}function r(e){return "object"==typeof e&&null!==e||"function"==typeof e}const o=t$2;function n(e,t){try{Object.defineProperty(e,"name",{value:t,configurable:!0});}catch(e){}}const a=Promise,i=Promise.prototype.then,l=Promise.resolve.bind(a),s$1=Promise.reject.bind(a);function u(e){return new a(e)}function c(e){return l(e)}function d$2(e){return s$1(e)}function f$1(e,t,r){return i.call(e,t,r)}function b(e,t,r){f$1(f$1(e,t,r),void 0,o);}function h(e,t){b(e,t);}function _(e,t){b(e,void 0,t);}function p(e,t,r){return f$1(e,t,r)}function m(e){f$1(e,void 0,o);}let y=e=>{if("function"==typeof queueMicrotask)y=queueMicrotask;else {const e=c(void 0);y=t=>f$1(e,t);}return y(e)};function g(e,t,r){if("function"!=typeof e)throw new TypeError("Argument is not a function");return Function.prototype.apply.call(e,t,r)}function w(e,t,r){try{return c(g(e,t,r))}catch(e){return d$2(e)}}let S$1 = class S{constructor(){this._cursor=0,this._size=0,this._front={_elements:[],_next:void 0},this._back=this._front,this._cursor=0,this._size=0;}get length(){return this._size}push(e){const t=this._back;let r=t;16383===t._elements.length&&(r={_elements:[],_next:void 0}),t._elements.push(e),r!==t&&(this._back=r,t._next=r),++this._size;}shift(){const e=this._front;let t=e;const r=this._cursor;let o=r+1;const n=e._elements,a=n[r];return 16384===o&&(t=e._next,o=0),--this._size,this._cursor=o,e!==t&&(this._front=t),n[r]=void 0,a}forEach(e){let t=this._cursor,r=this._front,o=r._elements;for(;!(t===o.length&&void 0===r._next||t===o.length&&(r=r._next,o=r._elements,t=0,0===o.length));)e(o[t]),++t;}peek(){const e=this._front,t=this._cursor;return e._elements[t]}};const v=e("[[AbortSteps]]"),R=e("[[ErrorSteps]]"),T=e("[[CancelSteps]]"),q=e("[[PullSteps]]"),C=e("[[ReleaseSteps]]");function E(e,t){e._ownerReadableStream=t,t._reader=e,"readable"===t._state?O(e):"closed"===t._state?function(e){O(e),j(e);}(e):B(e,t._storedError);}function P(e,t){return Gt(e._ownerReadableStream,t)}function W(e){const t=e._ownerReadableStream;"readable"===t._state?A$1(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):function(e,t){B(e,t);}(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),t._readableStreamController[C](),t._reader=void 0,e._ownerReadableStream=void 0;}function k(e){return new TypeError("Cannot "+e+" a stream using a released reader")}function O(e){e._closedPromise=u(((t,r)=>{e._closedPromise_resolve=t,e._closedPromise_reject=r;}));}function B(e,t){O(e),A$1(e,t);}function A$1(e,t){void 0!==e._closedPromise_reject&&(m(e._closedPromise),e._closedPromise_reject(t),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0);}function j(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0);}const z=Number.isFinite||function(e){return "number"==typeof e&&isFinite(e)},L=Math.trunc||function(e){return e<0?Math.ceil(e):Math.floor(e)};function F$1(e,t){if(void 0!==e&&("object"!=typeof(r=e)&&"function"!=typeof r))throw new TypeError(`${t} is not an object.`);var r;}function I(e,t){if("function"!=typeof e)throw new TypeError(`${t} is not a function.`)}function D(e,t){if(!function(e){return "object"==typeof e&&null!==e||"function"==typeof e}(e))throw new TypeError(`${t} is not an object.`)}function $(e,t,r){if(void 0===e)throw new TypeError(`Parameter ${t} is required in '${r}'.`)}function M(e,t,r){if(void 0===e)throw new TypeError(`${t} is required in '${r}'.`)}function Y(e){return Number(e)}function Q(e){return 0===e?0:e}function N(e,t){const r=Number.MAX_SAFE_INTEGER;let o=Number(e);if(o=Q(o),!z(o))throw new TypeError(`${t} is not a finite number`);if(o=function(e){return Q(L(e))}(o),o<0||o>r)throw new TypeError(`${t} is outside the accepted range of 0 to ${r}, inclusive`);return z(o)&&0!==o?o:0}function H(e){if(!r(e))return !1;if("function"!=typeof e.getReader)return !1;try{return "boolean"==typeof e.locked}catch(e){return !1}}function x(e){if(!r(e))return !1;if("function"!=typeof e.getWriter)return !1;try{return "boolean"==typeof e.locked}catch(e){return !1}}function V(e,t){if(!Vt(e))throw new TypeError(`${t} is not a ReadableStream.`)}function U(e,t){e._reader._readRequests.push(t);}function G(e,t,r){const o=e._reader._readRequests.shift();r?o._closeSteps():o._chunkSteps(t);}function X(e){return e._reader._readRequests.length}function J(e){const t=e._reader;return void 0!==t&&!!K(t)}class ReadableStreamDefaultReader{constructor(e){if($(e,1,"ReadableStreamDefaultReader"),V(e,"First parameter"),Ut(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");E(this,e),this._readRequests=new S$1;}get closed(){return K(this)?this._closedPromise:d$2(ee$1("closed"))}cancel(e){return K(this)?void 0===this._ownerReadableStream?d$2(k("cancel")):P(this,e):d$2(ee$1("cancel"))}read(){if(!K(this))return d$2(ee$1("read"));if(void 0===this._ownerReadableStream)return d$2(k("read from"));let e,t;const r=u(((r,o)=>{e=r,t=o;}));return function(e,t){const r=e._ownerReadableStream;r._disturbed=!0,"closed"===r._state?t._closeSteps():"errored"===r._state?t._errorSteps(r._storedError):r._readableStreamController[q](t);}(this,{_chunkSteps:t=>e({value:t,done:!1}),_closeSteps:()=>e({value:void 0,done:!0}),_errorSteps:e=>t(e)}),r}releaseLock(){if(!K(this))throw ee$1("releaseLock");void 0!==this._ownerReadableStream&&function(e){W(e);const t=new TypeError("Reader was released");Z$1(e,t);}(this);}}function K(e){return !!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readRequests")&&e instanceof ReadableStreamDefaultReader)}function Z$1(e,t){const r=e._readRequests;e._readRequests=new S$1,r.forEach((e=>{e._errorSteps(t);}));}function ee$1(e){return new TypeError(`ReadableStreamDefaultReader.prototype.${e} can only be used on a ReadableStreamDefaultReader`)}Object.defineProperties(ReadableStreamDefaultReader.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),n(ReadableStreamDefaultReader.prototype.cancel,"cancel"),n(ReadableStreamDefaultReader.prototype.read,"read"),n(ReadableStreamDefaultReader.prototype.releaseLock,"releaseLock"),"symbol"==typeof e.toStringTag&&Object.defineProperty(ReadableStreamDefaultReader.prototype,e.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0});class te{constructor(e,t){this._ongoingPromise=void 0,this._isFinished=!1,this._reader=e,this._preventCancel=t;}next(){const e=()=>this._nextSteps();return this._ongoingPromise=this._ongoingPromise?p(this._ongoingPromise,e,e):e(),this._ongoingPromise}return(e){const t=()=>this._returnSteps(e);return this._ongoingPromise?p(this._ongoingPromise,t,t):t()}_nextSteps(){if(this._isFinished)return Promise.resolve({value:void 0,done:!0});const e=this._reader;return void 0===e?d$2(k("iterate")):f$1(e.read(),(e=>{var t;return this._ongoingPromise=void 0,e.done&&(this._isFinished=!0,null===(t=this._reader)||void 0===t||t.releaseLock(),this._reader=void 0),e}),(e=>{var t;throw this._ongoingPromise=void 0,this._isFinished=!0,null===(t=this._reader)||void 0===t||t.releaseLock(),this._reader=void 0,e}))}_returnSteps(e){if(this._isFinished)return Promise.resolve({value:e,done:!0});this._isFinished=!0;const t=this._reader;if(void 0===t)return d$2(k("finish iterating"));if(this._reader=void 0,!this._preventCancel){const r=t.cancel(e);return t.releaseLock(),p(r,(()=>({value:e,done:!0})))}return t.releaseLock(),c({value:e,done:!0})}}const re$1={next(){return oe(this)?this._asyncIteratorImpl.next():d$2(ne("next"))},return(e){return oe(this)?this._asyncIteratorImpl.return(e):d$2(ne("return"))}};function oe(e){if(!r(e))return !1;if(!Object.prototype.hasOwnProperty.call(e,"_asyncIteratorImpl"))return !1;try{return e._asyncIteratorImpl instanceof te}catch(e){return !1}}function ne(e){return new TypeError(`ReadableStreamAsyncIterator.${e} can only be used on a ReadableSteamAsyncIterator`)}"symbol"==typeof e.asyncIterator&&Object.defineProperty(re$1,e.asyncIterator,{value(){return this},writable:!0,configurable:!0});const ae=Number.isNaN||function(e){return e!=e};function ie(e,t,r,o,n){new Uint8Array(e).set(new Uint8Array(r,o,n),t);}function le(e){const t=function(e,t,r){if(e.slice)return e.slice(t,r);const o=r-t,n=new ArrayBuffer(o);return ie(n,0,e,t,o),n}(e.buffer,e.byteOffset,e.byteOffset+e.byteLength);return new Uint8Array(t)}function se(e){const t=e._queue.shift();return e._queueTotalSize-=t.size,e._queueTotalSize<0&&(e._queueTotalSize=0),t.value}function ue(e,t,r){if("number"!=typeof(o=r)||ae(o)||o<0||r===1/0)throw new RangeError("Size must be a finite, non-NaN, non-negative number.");var o;e._queue.push({value:t,size:r}),e._queueTotalSize+=r;}function ce(e){e._queue=new S$1,e._queueTotalSize=0;}class ReadableStreamBYOBRequest{constructor(){throw new TypeError("Illegal constructor")}get view(){if(!fe(this))throw Be("view");return this._view}respond(e){if(!fe(this))throw Be("respond");if($(e,1,"respond"),e=N(e,"First parameter"),void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");this._view.buffer,function(e,t){const r=e._pendingPullIntos.peek();if("closed"===e._controlledReadableByteStream._state){if(0!==t)throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream")}else {if(0===t)throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream");if(r.bytesFilled+t>r.byteLength)throw new RangeError("bytesWritten out of range")}r.buffer=r.buffer,qe(e,t);}(this._associatedReadableByteStreamController,e);}respondWithNewView(e){if(!fe(this))throw Be("respondWithNewView");if($(e,1,"respondWithNewView"),!ArrayBuffer.isView(e))throw new TypeError("You can only respond with array buffer views");if(void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");e.buffer,function(e,t){const r=e._pendingPullIntos.peek();if("closed"===e._controlledReadableByteStream._state){if(0!==t.byteLength)throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream")}else if(0===t.byteLength)throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream");if(r.byteOffset+r.bytesFilled!==t.byteOffset)throw new RangeError("The region specified by view does not match byobRequest");if(r.bufferByteLength!==t.buffer.byteLength)throw new RangeError("The buffer of view has different capacity than byobRequest");if(r.bytesFilled+t.byteLength>r.byteLength)throw new RangeError("The region specified by view is larger than byobRequest");const o=t.byteLength;r.buffer=t.buffer,qe(e,o);}(this._associatedReadableByteStreamController,e);}}Object.defineProperties(ReadableStreamBYOBRequest.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),n(ReadableStreamBYOBRequest.prototype.respond,"respond"),n(ReadableStreamBYOBRequest.prototype.respondWithNewView,"respondWithNewView"),"symbol"==typeof e.toStringTag&&Object.defineProperty(ReadableStreamBYOBRequest.prototype,e.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});class ReadableByteStreamController{constructor(){throw new TypeError("Illegal constructor")}get byobRequest(){if(!de(this))throw Ae("byobRequest");return function(e){if(null===e._byobRequest&&e._pendingPullIntos.length>0){const t=e._pendingPullIntos.peek(),r=new Uint8Array(t.buffer,t.byteOffset+t.bytesFilled,t.byteLength-t.bytesFilled),o=Object.create(ReadableStreamBYOBRequest.prototype);!function(e,t,r){e._associatedReadableByteStreamController=t,e._view=r;}(o,e,r),e._byobRequest=o;}return e._byobRequest}(this)}get desiredSize(){if(!de(this))throw Ae("desiredSize");return ke(this)}close(){if(!de(this))throw Ae("close");if(this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");const e=this._controlledReadableByteStream._state;if("readable"!==e)throw new TypeError(`The stream (in ${e} state) is not in the readable state and cannot be closed`);!function(e){const t=e._controlledReadableByteStream;if(e._closeRequested||"readable"!==t._state)return;if(e._queueTotalSize>0)return void(e._closeRequested=!0);if(e._pendingPullIntos.length>0){if(e._pendingPullIntos.peek().bytesFilled>0){const t=new TypeError("Insufficient bytes to fill elements in the given buffer");throw Pe(e,t),t}}Ee(e),Xt(t);}(this);}enqueue(e){if(!de(this))throw Ae("enqueue");if($(e,1,"enqueue"),!ArrayBuffer.isView(e))throw new TypeError("chunk must be an array buffer view");if(0===e.byteLength)throw new TypeError("chunk must have non-zero byteLength");if(0===e.buffer.byteLength)throw new TypeError("chunk's buffer must have non-zero byteLength");if(this._closeRequested)throw new TypeError("stream is closed or draining");const t=this._controlledReadableByteStream._state;if("readable"!==t)throw new TypeError(`The stream (in ${t} state) is not in the readable state and cannot be enqueued to`);!function(e,t){const r=e._controlledReadableByteStream;if(e._closeRequested||"readable"!==r._state)return;const o=t.buffer,n=t.byteOffset,a=t.byteLength,i=o;if(e._pendingPullIntos.length>0){const t=e._pendingPullIntos.peek();t.buffer,Re(e),t.buffer=t.buffer,"none"===t.readerType&&ge(e,t);}if(J(r))if(function(e){const t=e._controlledReadableByteStream._reader;for(;t._readRequests.length>0;){if(0===e._queueTotalSize)return;We(e,t._readRequests.shift());}}(e),0===X(r))me(e,i,n,a);else {e._pendingPullIntos.length>0&&Ce(e);G(r,new Uint8Array(i,n,a),!1);}else Le(r)?(me(e,i,n,a),Te(e)):me(e,i,n,a);be(e);}(this,e);}error(e){if(!de(this))throw Ae("error");Pe(this,e);}[T](e){he(this),ce(this);const t=this._cancelAlgorithm(e);return Ee(this),t}[q](e){const t=this._controlledReadableByteStream;if(this._queueTotalSize>0)return void We(this,e);const r=this._autoAllocateChunkSize;if(void 0!==r){let t;try{t=new ArrayBuffer(r);}catch(t){return void e._errorSteps(t)}const o={buffer:t,bufferByteLength:r,byteOffset:0,byteLength:r,bytesFilled:0,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(o);}U(t,e),be(this);}[C](){if(this._pendingPullIntos.length>0){const e=this._pendingPullIntos.peek();e.readerType="none",this._pendingPullIntos=new S$1,this._pendingPullIntos.push(e);}}}function de(e){return !!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableByteStream")&&e instanceof ReadableByteStreamController)}function fe(e){return !!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_associatedReadableByteStreamController")&&e instanceof ReadableStreamBYOBRequest)}function be(e){const t=function(e){const t=e._controlledReadableByteStream;if("readable"!==t._state)return !1;if(e._closeRequested)return !1;if(!e._started)return !1;if(J(t)&&X(t)>0)return !0;if(Le(t)&&ze(t)>0)return !0;if(ke(e)>0)return !0;return !1}(e);if(!t)return;if(e._pulling)return void(e._pullAgain=!0);e._pulling=!0;b(e._pullAlgorithm(),(()=>(e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,be(e)),null)),(t=>(Pe(e,t),null)));}function he(e){Re(e),e._pendingPullIntos=new S$1;}function _e(e,t){let r=!1;"closed"===e._state&&(r=!0);const o=pe(t);"default"===t.readerType?G(e,o,r):function(e,t,r){const o=e._reader._readIntoRequests.shift();r?o._closeSteps(t):o._chunkSteps(t);}(e,o,r);}function pe(e){const t=e.bytesFilled,r=e.elementSize;return new e.viewConstructor(e.buffer,e.byteOffset,t/r)}function me(e,t,r,o){e._queue.push({buffer:t,byteOffset:r,byteLength:o}),e._queueTotalSize+=o;}function ye(e,t,r,o){let n;try{n=t.slice(r,r+o);}catch(t){throw Pe(e,t),t}me(e,n,0,o);}function ge(e,t){t.bytesFilled>0&&ye(e,t.buffer,t.byteOffset,t.bytesFilled),Ce(e);}function we(e,t){const r=t.elementSize,o=t.bytesFilled-t.bytesFilled%r,n=Math.min(e._queueTotalSize,t.byteLength-t.bytesFilled),a=t.bytesFilled+n,i=a-a%r;let l=n,s=!1;i>o&&(l=i-t.bytesFilled,s=!0);const u=e._queue;for(;l>0;){const r=u.peek(),o=Math.min(l,r.byteLength),n=t.byteOffset+t.bytesFilled;ie(t.buffer,n,r.buffer,r.byteOffset,o),r.byteLength===o?u.shift():(r.byteOffset+=o,r.byteLength-=o),e._queueTotalSize-=o,Se(e,o,t),l-=o;}return s}function Se(e,t,r){r.bytesFilled+=t;}function ve(e){0===e._queueTotalSize&&e._closeRequested?(Ee(e),Xt(e._controlledReadableByteStream)):be(e);}function Re(e){null!==e._byobRequest&&(e._byobRequest._associatedReadableByteStreamController=void 0,e._byobRequest._view=null,e._byobRequest=null);}function Te(e){for(;e._pendingPullIntos.length>0;){if(0===e._queueTotalSize)return;const t=e._pendingPullIntos.peek();we(e,t)&&(Ce(e),_e(e._controlledReadableByteStream,t));}}function qe(e,t){const r=e._pendingPullIntos.peek();Re(e);"closed"===e._controlledReadableByteStream._state?function(e,t){"none"===t.readerType&&Ce(e);const r=e._controlledReadableByteStream;if(Le(r))for(;ze(r)>0;)_e(r,Ce(e));}(e,r):function(e,t,r){if(Se(0,t,r),"none"===r.readerType)return ge(e,r),void Te(e);if(r.bytesFilled<r.elementSize)return;Ce(e);const o=r.bytesFilled%r.elementSize;if(o>0){const t=r.byteOffset+r.bytesFilled;ye(e,r.buffer,t-o,o);}r.bytesFilled-=o,_e(e._controlledReadableByteStream,r),Te(e);}(e,t,r),be(e);}function Ce(e){return e._pendingPullIntos.shift()}function Ee(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0;}function Pe(e,t){const r=e._controlledReadableByteStream;"readable"===r._state&&(he(e),ce(e),Ee(e),Jt(r,t));}function We(e,t){const r=e._queue.shift();e._queueTotalSize-=r.byteLength,ve(e);const o=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);t._chunkSteps(o);}function ke(e){const t=e._controlledReadableByteStream._state;return "errored"===t?null:"closed"===t?0:e._strategyHWM-e._queueTotalSize}function Oe(e,t,r){const o=Object.create(ReadableByteStreamController.prototype);let n,a,i;n=void 0!==t.start?()=>t.start(o):()=>{},a=void 0!==t.pull?()=>t.pull(o):()=>c(void 0),i=void 0!==t.cancel?e=>t.cancel(e):()=>c(void 0);const l=t.autoAllocateChunkSize;if(0===l)throw new TypeError("autoAllocateChunkSize must be greater than 0");!function(e,t,r,o,n,a,i){t._controlledReadableByteStream=e,t._pullAgain=!1,t._pulling=!1,t._byobRequest=null,t._queue=t._queueTotalSize=void 0,ce(t),t._closeRequested=!1,t._started=!1,t._strategyHWM=a,t._pullAlgorithm=o,t._cancelAlgorithm=n,t._autoAllocateChunkSize=i,t._pendingPullIntos=new S$1,e._readableStreamController=t,b(c(r()),(()=>(t._started=!0,be(t),null)),(e=>(Pe(t,e),null)));}(e,o,n,a,i,r,l);}function Be(e){return new TypeError(`ReadableStreamBYOBRequest.prototype.${e} can only be used on a ReadableStreamBYOBRequest`)}function Ae(e){return new TypeError(`ReadableByteStreamController.prototype.${e} can only be used on a ReadableByteStreamController`)}function je(e,t){e._reader._readIntoRequests.push(t);}function ze(e){return e._reader._readIntoRequests.length}function Le(e){const t=e._reader;return void 0!==t&&!!Fe(t)}Object.defineProperties(ReadableByteStreamController.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),n(ReadableByteStreamController.prototype.close,"close"),n(ReadableByteStreamController.prototype.enqueue,"enqueue"),n(ReadableByteStreamController.prototype.error,"error"),"symbol"==typeof e.toStringTag&&Object.defineProperty(ReadableByteStreamController.prototype,e.toStringTag,{value:"ReadableByteStreamController",configurable:!0});class ReadableStreamBYOBReader{constructor(e){if($(e,1,"ReadableStreamBYOBReader"),V(e,"First parameter"),Ut(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!de(e._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");E(this,e),this._readIntoRequests=new S$1;}get closed(){return Fe(this)?this._closedPromise:d$2(De("closed"))}cancel(e){return Fe(this)?void 0===this._ownerReadableStream?d$2(k("cancel")):P(this,e):d$2(De("cancel"))}read(e){if(!Fe(this))return d$2(De("read"));if(!ArrayBuffer.isView(e))return d$2(new TypeError("view must be an array buffer view"));if(0===e.byteLength)return d$2(new TypeError("view must have non-zero byteLength"));if(0===e.buffer.byteLength)return d$2(new TypeError("view's buffer must have non-zero byteLength"));if(e.buffer,void 0===this._ownerReadableStream)return d$2(k("read from"));let t,r;const o=u(((e,o)=>{t=e,r=o;}));return function(e,t,r){const o=e._ownerReadableStream;o._disturbed=!0,"errored"===o._state?r._errorSteps(o._storedError):function(e,t,r){const o=e._controlledReadableByteStream;let n=1;t.constructor!==DataView&&(n=t.constructor.BYTES_PER_ELEMENT);const a=t.constructor,i=t.buffer,l={buffer:i,bufferByteLength:i.byteLength,byteOffset:t.byteOffset,byteLength:t.byteLength,bytesFilled:0,elementSize:n,viewConstructor:a,readerType:"byob"};if(e._pendingPullIntos.length>0)return e._pendingPullIntos.push(l),void je(o,r);if("closed"!==o._state){if(e._queueTotalSize>0){if(we(e,l)){const t=pe(l);return ve(e),void r._chunkSteps(t)}if(e._closeRequested){const t=new TypeError("Insufficient bytes to fill elements in the given buffer");return Pe(e,t),void r._errorSteps(t)}}e._pendingPullIntos.push(l),je(o,r),be(e);}else {const e=new a(l.buffer,l.byteOffset,0);r._closeSteps(e);}}(o._readableStreamController,t,r);}(this,e,{_chunkSteps:e=>t({value:e,done:!1}),_closeSteps:e=>t({value:e,done:!0}),_errorSteps:e=>r(e)}),o}releaseLock(){if(!Fe(this))throw De("releaseLock");void 0!==this._ownerReadableStream&&function(e){W(e);const t=new TypeError("Reader was released");Ie(e,t);}(this);}}function Fe(e){return !!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readIntoRequests")&&e instanceof ReadableStreamBYOBReader)}function Ie(e,t){const r=e._readIntoRequests;e._readIntoRequests=new S$1,r.forEach((e=>{e._errorSteps(t);}));}function De(e){return new TypeError(`ReadableStreamBYOBReader.prototype.${e} can only be used on a ReadableStreamBYOBReader`)}function $e(e,t){const{highWaterMark:r}=e;if(void 0===r)return t;if(ae(r)||r<0)throw new RangeError("Invalid highWaterMark");return r}function Me(e){const{size:t}=e;return t||(()=>1)}function Ye(e,t){F$1(e,t);const r=null==e?void 0:e.highWaterMark,o=null==e?void 0:e.size;return {highWaterMark:void 0===r?void 0:Y(r),size:void 0===o?void 0:Qe(o,`${t} has member 'size' that`)}}function Qe(e,t){return I(e,t),t=>Y(e(t))}function Ne(e,t,r){return I(e,r),r=>w(e,t,[r])}function He(e,t,r){return I(e,r),()=>w(e,t,[])}function xe(e,t,r){return I(e,r),r=>g(e,t,[r])}function Ve(e,t,r){return I(e,r),(r,o)=>w(e,t,[r,o])}Object.defineProperties(ReadableStreamBYOBReader.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),n(ReadableStreamBYOBReader.prototype.cancel,"cancel"),n(ReadableStreamBYOBReader.prototype.read,"read"),n(ReadableStreamBYOBReader.prototype.releaseLock,"releaseLock"),"symbol"==typeof e.toStringTag&&Object.defineProperty(ReadableStreamBYOBReader.prototype,e.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});const Ue="function"==typeof AbortController;class WritableStream{constructor(e={},t={}){void 0===e?e=null:D(e,"First parameter");const r=Ye(t,"Second parameter"),o=function(e,t){F$1(e,t);const r=null==e?void 0:e.abort,o=null==e?void 0:e.close,n=null==e?void 0:e.start,a=null==e?void 0:e.type,i=null==e?void 0:e.write;return {abort:void 0===r?void 0:Ne(r,e,`${t} has member 'abort' that`),close:void 0===o?void 0:He(o,e,`${t} has member 'close' that`),start:void 0===n?void 0:xe(n,e,`${t} has member 'start' that`),write:void 0===i?void 0:Ve(i,e,`${t} has member 'write' that`),type:a}}(e,"First parameter");var n;(n=this)._state="writable",n._storedError=void 0,n._writer=void 0,n._writableStreamController=void 0,n._writeRequests=new S$1,n._inFlightWriteRequest=void 0,n._closeRequest=void 0,n._inFlightCloseRequest=void 0,n._pendingAbortRequest=void 0,n._backpressure=!1;if(void 0!==o.type)throw new RangeError("Invalid type is specified");const a=Me(r);!function(e,t,r,o){const n=Object.create(WritableStreamDefaultController.prototype);let a,i,l,s;a=void 0!==t.start?()=>t.start(n):()=>{};i=void 0!==t.write?e=>t.write(e,n):()=>c(void 0);l=void 0!==t.close?()=>t.close():()=>c(void 0);s=void 0!==t.abort?e=>t.abort(e):()=>c(void 0);!function(e,t,r,o,n,a,i,l){t._controlledWritableStream=e,e._writableStreamController=t,t._queue=void 0,t._queueTotalSize=void 0,ce(t),t._abortReason=void 0,t._abortController=function(){if(Ue)return new AbortController}(),t._started=!1,t._strategySizeAlgorithm=l,t._strategyHWM=i,t._writeAlgorithm=o,t._closeAlgorithm=n,t._abortAlgorithm=a;const s=bt(t);nt(e,s);const u=r();b(c(u),(()=>(t._started=!0,dt(t),null)),(r=>(t._started=!0,Ze(e,r),null)));}(e,n,a,i,l,s,r,o);}(this,o,$e(r,1),a);}get locked(){if(!Ge(this))throw _t("locked");return Xe(this)}abort(e){return Ge(this)?Xe(this)?d$2(new TypeError("Cannot abort a stream that already has a writer")):Je(this,e):d$2(_t("abort"))}close(){return Ge(this)?Xe(this)?d$2(new TypeError("Cannot close a stream that already has a writer")):rt(this)?d$2(new TypeError("Cannot close an already-closing stream")):Ke(this):d$2(_t("close"))}getWriter(){if(!Ge(this))throw _t("getWriter");return new WritableStreamDefaultWriter(this)}}function Ge(e){return !!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_writableStreamController")&&e instanceof WritableStream)}function Xe(e){return void 0!==e._writer}function Je(e,t){var r;if("closed"===e._state||"errored"===e._state)return c(void 0);e._writableStreamController._abortReason=t,null===(r=e._writableStreamController._abortController)||void 0===r||r.abort(t);const o=e._state;if("closed"===o||"errored"===o)return c(void 0);if(void 0!==e._pendingAbortRequest)return e._pendingAbortRequest._promise;let n=!1;"erroring"===o&&(n=!0,t=void 0);const a=u(((r,o)=>{e._pendingAbortRequest={_promise:void 0,_resolve:r,_reject:o,_reason:t,_wasAlreadyErroring:n};}));return e._pendingAbortRequest._promise=a,n||et(e,t),a}function Ke(e){const t=e._state;if("closed"===t||"errored"===t)return d$2(new TypeError(`The stream (in ${t} state) is not in the writable state and cannot be closed`));const r=u(((t,r)=>{const o={_resolve:t,_reject:r};e._closeRequest=o;})),o=e._writer;var n;return void 0!==o&&e._backpressure&&"writable"===t&&Et(o),ue(n=e._writableStreamController,lt,0),dt(n),r}function Ze(e,t){"writable"!==e._state?tt(e):et(e,t);}function et(e,t){const r=e._writableStreamController;e._state="erroring",e._storedError=t;const o=e._writer;void 0!==o&&it(o,t),!function(e){if(void 0===e._inFlightWriteRequest&&void 0===e._inFlightCloseRequest)return !1;return !0}(e)&&r._started&&tt(e);}function tt(e){e._state="errored",e._writableStreamController[R]();const t=e._storedError;if(e._writeRequests.forEach((e=>{e._reject(t);})),e._writeRequests=new S$1,void 0===e._pendingAbortRequest)return void ot(e);const r=e._pendingAbortRequest;if(e._pendingAbortRequest=void 0,r._wasAlreadyErroring)return r._reject(t),void ot(e);b(e._writableStreamController[v](r._reason),(()=>(r._resolve(),ot(e),null)),(t=>(r._reject(t),ot(e),null)));}function rt(e){return void 0!==e._closeRequest||void 0!==e._inFlightCloseRequest}function ot(e){void 0!==e._closeRequest&&(e._closeRequest._reject(e._storedError),e._closeRequest=void 0);const t=e._writer;void 0!==t&&St(t,e._storedError);}function nt(e,t){const r=e._writer;void 0!==r&&t!==e._backpressure&&(t?function(e){Rt(e);}(r):Et(r)),e._backpressure=t;}Object.defineProperties(WritableStream.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),n(WritableStream.prototype.abort,"abort"),n(WritableStream.prototype.close,"close"),n(WritableStream.prototype.getWriter,"getWriter"),"symbol"==typeof e.toStringTag&&Object.defineProperty(WritableStream.prototype,e.toStringTag,{value:"WritableStream",configurable:!0});class WritableStreamDefaultWriter{constructor(e){if($(e,1,"WritableStreamDefaultWriter"),function(e,t){if(!Ge(e))throw new TypeError(`${t} is not a WritableStream.`)}(e,"First parameter"),Xe(e))throw new TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=e,e._writer=this;const t=e._state;if("writable"===t)!rt(e)&&e._backpressure?Rt(this):qt(this),gt(this);else if("erroring"===t)Tt(this,e._storedError),gt(this);else if("closed"===t)qt(this),gt(r=this),vt(r);else {const t=e._storedError;Tt(this,t),wt(this,t);}var r;}get closed(){return at(this)?this._closedPromise:d$2(mt("closed"))}get desiredSize(){if(!at(this))throw mt("desiredSize");if(void 0===this._ownerWritableStream)throw yt("desiredSize");return function(e){const t=e._ownerWritableStream,r=t._state;if("errored"===r||"erroring"===r)return null;if("closed"===r)return 0;return ct(t._writableStreamController)}(this)}get ready(){return at(this)?this._readyPromise:d$2(mt("ready"))}abort(e){return at(this)?void 0===this._ownerWritableStream?d$2(yt("abort")):function(e,t){return Je(e._ownerWritableStream,t)}(this,e):d$2(mt("abort"))}close(){if(!at(this))return d$2(mt("close"));const e=this._ownerWritableStream;return void 0===e?d$2(yt("close")):rt(e)?d$2(new TypeError("Cannot close an already-closing stream")):Ke(this._ownerWritableStream)}releaseLock(){if(!at(this))throw mt("releaseLock");void 0!==this._ownerWritableStream&&function(e){const t=e._ownerWritableStream,r=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");it(e,r),function(e,t){"pending"===e._closedPromiseState?St(e,t):function(e,t){wt(e,t);}(e,t);}(e,r),t._writer=void 0,e._ownerWritableStream=void 0;}(this);}write(e){return at(this)?void 0===this._ownerWritableStream?d$2(yt("write to")):function(e,t){const r=e._ownerWritableStream,o=r._writableStreamController,n=function(e,t){try{return e._strategySizeAlgorithm(t)}catch(t){return ft(e,t),1}}(o,t);if(r!==e._ownerWritableStream)return d$2(yt("write to"));const a=r._state;if("errored"===a)return d$2(r._storedError);if(rt(r)||"closed"===a)return d$2(new TypeError("The stream is closing or closed and cannot be written to"));if("erroring"===a)return d$2(r._storedError);const i=function(e){return u(((t,r)=>{const o={_resolve:t,_reject:r};e._writeRequests.push(o);}))}(r);return function(e,t,r){try{ue(e,t,r);}catch(t){return void ft(e,t)}const o=e._controlledWritableStream;if(!rt(o)&&"writable"===o._state){nt(o,bt(e));}dt(e);}(o,t,n),i}(this,e):d$2(mt("write"))}}function at(e){return !!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_ownerWritableStream")&&e instanceof WritableStreamDefaultWriter)}function it(e,t){"pending"===e._readyPromiseState?Ct(e,t):function(e,t){Tt(e,t);}(e,t);}Object.defineProperties(WritableStreamDefaultWriter.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),n(WritableStreamDefaultWriter.prototype.abort,"abort"),n(WritableStreamDefaultWriter.prototype.close,"close"),n(WritableStreamDefaultWriter.prototype.releaseLock,"releaseLock"),n(WritableStreamDefaultWriter.prototype.write,"write"),"symbol"==typeof e.toStringTag&&Object.defineProperty(WritableStreamDefaultWriter.prototype,e.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});const lt={};class WritableStreamDefaultController{constructor(){throw new TypeError("Illegal constructor")}get abortReason(){if(!st(this))throw pt("abortReason");return this._abortReason}get signal(){if(!st(this))throw pt("signal");if(void 0===this._abortController)throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");return this._abortController.signal}error(e){if(!st(this))throw pt("error");"writable"===this._controlledWritableStream._state&&ht(this,e);}[v](e){const t=this._abortAlgorithm(e);return ut(this),t}[R](){ce(this);}}function st(e){return !!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledWritableStream")&&e instanceof WritableStreamDefaultController)}function ut(e){e._writeAlgorithm=void 0,e._closeAlgorithm=void 0,e._abortAlgorithm=void 0,e._strategySizeAlgorithm=void 0;}function ct(e){return e._strategyHWM-e._queueTotalSize}function dt(e){const t=e._controlledWritableStream;if(!e._started)return;if(void 0!==t._inFlightWriteRequest)return;if("erroring"===t._state)return void tt(t);if(0===e._queue.length)return;const r=e._queue.peek().value;r===lt?function(e){const t=e._controlledWritableStream;((function(e){e._inFlightCloseRequest=e._closeRequest,e._closeRequest=void 0;}))(t),se(e);const r=e._closeAlgorithm();ut(e),b(r,(()=>(function(e){e._inFlightCloseRequest._resolve(void 0),e._inFlightCloseRequest=void 0,"erroring"===e._state&&(e._storedError=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._resolve(),e._pendingAbortRequest=void 0)),e._state="closed";const t=e._writer;void 0!==t&&vt(t);}(t),null)),(e=>(function(e,t){e._inFlightCloseRequest._reject(t),e._inFlightCloseRequest=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._reject(t),e._pendingAbortRequest=void 0),Ze(e,t);}(t,e),null)));}(e):function(e,t){const r=e._controlledWritableStream;!function(e){e._inFlightWriteRequest=e._writeRequests.shift();}(r);b(e._writeAlgorithm(t),(()=>{!function(e){e._inFlightWriteRequest._resolve(void 0),e._inFlightWriteRequest=void 0;}(r);const t=r._state;if(se(e),!rt(r)&&"writable"===t){const t=bt(e);nt(r,t);}return dt(e),null}),(t=>("writable"===r._state&&ut(e),function(e,t){e._inFlightWriteRequest._reject(t),e._inFlightWriteRequest=void 0,Ze(e,t);}(r,t),null)));}(e,r);}function ft(e,t){"writable"===e._controlledWritableStream._state&&ht(e,t);}function bt(e){return ct(e)<=0}function ht(e,t){const r=e._controlledWritableStream;ut(e),et(r,t);}function _t(e){return new TypeError(`WritableStream.prototype.${e} can only be used on a WritableStream`)}function pt(e){return new TypeError(`WritableStreamDefaultController.prototype.${e} can only be used on a WritableStreamDefaultController`)}function mt(e){return new TypeError(`WritableStreamDefaultWriter.prototype.${e} can only be used on a WritableStreamDefaultWriter`)}function yt(e){return new TypeError("Cannot "+e+" a stream using a released writer")}function gt(e){e._closedPromise=u(((t,r)=>{e._closedPromise_resolve=t,e._closedPromise_reject=r,e._closedPromiseState="pending";}));}function wt(e,t){gt(e),St(e,t);}function St(e,t){void 0!==e._closedPromise_reject&&(m(e._closedPromise),e._closedPromise_reject(t),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="rejected");}function vt(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="resolved");}function Rt(e){e._readyPromise=u(((t,r)=>{e._readyPromise_resolve=t,e._readyPromise_reject=r;})),e._readyPromiseState="pending";}function Tt(e,t){Rt(e),Ct(e,t);}function qt(e){Rt(e),Et(e);}function Ct(e,t){void 0!==e._readyPromise_reject&&(m(e._readyPromise),e._readyPromise_reject(t),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="rejected");}function Et(e){void 0!==e._readyPromise_resolve&&(e._readyPromise_resolve(void 0),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="fulfilled");}Object.defineProperties(WritableStreamDefaultController.prototype,{abortReason:{enumerable:!0},signal:{enumerable:!0},error:{enumerable:!0}}),"symbol"==typeof e.toStringTag&&Object.defineProperty(WritableStreamDefaultController.prototype,e.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});const Pt="undefined"!=typeof DOMException?DOMException:void 0;const Wt=function(e){if("function"!=typeof e&&"object"!=typeof e)return !1;try{return new e,!0}catch(e){return !1}}(Pt)?Pt:function(){const e=function(e,t){this.message=e||"",this.name=t||"Error",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor);};return e.prototype=Object.create(Error.prototype),Object.defineProperty(e.prototype,"constructor",{value:e,writable:!0,configurable:!0}),e}();function kt(e,t,r,o,n,a){const i=e.getReader(),l=t.getWriter();Vt(e)&&(e._disturbed=!0);let s,_,g,w=!1,S=!1,v="readable",R="writable",T=!1,q=!1;const C=u((e=>{g=e;}));let E=Promise.resolve(void 0);return u(((P,W)=>{let k;function O(){if(w)return;const e=u(((e,t)=>{!function r(o){o?e():f$1(function(){if(w)return c(!0);return f$1(l.ready,(()=>f$1(i.read(),(e=>!!e.done||(E=l.write(e.value),m(E),!1)))))}(),r,t);}(!1);}));m(e);}function B(){return v="closed",r?L():z((()=>(Ge(t)&&(T=rt(t),R=t._state),T||"closed"===R?c(void 0):"erroring"===R||"errored"===R?d$2(_):(T=!0,l.close()))),!1,void 0),null}function A(e){return w||(v="errored",s=e,o?L(!0,e):z((()=>l.abort(e)),!0,e)),null}function j(e){return S||(R="errored",_=e,n?L(!0,e):z((()=>i.cancel(e)),!0,e)),null}if(void 0!==a&&(k=()=>{const e=void 0!==a.reason?a.reason:new Wt("Aborted","AbortError"),t=[];o||t.push((()=>"writable"===R?l.abort(e):c(void 0))),n||t.push((()=>"readable"===v?i.cancel(e):c(void 0))),z((()=>Promise.all(t.map((e=>e())))),!0,e);},a.aborted?k():a.addEventListener("abort",k)),Vt(e)&&(v=e._state,s=e._storedError),Ge(t)&&(R=t._state,_=t._storedError,T=rt(t)),Vt(e)&&Ge(t)&&(q=!0,g()),"errored"===v)A(s);else if("erroring"===R||"errored"===R)j(_);else if("closed"===v)B();else if(T||"closed"===R){const e=new TypeError("the destination writable stream closed before all data could be piped to it");n?L(!0,e):z((()=>i.cancel(e)),!0,e);}function z(e,t,r){function o(){return "writable"!==R||T?n():h(function(){let e;return c(function t(){if(e!==E)return e=E,p(E,t,t)}())}(),n),null}function n(){return e?b(e(),(()=>F(t,r)),(e=>F(!0,e))):F(t,r),null}w||(w=!0,q?o():h(C,o));}function L(e,t){z(void 0,e,t);}function F(e,t){return S=!0,l.releaseLock(),i.releaseLock(),void 0!==a&&a.removeEventListener("abort",k),e?W(t):P(void 0),null}w||(b(i.closed,B,A),b(l.closed,(function(){return S||(R="closed"),null}),j)),q?O():y((()=>{q=!0,g(),O();}));}))}function Ot(e,t){return function(e){try{return e.getReader({mode:"byob"}).releaseLock(),!0}catch(e){return !1}}(e)?function(e){let t,r,o,n,a,i=e.getReader(),l=!1,s=!1,d=!1,f=!1,h=!1,p=!1;const m=u((e=>{a=e;}));function y(e){_(e.closed,(t=>(e!==i||(o.error(t),n.error(t),h&&p||a(void 0)),null)));}function g(){l&&(i.releaseLock(),i=e.getReader(),y(i),l=!1),b(i.read(),(e=>{var t,r;if(d=!1,f=!1,e.done)return h||o.close(),p||n.close(),null===(t=o.byobRequest)||void 0===t||t.respond(0),null===(r=n.byobRequest)||void 0===r||r.respond(0),h&&p||a(void 0),null;const l=e.value,u=l;let c=l;if(!h&&!p)try{c=le(l);}catch(e){return o.error(e),n.error(e),a(i.cancel(e)),null}return h||o.enqueue(u),p||n.enqueue(c),s=!1,d?S():f&&v(),null}),(()=>(s=!1,null)));}function w(t,r){l||(i.releaseLock(),i=e.getReader({mode:"byob"}),y(i),l=!0);const u=r?n:o,c=r?o:n;b(i.read(t),(e=>{var t;d=!1,f=!1;const o=r?p:h,n=r?h:p;if(e.done){o||u.close(),n||c.close();const r=e.value;return void 0!==r&&(o||u.byobRequest.respondWithNewView(r),n||null===(t=c.byobRequest)||void 0===t||t.respond(0)),o&&n||a(void 0),null}const l=e.value;if(n)o||u.byobRequest.respondWithNewView(l);else {let e;try{e=le(l);}catch(e){return u.error(e),c.error(e),a(i.cancel(e)),null}o||u.byobRequest.respondWithNewView(l),c.enqueue(e);}return s=!1,d?S():f&&v(),null}),(()=>(s=!1,null)));}function S(){if(s)return d=!0,c(void 0);s=!0;const e=o.byobRequest;return null===e?g():w(e.view,!1),c(void 0)}function v(){if(s)return f=!0,c(void 0);s=!0;const e=n.byobRequest;return null===e?g():w(e.view,!0),c(void 0)}function R(e){if(h=!0,t=e,p){const e=[t,r],o=i.cancel(e);a(o);}return m}function T(e){if(p=!0,r=e,h){const e=[t,r],o=i.cancel(e);a(o);}return m}const q=new ReadableStream$1({type:"bytes",start(e){o=e;},pull:S,cancel:R}),C=new ReadableStream$1({type:"bytes",start(e){n=e;},pull:v,cancel:T});return y(i),[q,C]}(e):function(e,t){const r=e.getReader();let o,n,a,i,l,s=!1,d=!1,f=!1,h=!1;const p=u((e=>{l=e;}));function m(){return s?(d=!0,c(void 0)):(s=!0,b(r.read(),(e=>{if(d=!1,e.done)return f||a.close(),h||i.close(),f&&h||l(void 0),null;const t=e.value,r=t,o=t;return f||a.enqueue(r),h||i.enqueue(o),s=!1,d&&m(),null}),(()=>(s=!1,null))),c(void 0))}function y(e){if(f=!0,o=e,h){const e=[o,n],t=r.cancel(e);l(t);}return p}function g(e){if(h=!0,n=e,f){const e=[o,n],t=r.cancel(e);l(t);}return p}const w=new ReadableStream$1({start(e){a=e;},pull:m,cancel:y}),S=new ReadableStream$1({start(e){i=e;},pull:m,cancel:g});return _(r.closed,(e=>(a.error(e),i.error(e),f&&h||l(void 0),null))),[w,S]}(e)}class ReadableStreamDefaultController{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!Bt(this))throw Dt("desiredSize");return Lt(this)}close(){if(!Bt(this))throw Dt("close");if(!Ft(this))throw new TypeError("The stream is not in a state that permits close");!function(e){if(!Ft(e))return;const t=e._controlledReadableStream;e._closeRequested=!0,0===e._queue.length&&(jt(e),Xt(t));}(this);}enqueue(e){if(!Bt(this))throw Dt("enqueue");if(!Ft(this))throw new TypeError("The stream is not in a state that permits enqueue");return function(e,t){if(!Ft(e))return;const r=e._controlledReadableStream;if(Ut(r)&&X(r)>0)G(r,t,!1);else {let r;try{r=e._strategySizeAlgorithm(t);}catch(t){throw zt(e,t),t}try{ue(e,t,r);}catch(t){throw zt(e,t),t}}At(e);}(this,e)}error(e){if(!Bt(this))throw Dt("error");zt(this,e);}[T](e){ce(this);const t=this._cancelAlgorithm(e);return jt(this),t}[q](e){const t=this._controlledReadableStream;if(this._queue.length>0){const r=se(this);this._closeRequested&&0===this._queue.length?(jt(this),Xt(t)):At(this),e._chunkSteps(r);}else U(t,e),At(this);}[C](){}}function Bt(e){return !!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableStream")&&e instanceof ReadableStreamDefaultController)}function At(e){const t=function(e){const t=e._controlledReadableStream;if(!Ft(e))return !1;if(!e._started)return !1;if(Ut(t)&&X(t)>0)return !0;if(Lt(e)>0)return !0;return !1}(e);if(!t)return;if(e._pulling)return void(e._pullAgain=!0);e._pulling=!0;b(e._pullAlgorithm(),(()=>(e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,At(e)),null)),(t=>(zt(e,t),null)));}function jt(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0,e._strategySizeAlgorithm=void 0;}function zt(e,t){const r=e._controlledReadableStream;"readable"===r._state&&(ce(e),jt(e),Jt(r,t));}function Lt(e){const t=e._controlledReadableStream._state;return "errored"===t?null:"closed"===t?0:e._strategyHWM-e._queueTotalSize}function Ft(e){return !e._closeRequested&&"readable"===e._controlledReadableStream._state}function It(e,t,r,o){const n=Object.create(ReadableStreamDefaultController.prototype);let a,i,l;a=void 0!==t.start?()=>t.start(n):()=>{},i=void 0!==t.pull?()=>t.pull(n):()=>c(void 0),l=void 0!==t.cancel?e=>t.cancel(e):()=>c(void 0),function(e,t,r,o,n,a,i){t._controlledReadableStream=e,t._queue=void 0,t._queueTotalSize=void 0,ce(t),t._started=!1,t._closeRequested=!1,t._pullAgain=!1,t._pulling=!1,t._strategySizeAlgorithm=i,t._strategyHWM=a,t._pullAlgorithm=o,t._cancelAlgorithm=n,e._readableStreamController=t,b(c(r()),(()=>(t._started=!0,At(t),null)),(e=>(zt(t,e),null)));}(e,n,a,i,l,r,o);}function Dt(e){return new TypeError(`ReadableStreamDefaultController.prototype.${e} can only be used on a ReadableStreamDefaultController`)}function $t(e,t,r){return I(e,r),r=>w(e,t,[r])}function Mt(e,t,r){return I(e,r),r=>w(e,t,[r])}function Yt(e,t,r){return I(e,r),r=>g(e,t,[r])}function Qt(e,t){if("bytes"!==(e=`${e}`))throw new TypeError(`${t} '${e}' is not a valid enumeration value for ReadableStreamType`);return e}function Nt(e,t){if("byob"!==(e=`${e}`))throw new TypeError(`${t} '${e}' is not a valid enumeration value for ReadableStreamReaderMode`);return e}function Ht(e,t){F$1(e,t);const r=null==e?void 0:e.preventAbort,o=null==e?void 0:e.preventCancel,n=null==e?void 0:e.preventClose,a=null==e?void 0:e.signal;return void 0!==a&&function(e,t){if(!function(e){if("object"!=typeof e||null===e)return !1;try{return "boolean"==typeof e.aborted}catch(e){return !1}}(e))throw new TypeError(`${t} is not an AbortSignal.`)}(a,`${t} has member 'signal' that`),{preventAbort:Boolean(r),preventCancel:Boolean(o),preventClose:Boolean(n),signal:a}}function xt(e,t){F$1(e,t);const r=null==e?void 0:e.readable;M(r,"readable","ReadableWritablePair"),function(e,t){if(!H(e))throw new TypeError(`${t} is not a ReadableStream.`)}(r,`${t} has member 'readable' that`);const o=null==e?void 0:e.writable;return M(o,"writable","ReadableWritablePair"),function(e,t){if(!x(e))throw new TypeError(`${t} is not a WritableStream.`)}(o,`${t} has member 'writable' that`),{readable:r,writable:o}}Object.defineProperties(ReadableStreamDefaultController.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),n(ReadableStreamDefaultController.prototype.close,"close"),n(ReadableStreamDefaultController.prototype.enqueue,"enqueue"),n(ReadableStreamDefaultController.prototype.error,"error"),"symbol"==typeof e.toStringTag&&Object.defineProperty(ReadableStreamDefaultController.prototype,e.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});let ReadableStream$1 = class ReadableStream{constructor(e={},t={}){void 0===e?e=null:D(e,"First parameter");const r=Ye(t,"Second parameter"),o=function(e,t){F$1(e,t);const r=e,o=null==r?void 0:r.autoAllocateChunkSize,n=null==r?void 0:r.cancel,a=null==r?void 0:r.pull,i=null==r?void 0:r.start,l=null==r?void 0:r.type;return {autoAllocateChunkSize:void 0===o?void 0:N(o,`${t} has member 'autoAllocateChunkSize' that`),cancel:void 0===n?void 0:$t(n,r,`${t} has member 'cancel' that`),pull:void 0===a?void 0:Mt(a,r,`${t} has member 'pull' that`),start:void 0===i?void 0:Yt(i,r,`${t} has member 'start' that`),type:void 0===l?void 0:Qt(l,`${t} has member 'type' that`)}}(e,"First parameter");var n;if((n=this)._state="readable",n._reader=void 0,n._storedError=void 0,n._disturbed=!1,"bytes"===o.type){if(void 0!==r.size)throw new RangeError("The strategy for a byte stream cannot have a size function");Oe(this,o,$e(r,0));}else {const e=Me(r);It(this,o,$e(r,1),e);}}get locked(){if(!Vt(this))throw Kt("locked");return Ut(this)}cancel(e){return Vt(this)?Ut(this)?d$2(new TypeError("Cannot cancel a stream that already has a reader")):Gt(this,e):d$2(Kt("cancel"))}getReader(e){if(!Vt(this))throw Kt("getReader");return void 0===function(e,t){F$1(e,t);const r=null==e?void 0:e.mode;return {mode:void 0===r?void 0:Nt(r,`${t} has member 'mode' that`)}}(e,"First parameter").mode?new ReadableStreamDefaultReader(this):function(e){return new ReadableStreamBYOBReader(e)}(this)}pipeThrough(e,t={}){if(!H(this))throw Kt("pipeThrough");$(e,1,"pipeThrough");const r=xt(e,"First parameter"),o=Ht(t,"Second parameter");if(this.locked)throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(r.writable.locked)throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");return m(kt(this,r.writable,o.preventClose,o.preventAbort,o.preventCancel,o.signal)),r.readable}pipeTo(e,t={}){if(!H(this))return d$2(Kt("pipeTo"));if(void 0===e)return d$2("Parameter 1 is required in 'pipeTo'.");if(!x(e))return d$2(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));let r;try{r=Ht(t,"Second parameter");}catch(e){return d$2(e)}return this.locked?d$2(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):e.locked?d$2(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):kt(this,e,r.preventClose,r.preventAbort,r.preventCancel,r.signal)}tee(){if(!H(this))throw Kt("tee");if(this.locked)throw new TypeError("Cannot tee a stream that already has a reader");return Ot(this)}values(e){if(!H(this))throw Kt("values");return function(e,t){const r=e.getReader(),o=new te(r,t),n=Object.create(re$1);return n._asyncIteratorImpl=o,n}(this,function(e,t){F$1(e,t);const r=null==e?void 0:e.preventCancel;return {preventCancel:Boolean(r)}}(e,"First parameter").preventCancel)}};function Vt(e){return !!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readableStreamController")&&e instanceof ReadableStream$1)}function Ut(e){return void 0!==e._reader}function Gt(e,r){if(e._disturbed=!0,"closed"===e._state)return c(void 0);if("errored"===e._state)return d$2(e._storedError);Xt(e);const o=e._reader;if(void 0!==o&&Fe(o)){const e=o._readIntoRequests;o._readIntoRequests=new S$1,e.forEach((e=>{e._closeSteps(void 0);}));}return p(e._readableStreamController[T](r),t$2)}function Xt(e){e._state="closed";const t=e._reader;if(void 0!==t&&(j(t),K(t))){const e=t._readRequests;t._readRequests=new S$1,e.forEach((e=>{e._closeSteps();}));}}function Jt(e,t){e._state="errored",e._storedError=t;const r=e._reader;void 0!==r&&(A$1(r,t),K(r)?Z$1(r,t):Ie(r,t));}function Kt(e){return new TypeError(`ReadableStream.prototype.${e} can only be used on a ReadableStream`)}Object.defineProperties(ReadableStream$1.prototype,{cancel:{enumerable:!0},getReader:{enumerable:!0},pipeThrough:{enumerable:!0},pipeTo:{enumerable:!0},tee:{enumerable:!0},values:{enumerable:!0},locked:{enumerable:!0}}),n(ReadableStream$1.prototype.cancel,"cancel"),n(ReadableStream$1.prototype.getReader,"getReader"),n(ReadableStream$1.prototype.pipeThrough,"pipeThrough"),n(ReadableStream$1.prototype.pipeTo,"pipeTo"),n(ReadableStream$1.prototype.tee,"tee"),n(ReadableStream$1.prototype.values,"values"),"symbol"==typeof e.toStringTag&&Object.defineProperty(ReadableStream$1.prototype,e.toStringTag,{value:"ReadableStream",configurable:!0}),"symbol"==typeof e.asyncIterator&&Object.defineProperty(ReadableStream$1.prototype,e.asyncIterator,{value:ReadableStream$1.prototype.values,writable:!0,configurable:!0});const er=e=>e.byteLength;n(er,"size");const or=()=>1;n(or,"size");function cr(e,t){Sr(e,t),dr(e,t);}function dr(e,t){hr(e._transformStreamController),function(e,t){e._writableController.error(t);"writable"===e._writableState&&Tr(e,t);}(e,t),e._backpressure&&fr(e,!1);}function fr(e,t){void 0!==e._backpressureChangePromise&&e._backpressureChangePromise_resolve(),e._backpressureChangePromise=u((t=>{e._backpressureChangePromise_resolve=t;})),e._backpressure=t;}class TransformStreamDefaultController{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!br(this))throw mr("desiredSize");return vr(this._controlledTransformStream)}enqueue(e){if(!br(this))throw mr("enqueue");_r(this,e);}error(e){if(!br(this))throw mr("error");var t;t=e,cr(this._controlledTransformStream,t);}terminate(){if(!br(this))throw mr("terminate");!function(e){const t=e._controlledTransformStream;gr(t)&&wr(t);const r=new TypeError("TransformStream terminated");dr(t,r);}(this);}}function br(e){return !!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledTransformStream")&&e instanceof TransformStreamDefaultController)}function hr(e){e._transformAlgorithm=void 0,e._flushAlgorithm=void 0;}function _r(e,t){const r=e._controlledTransformStream;if(!gr(r))throw new TypeError("Readable side is not in a state that permits enqueue");try{!function(e,t){e._readablePulling=!1;try{e._readableController.enqueue(t);}catch(t){throw Sr(e,t),t}}(r,t);}catch(e){throw dr(r,e),r._readableStoredError}const o=function(e){return !function(e){if(!gr(e))return !1;if(e._readablePulling)return !0;if(vr(e)>0)return !0;return !1}(e)}(r);o!==r._backpressure&&fr(r,!0);}function mr(e){return new TypeError(`TransformStreamDefaultController.prototype.${e} can only be used on a TransformStreamDefaultController`)}function gr(e){return !e._readableCloseRequested&&"readable"===e._readableState}function wr(e){e._readableState="closed",e._readableCloseRequested=!0,e._readableController.close();}function Sr(e,t){"readable"===e._readableState&&(e._readableState="errored",e._readableStoredError=t),e._readableController.error(t);}function vr(e){return e._readableController.desiredSize}function Tr(e,t){e._writableState="erroring",e._writableStoredError=t,!function(e){return e._writableHasInFlightOperation}(e)&&e._writableStarted&&qr(e);}function qr(e){e._writableState="errored";}Object.defineProperties(TransformStreamDefaultController.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),n(TransformStreamDefaultController.prototype.enqueue,"enqueue"),n(TransformStreamDefaultController.prototype.error,"error"),n(TransformStreamDefaultController.prototype.terminate,"terminate"),"symbol"==typeof e.toStringTag&&Object.defineProperty(TransformStreamDefaultController.prototype,e.toStringTag,{value:"TransformStreamDefaultController",configurable:!0}); + +/*! Based on fetch-blob. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> & David Frank */ +const CHUNK_SIZE = 65536; +async function* clonePart(part) { + const end = part.byteOffset + part.byteLength; + let position = part.byteOffset; + while (position !== end) { + const size = Math.min(end - position, CHUNK_SIZE); + const chunk = part.buffer.slice(position, position + size); + position += chunk.byteLength; + yield new Uint8Array(chunk); + } +} +async function* consumeNodeBlob(blob) { + let position = 0; + while (position !== blob.size) { + const chunk = blob.slice(position, Math.min(blob.size, position + CHUNK_SIZE)); + const buffer = await chunk.arrayBuffer(); + position += buffer.byteLength; + yield new Uint8Array(buffer); + } +} +async function* consumeBlobParts(parts, clone = false) { + for (const part of parts) { + if (ArrayBuffer.isView(part)) { + if (clone) { + yield* clonePart(part); + } + else { + yield part; + } + } + else if (isFunction$b(part.stream)) { + yield* part.stream(); + } + else { + yield* consumeNodeBlob(part); + } + } +} +function* sliceBlob(blobParts, blobSize, start = 0, end) { + end !== null && end !== void 0 ? end : (end = blobSize); + let relativeStart = start < 0 + ? Math.max(blobSize + start, 0) + : Math.min(start, blobSize); + let relativeEnd = end < 0 + ? Math.max(blobSize + end, 0) + : Math.min(end, blobSize); + const span = Math.max(relativeEnd - relativeStart, 0); + let added = 0; + for (const part of blobParts) { + if (added >= span) { + break; + } + const partSize = ArrayBuffer.isView(part) ? part.byteLength : part.size; + if (relativeStart && partSize <= relativeStart) { + relativeStart -= partSize; + relativeEnd -= partSize; + } + else { + let chunk; + if (ArrayBuffer.isView(part)) { + chunk = part.subarray(relativeStart, Math.min(partSize, relativeEnd)); + added += chunk.byteLength; + } + else { + chunk = part.slice(relativeStart, Math.min(partSize, relativeEnd)); + added += chunk.size; + } + relativeEnd -= partSize; + relativeStart = 0; + yield chunk; + } + } +} + +/*! Based on fetch-blob. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> & David Frank */ +var __classPrivateFieldGet$2 = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var __classPrivateFieldSet$1 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +}; +var _Blob_parts, _Blob_type, _Blob_size; +let Blob$1 = class Blob { + static [(_Blob_parts = new WeakMap(), _Blob_type = new WeakMap(), _Blob_size = new WeakMap(), Symbol.hasInstance)](value) { + return Boolean(value + && typeof value === "object" + && isFunction$b(value.constructor) + && (isFunction$b(value.stream) + || isFunction$b(value.arrayBuffer)) + && /^(Blob|File)$/.test(value[Symbol.toStringTag])); + } + constructor(blobParts = [], options = {}) { + _Blob_parts.set(this, []); + _Blob_type.set(this, ""); + _Blob_size.set(this, 0); + options !== null && options !== void 0 ? options : (options = {}); + if (typeof blobParts !== "object" || blobParts === null) { + throw new TypeError("Failed to construct 'Blob': " + + "The provided value cannot be converted to a sequence."); + } + if (!isFunction$b(blobParts[Symbol.iterator])) { + throw new TypeError("Failed to construct 'Blob': " + + "The object must have a callable @@iterator property."); + } + if (typeof options !== "object" && !isFunction$b(options)) { + throw new TypeError("Failed to construct 'Blob': parameter 2 cannot convert to dictionary."); + } + const encoder = new TextEncoder(); + for (const raw of blobParts) { + let part; + if (ArrayBuffer.isView(raw)) { + part = new Uint8Array(raw.buffer.slice(raw.byteOffset, raw.byteOffset + raw.byteLength)); + } + else if (raw instanceof ArrayBuffer) { + part = new Uint8Array(raw.slice(0)); + } + else if (raw instanceof Blob) { + part = raw; + } + else { + part = encoder.encode(String(raw)); + } + __classPrivateFieldSet$1(this, _Blob_size, __classPrivateFieldGet$2(this, _Blob_size, "f") + (ArrayBuffer.isView(part) ? part.byteLength : part.size), "f"); + __classPrivateFieldGet$2(this, _Blob_parts, "f").push(part); + } + const type = options.type === undefined ? "" : String(options.type); + __classPrivateFieldSet$1(this, _Blob_type, /^[\x20-\x7E]*$/.test(type) ? type : "", "f"); + } + get type() { + return __classPrivateFieldGet$2(this, _Blob_type, "f"); + } + get size() { + return __classPrivateFieldGet$2(this, _Blob_size, "f"); + } + slice(start, end, contentType) { + return new Blob(sliceBlob(__classPrivateFieldGet$2(this, _Blob_parts, "f"), this.size, start, end), { + type: contentType + }); + } + async text() { + const decoder = new TextDecoder(); + let result = ""; + for await (const chunk of consumeBlobParts(__classPrivateFieldGet$2(this, _Blob_parts, "f"))) { + result += decoder.decode(chunk, { stream: true }); + } + result += decoder.decode(); + return result; + } + async arrayBuffer() { + const view = new Uint8Array(this.size); + let offset = 0; + for await (const chunk of consumeBlobParts(__classPrivateFieldGet$2(this, _Blob_parts, "f"))) { + view.set(chunk, offset); + offset += chunk.length; + } + return view.buffer; + } + stream() { + const iterator = consumeBlobParts(__classPrivateFieldGet$2(this, _Blob_parts, "f"), true); + return new ReadableStream$1({ + async pull(controller) { + const { value, done } = await iterator.next(); + if (done) { + return queueMicrotask(() => controller.close()); + } + controller.enqueue(value); + }, + async cancel() { + await iterator.return(); + } + }); + } + get [Symbol.toStringTag]() { + return "Blob"; + } +}; +Object.defineProperties(Blob$1.prototype, { + type: { enumerable: true }, + size: { enumerable: true }, + slice: { enumerable: true }, + stream: { enumerable: true }, + text: { enumerable: true }, + arrayBuffer: { enumerable: true } +}); + +const isBlob$1 = (value) => value instanceof Blob$1; + +var __classPrivateFieldSet = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +}; +var __classPrivateFieldGet$1 = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var _File_name, _File_lastModified; +class File extends Blob$1 { + static [(_File_name = new WeakMap(), _File_lastModified = new WeakMap(), Symbol.hasInstance)](value) { + return value instanceof Blob$1 + && value[Symbol.toStringTag] === "File" + && typeof value.name === "string"; + } + constructor(fileBits, name, options = {}) { + super(fileBits, options); + _File_name.set(this, void 0); + _File_lastModified.set(this, 0); + if (arguments.length < 2) { + throw new TypeError("Failed to construct 'File': 2 arguments required, " + + `but only ${arguments.length} present.`); + } + __classPrivateFieldSet(this, _File_name, String(name), "f"); + const lastModified = options.lastModified === undefined + ? Date.now() + : Number(options.lastModified); + if (!Number.isNaN(lastModified)) { + __classPrivateFieldSet(this, _File_lastModified, lastModified, "f"); + } + } + get name() { + return __classPrivateFieldGet$1(this, _File_name, "f"); + } + get webkitRelativePath() { + return ""; + } + get lastModified() { + return __classPrivateFieldGet$1(this, _File_lastModified, "f"); + } + get [Symbol.toStringTag]() { + return "File"; + } +} + +const isFile = (value) => value instanceof File; + +var __classPrivateFieldGet = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var _FormData_instances, _FormData_entries, _FormData_setEntry; +class FormData { + constructor() { + _FormData_instances.add(this); + _FormData_entries.set(this, new Map()); + } + static [(_FormData_entries = new WeakMap(), _FormData_instances = new WeakSet(), Symbol.hasInstance)](value) { + if (!value) { + return false; + } + const val = value; + return Boolean(isFunction$b(val.constructor) + && val[Symbol.toStringTag] === "FormData" + && isFunction$b(val.append) + && isFunction$b(val.set) + && isFunction$b(val.get) + && isFunction$b(val.getAll) + && isFunction$b(val.has) + && isFunction$b(val.delete) + && isFunction$b(val.entries) + && isFunction$b(val.values) + && isFunction$b(val.keys) + && isFunction$b(val[Symbol.iterator]) + && isFunction$b(val.forEach)); + } + append(name, value, fileName) { + __classPrivateFieldGet(this, _FormData_instances, "m", _FormData_setEntry).call(this, { + name, + fileName, + append: true, + rawValue: value, + argsLength: arguments.length + }); + } + set(name, value, fileName) { + __classPrivateFieldGet(this, _FormData_instances, "m", _FormData_setEntry).call(this, { + name, + fileName, + append: false, + rawValue: value, + argsLength: arguments.length + }); + } + get(name) { + const field = __classPrivateFieldGet(this, _FormData_entries, "f").get(String(name)); + if (!field) { + return null; + } + return field[0]; + } + getAll(name) { + const field = __classPrivateFieldGet(this, _FormData_entries, "f").get(String(name)); + if (!field) { + return []; + } + return field.slice(); + } + has(name) { + return __classPrivateFieldGet(this, _FormData_entries, "f").has(String(name)); + } + delete(name) { + __classPrivateFieldGet(this, _FormData_entries, "f").delete(String(name)); + } + *keys() { + for (const key of __classPrivateFieldGet(this, _FormData_entries, "f").keys()) { + yield key; + } + } + *entries() { + for (const name of this.keys()) { + const values = this.getAll(name); + for (const value of values) { + yield [name, value]; + } + } + } + *values() { + for (const [, value] of this) { + yield value; + } + } + [(_FormData_setEntry = function _FormData_setEntry({ name, rawValue, append, fileName, argsLength }) { + const methodName = append ? "append" : "set"; + if (argsLength < 2) { + throw new TypeError(`Failed to execute '${methodName}' on 'FormData': ` + + `2 arguments required, but only ${argsLength} present.`); + } + name = String(name); + let value; + if (isFile(rawValue)) { + value = fileName === undefined + ? rawValue + : new File([rawValue], fileName, { + type: rawValue.type, + lastModified: rawValue.lastModified + }); + } + else if (isBlob$1(rawValue)) { + value = new File([rawValue], fileName === undefined ? "blob" : fileName, { + type: rawValue.type + }); + } + else if (fileName) { + throw new TypeError(`Failed to execute '${methodName}' on 'FormData': ` + + "parameter 2 is not of type 'Blob'."); + } + else { + value = String(rawValue); + } + const values = __classPrivateFieldGet(this, _FormData_entries, "f").get(name); + if (!values) { + return void __classPrivateFieldGet(this, _FormData_entries, "f").set(name, [value]); + } + if (!append) { + return void __classPrivateFieldGet(this, _FormData_entries, "f").set(name, [value]); + } + values.push(value); + }, Symbol.iterator)]() { + return this.entries(); + } + forEach(callback, thisArg) { + for (const [name, value] of this) { + callback.call(thisArg, value, name, this); + } + } + get [Symbol.toStringTag]() { + return "FormData"; + } +} + +var tmpPromise = {exports: {}}; + +var tmp = {exports: {}}; + +var old = {}; + +var hasRequiredOld; + +function requireOld () { + if (hasRequiredOld) return old; + hasRequiredOld = 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$b; + var isWindows = process.platform === 'win32'; + var fs = require$$0$8; + + // 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) { + var nextPartRe = /(.*?)(?:[\/\\]+|$)/g; + } else { + var nextPartRe = /(.*?)(?:[\/]+|$)/g; + } + + // Regex to find the device root, including trailing slash. E.g. 'c:\\'. + if (isWindows) { + var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/; + } else { + var splitRootRe = /^[\/]*/; + } + + old.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 && !knownHard[base]) { + fs.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.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) { + var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); + if (seenLinks.hasOwnProperty(id)) { + linkTarget = seenLinks[id]; + } + } + if (linkTarget === null) { + fs.statSync(base); + linkTarget = fs.readlinkSync(base); + } + resolvedLink = pathModule.resolve(previous, linkTarget); + // track this, if given a cache. + if (cache) cache[base] = resolvedLink; + if (!isWindows) 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.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 && !knownHard[base]) { + fs.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.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) { + var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); + if (seenLinks.hasOwnProperty(id)) { + return gotTarget(null, seenLinks[id], base); + } + } + fs.stat(base, function(err) { + if (err) return cb(err); + + fs.readlink(base, function(err, target) { + if (!isWindows) 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(); + } + }; + return old; +} + +var fs_realpath; +var hasRequiredFs_realpath; + +function requireFs_realpath () { + if (hasRequiredFs_realpath) return fs_realpath; + hasRequiredFs_realpath = 1; + fs_realpath = realpath; + realpath.realpath = realpath; + realpath.sync = realpathSync; + realpath.realpathSync = realpathSync; + realpath.monkeypatch = monkeypatch; + realpath.unmonkeypatch = unmonkeypatch; + + var fs = require$$0$8; + var origRealpath = fs.realpath; + var origRealpathSync = fs.realpathSync; + + var version = process.version; + var ok = /^v[0-5]\./.test(version); + var old = requireOld(); + + 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.realpath = realpath; + fs.realpathSync = realpathSync; + } + + function unmonkeypatch () { + fs.realpath = origRealpath; + fs.realpathSync = origRealpathSync; + } + return fs_realpath; +} + +var concatMap; +var hasRequiredConcatMap; + +function requireConcatMap () { + if (hasRequiredConcatMap) return concatMap; + hasRequiredConcatMap = 1; + concatMap = function (xs, fn) { + var res = []; + for (var i = 0; i < xs.length; i++) { + var x = fn(xs[i], i); + if (isArray(x)) res.push.apply(res, x); + else res.push(x); + } + return res; + }; + + var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; + }; + return concatMap; +} + +var balancedMatch; +var hasRequiredBalancedMatch; + +function requireBalancedMatch () { + if (hasRequiredBalancedMatch) return balancedMatch; + hasRequiredBalancedMatch = 1; + balancedMatch = balanced; + function balanced(a, b, str) { + if (a instanceof RegExp) a = maybeMatch(a, str); + if (b instanceof RegExp) b = maybeMatch(b, str); + + var r = range(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.range = range; + function range(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; + } + return balancedMatch; +} + +var braceExpansion; +var hasRequiredBraceExpansion; + +function requireBraceExpansion () { + if (hasRequiredBraceExpansion) return braceExpansion; + hasRequiredBraceExpansion = 1; + var concatMap = requireConcatMap(); + var balanced = requireBalancedMatch(); + + 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(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(str, isTop) { + var expansions = []; + + var m = balanced('{', '}', str); + if (!m || /\$$/.test(m.pre)) return [str]; + + 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(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(n[0], false).map(embrace); + if (n.length === 1) { + var post = m.post.length + ? expand(m.post, false) + : ['']; + 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. + + // 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(m.post, false) + : ['']; + + 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 = concatMap(n, function(el) { return expand(el, 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; + } + return braceExpansion; +} + +var minimatch_1; +var hasRequiredMinimatch; + +function requireMinimatch () { + if (hasRequiredMinimatch) return minimatch_1; + hasRequiredMinimatch = 1; + minimatch_1 = minimatch; + minimatch.Minimatch = Minimatch; + + var path = (function () { try { return require('path') } catch (e) {}}()) || { + sep: '/' + }; + minimatch.sep = path.sep; + + var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {}; + var expand = requireBraceExpansion(); + + var 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() + var qmark = '[^/]'; + + // * => any number of characters + var 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. + var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?'; + + // not a ^ or / followed by a dot, + // followed by anything, any number of times. + var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?'; + + // characters that need to be escaped in RegExp. + var reSpecials = charSet('().*{}+?[]^$\\!'); + + // "abc" -> { a:true, b:true, c:true } + function charSet (s) { + return s.split('').reduce(function (set, c) { + set[c] = true; + return set + }, {}) + } + + // normalizes slashes. + var slashSplit = /\/+/; + + minimatch.filter = filter; + function filter (pattern, options) { + options = options || {}; + return function (p, i, list) { + return minimatch(p, pattern, options) + } + } + + function ext (a, b) { + b = b || {}; + var t = {}; + Object.keys(a).forEach(function (k) { + t[k] = a[k]; + }); + Object.keys(b).forEach(function (k) { + t[k] = b[k]; + }); + return t + } + + minimatch.defaults = function (def) { + if (!def || typeof def !== 'object' || !Object.keys(def).length) { + return minimatch + } + + var orig = minimatch; + + var m = function minimatch (p, pattern, options) { + return orig(p, pattern, ext(def, options)) + }; + + m.Minimatch = function Minimatch (pattern, options) { + return new orig.Minimatch(pattern, ext(def, options)) + }; + m.Minimatch.defaults = function defaults (options) { + return orig.defaults(ext(def, options)).Minimatch + }; + + m.filter = function filter (pattern, options) { + return orig.filter(pattern, ext(def, options)) + }; + + m.defaults = function defaults (options) { + return orig.defaults(ext(def, options)) + }; + + m.makeRe = function makeRe (pattern, options) { + return orig.makeRe(pattern, ext(def, options)) + }; + + m.braceExpand = function braceExpand (pattern, options) { + return orig.braceExpand(pattern, ext(def, options)) + }; + + m.match = function (list, pattern, options) { + return orig.match(list, pattern, ext(def, options)) + }; + + return m + }; + + Minimatch.defaults = function (def) { + return minimatch.defaults(def).Minimatch + }; + + function minimatch (p, pattern, options) { + assertValidPattern(pattern); + + if (!options) options = {}; + + // shortcut: comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + return false + } + + return new Minimatch(pattern, options).match(p) + } + + function Minimatch (pattern, options) { + if (!(this instanceof Minimatch)) { + return new Minimatch(pattern, options) + } + + assertValidPattern(pattern); + + if (!options) options = {}; + + pattern = pattern.trim(); + + // windows support: need to use /, not \ + if (!options.allowWindowsEscape && path.sep !== '/') { + pattern = pattern.split(path.sep).join('/'); + } + + this.options = options; + this.set = []; + this.pattern = pattern; + this.regexp = null; + this.negate = false; + this.comment = false; + this.empty = false; + this.partial = !!options.partial; + + // make the set of regexps etc. + this.make(); + } + + Minimatch.prototype.debug = function () {}; + + Minimatch.prototype.make = make; + function make () { + var pattern = this.pattern; + var 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 + var set = this.globSet = this.braceExpand(); + + if (options.debug) this.debug = function debug() { console.error.apply(console, arguments); }; + + 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(function (s) { + return s.split(slashSplit) + }); + + this.debug(this.pattern, set); + + // glob --> regexps + set = set.map(function (s, si, set) { + return s.map(this.parse, this) + }, this); + + this.debug(this.pattern, set); + + // filter out everything that didn't compile properly. + set = set.filter(function (s) { + return s.indexOf(false) === -1 + }); + + this.debug(this.pattern, set); + + this.set = set; + } + + Minimatch.prototype.parseNegate = parseNegate; + function parseNegate () { + var pattern = this.pattern; + var negate = false; + var options = this.options; + var negateOffset = 0; + + if (options.nonegate) return + + for (var i = 0, l = pattern.length + ; i < l && pattern.charAt(i) === '!' + ; i++) { + negate = !negate; + negateOffset++; + } + + if (negateOffset) this.pattern = pattern.substr(negateOffset); + this.negate = negate; + } + + // 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.braceExpand = function (pattern, options) { + return braceExpand(pattern, options) + }; + + Minimatch.prototype.braceExpand = braceExpand; + + function braceExpand (pattern, options) { + if (!options) { + if (this instanceof Minimatch) { + options = this.options; + } else { + options = {}; + } + } + + pattern = typeof pattern === 'undefined' + ? this.pattern : pattern; + + assertValidPattern(pattern); + + // Thanks to Yeting Li <https://github.com/yetingli> for + // improving this regexp to avoid a ReDOS vulnerability. + if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) { + // shortcut. no need to expand. + return [pattern] + } + + return expand(pattern) + } + + var MAX_PATTERN_LENGTH = 1024 * 64; + var assertValidPattern = function (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. + Minimatch.prototype.parse = parse; + var SUBPARSE = {}; + function parse (pattern, isSub) { + assertValidPattern(pattern); + + var options = this.options; + + // shortcuts + if (pattern === '**') { + if (!options.noglobstar) + return GLOBSTAR + else + pattern = '*'; + } + if (pattern === '') return '' + + var re = ''; + var hasMagic = !!options.nocase; + var escaping = false; + // ? => one single character + var patternListStack = []; + var negativeLists = []; + var stateChar; + var inClass = false; + var reClassStart = -1; + var classStart = -1; + // . and .. never match anything that doesn't start with ., + // even when options.dot is set. + var patternStart = pattern.charAt(0) === '.' ? '' // anything + // not (start or / followed by . or .. followed by / or end) + : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))' + : '(?!\\.)'; + var self = this; + + function 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 + } + self.debug('clearStateChar %j %j', stateChar, re); + stateChar = false; + } + } + + for (var i = 0, len = pattern.length, c + ; (i < len) && (c = pattern.charAt(i)) + ; i++) { + this.debug('%s\t%s %s %j', pattern, i, re, c); + + // skip over any that are escaped. + if (escaping && reSpecials[c]) { + re += '\\' + c; + escaping = false; + continue + } + + switch (c) { + /* istanbul ignore next */ + case '/': { + // completely not allowed, even escaped. + // Should already be path-split by now. + return false + } + + case '\\': + 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. + self.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 + } + + patternListStack.push({ + type: stateChar, + start: i - 1, + reStart: re.length, + open: plTypes[stateChar].open, + close: plTypes[stateChar].close + }); + // negation is (?:(?!js)[^/]*) + re += stateChar === '!' ? '(?:(?!(?:' : '(?:'; + this.debug('plType %j %j', stateChar, re); + stateChar = false; + continue + + case ')': + if (inClass || !patternListStack.length) { + re += '\\)'; + continue + } + + clearStateChar(); + hasMagic = true; + var pl = patternListStack.pop(); + // negation is (?:(?!js)[^/]*) + // The others are (?:<pattern>)<type> + re += pl.close; + if (pl.type === '!') { + negativeLists.push(pl); + } + pl.reEnd = re.length; + continue + + case '|': + if (inClass || !patternListStack.length || escaping) { + re += '\\|'; + escaping = false; + continue + } + + clearStateChar(); + re += '|'; + 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; + escaping = false; + continue + } + + // handle the case where we left a class open. + // "[z-a]" is valid, equivalent to "\[z-a\]" + // 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. + var cs = pattern.substring(classStart + 1, i); + try { + RegExp('[' + cs + ']'); + } catch (er) { + // not a valid class! + var sp = this.parse(cs, SUBPARSE); + re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]'; + hasMagic = hasMagic || sp[1]; + inClass = false; + continue + } + + // finish up the class. + hasMagic = true; + inClass = false; + re += c; + continue + + default: + // swallow any state char that wasn't consumed + clearStateChar(); + + if (escaping) { + // no need + escaping = false; + } else if (reSpecials[c] + && !(c === '^' && inClass)) { + re += '\\'; + } + + re += c; + + } // 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.substr(classStart + 1); + sp = this.parse(cs, SUBPARSE); + re = re.substr(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()) { + var 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, function (_, $1, $2) { + 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); + var 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 + var addPatternStart = false; + switch (re.charAt(0)) { + case '[': case '.': case '(': addPatternStart = true; + } + + // 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 (var n = negativeLists.length - 1; n > -1; n--) { + var nl = negativeLists[n]; + + var nlBefore = re.slice(0, nl.reStart); + var nlFirst = re.slice(nl.reStart, nl.reEnd - 8); + var nlLast = re.slice(nl.reEnd - 8, nl.reEnd); + var nlAfter = re.slice(nl.reEnd); + + nlLast += 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. + var openParensBefore = nlBefore.split('(').length - 1; + var cleanAfter = nlAfter; + for (i = 0; i < openParensBefore; i++) { + cleanAfter = cleanAfter.replace(/\)[+*?]?/, ''); + } + nlAfter = cleanAfter; + + var dollar = ''; + if (nlAfter === '' && isSub !== SUBPARSE) { + dollar = '$'; + } + var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast; + re = newRe; + } + + // 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] + } + + // 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) + } + + var flags = options.nocase ? 'i' : ''; + try { + var regExp = new RegExp('^' + re + '$', flags); + } 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('$.') + } + + regExp._glob = pattern; + regExp._src = re; + + return regExp + } + + minimatch.makeRe = function (pattern, options) { + return new Minimatch(pattern, options || {}).makeRe() + }; + + Minimatch.prototype.makeRe = makeRe; + function 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. + var set = this.set; + + if (!set.length) { + this.regexp = false; + return this.regexp + } + var options = this.options; + + var twoStar = options.noglobstar ? star + : options.dot ? twoStarDot + : twoStarNoDot; + var flags = options.nocase ? 'i' : ''; + + var re = set.map(function (pattern) { + return pattern.map(function (p) { + return (p === GLOBSTAR) ? twoStar + : (typeof p === 'string') ? regExpEscape(p) + : p._src + }).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 + } + + minimatch.match = function (list, pattern, options) { + options = options || {}; + var mm = new Minimatch(pattern, options); + list = list.filter(function (f) { + return mm.match(f) + }); + if (mm.options.nonull && !list.length) { + list.push(pattern); + } + return list + }; + + Minimatch.prototype.match = function match (f, partial) { + if (typeof partial === 'undefined') 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 + + var options = this.options; + + // windows: need to use /, not \ + if (path.sep !== '/') { + f = f.split(path.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. + + var set = this.set; + this.debug(this.pattern, 'set', set); + + // Find the basename of the path by looking for the last non-empty segment + var filename; + var i; + for (i = f.length - 1; i >= 0; i--) { + filename = f[i]; + if (filename) break + } + + for (i = 0; i < set.length; i++) { + var pattern = set[i]; + var file = f; + if (options.matchBase && pattern.length === 1) { + file = [filename]; + } + var 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 + }; + + // 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. + Minimatch.prototype.matchOne = function (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?') + }; + + // replace stuff like \* with * + function globUnescape (s) { + return s.replace(/\\(.)/g, '$1') + } + + function regExpEscape (s) { + return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') + } + return minimatch_1; +} + +var pathIsAbsolute = {exports: {}}; + +var hasRequiredPathIsAbsolute; + +function requirePathIsAbsolute () { + if (hasRequiredPathIsAbsolute) return pathIsAbsolute.exports; + hasRequiredPathIsAbsolute = 1; + + function posix(path) { + return path.charAt(0) === '/'; + } + + function win32(path) { + // https://github.com/nodejs/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56 + var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/; + var result = splitDeviceRe.exec(path); + var device = result[1] || ''; + var isUnc = Boolean(device && device.charAt(1) !== ':'); + + // UNC paths are always absolute + return Boolean(result[2] || isUnc); + } + + pathIsAbsolute.exports = process.platform === 'win32' ? win32 : posix; + pathIsAbsolute.exports.posix = posix; + pathIsAbsolute.exports.win32 = win32; + return pathIsAbsolute.exports; +} + +var common$1 = {}; + +var hasRequiredCommon; + +function requireCommon () { + if (hasRequiredCommon) return common$1; + hasRequiredCommon = 1; + common$1.setopts = setopts; + common$1.ownProp = ownProp; + common$1.makeAbs = makeAbs; + common$1.finish = finish; + common$1.mark = mark; + common$1.isIgnored = isIgnored; + common$1.childrenIgnored = childrenIgnored; + + function ownProp (obj, field) { + return Object.prototype.hasOwnProperty.call(obj, field) + } + + var fs = require$$0$8; + var path = require$$0$b; + var minimatch = requireMinimatch(); + var isAbsolute = requirePathIsAbsolute(); + 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.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; + + 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 = cwd; + else { + self.cwd = path.resolve(options.cwd); + self.changedCwd = self.cwd !== cwd; + } + + self.root = options.root || path.resolve(self.cwd, "/"); + self.root = path.resolve(self.root); + if (process.platform === "win32") + self.root = self.root.replace(/\\/g, "/"); + + // TODO: is an absolute `cwd` supposed to be resolved against `root`? + // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test') + self.cwdAbs = isAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd); + if (process.platform === "win32") + self.cwdAbs = self.cwdAbs.replace(/\\/g, "/"); + self.nomount = !!options.nomount; + + // disable comments and negation in Minimatch. + // Note that they are not supported in Glob itself anyway. + options.nonegate = true; + options.nocomment = true; + // always treat \ in patterns as escapes, not path separators + options.allowWindowsEscape = false; + + 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 (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.join(self.root, f); + } else if (isAbsolute(f) || f === '') { + abs = f; + } else if (self.changedCwd) { + abs = path.resolve(self.cwd, f); + } else { + abs = path.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)) + }) + } + return common$1; +} + +var sync; +var hasRequiredSync; + +function requireSync () { + if (hasRequiredSync) return sync; + hasRequiredSync = 1; + sync = globSync; + globSync.GlobSync = GlobSync; + + var rp = requireFs_realpath(); + var minimatch = requireMinimatch(); + minimatch.Minimatch; + requireGlob().Glob; + var path = require$$0$b; + var assert = require$$5$1; + var isAbsolute = requirePathIsAbsolute(); + var common = requireCommon(); + 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; +} + +var wrappy_1; +var hasRequiredWrappy; + +function requireWrappy () { + if (hasRequiredWrappy) return wrappy_1; + hasRequiredWrappy = 1; + // Returns a wrapper function that returns a wrapped callback + // The wrapper function should do some stuff, and return a + // presumably different callback function. + // This makes sure that own properties are retained, so that + // decorations and such are not lost along the way. + wrappy_1 = wrappy; + function wrappy (fn, cb) { + if (fn && cb) return wrappy(fn)(cb) + + if (typeof fn !== 'function') + throw new TypeError('need wrapper function') + + Object.keys(fn).forEach(function (k) { + wrapper[k] = fn[k]; + }); + + return wrapper + + function wrapper() { + var args = new Array(arguments.length); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i]; + } + var ret = fn.apply(this, args); + var cb = args[args.length-1]; + if (typeof ret === 'function' && ret !== cb) { + Object.keys(cb).forEach(function (k) { + ret[k] = cb[k]; + }); + } + return ret + } + } + return wrappy_1; +} + +var once = {exports: {}}; + +var hasRequiredOnce; + +function requireOnce () { + if (hasRequiredOnce) return once.exports; + hasRequiredOnce = 1; + var wrappy = requireWrappy(); + once.exports = wrappy(once$1); + once.exports.strict = wrappy(onceStrict); + + once$1.proto = once$1(function () { + Object.defineProperty(Function.prototype, 'once', { + value: function () { + return once$1(this) + }, + configurable: true + }); + + Object.defineProperty(Function.prototype, 'onceStrict', { + value: function () { + return onceStrict(this) + }, + configurable: true + }); + }); + + function once$1 (fn) { + var f = function () { + if (f.called) return f.value + f.called = true; + return f.value = fn.apply(this, arguments) + }; + f.called = false; + return f + } + + function onceStrict (fn) { + var f = function () { + if (f.called) + throw new Error(f.onceError) + f.called = true; + return f.value = fn.apply(this, arguments) + }; + var name = fn.name || 'Function wrapped with `once`'; + f.onceError = name + " shouldn't be called more than once"; + f.called = false; + return f + } + return once.exports; +} + +var inflight_1; +var hasRequiredInflight; + +function requireInflight () { + if (hasRequiredInflight) return inflight_1; + hasRequiredInflight = 1; + var wrappy = requireWrappy(); + var reqs = Object.create(null); + var once = requireOnce(); + + 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 + } + return inflight_1; +} + +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 = requireFs_realpath(); + var minimatch = requireMinimatch(); + minimatch.Minimatch; + var inherits = inheritsExports; + var EE = require$$2$3.EventEmitter; + var path = require$$0$b; + var assert = require$$5$1; + var isAbsolute = requirePathIsAbsolute(); + var globSync = requireSync(); + var common = requireCommon(); + var setopts = common.setopts; + var ownProp = common.ownProp; + var inflight = requireInflight(); + var childrenIgnored = common.childrenIgnored; + var isIgnored = common.isIgnored; + + var once = requireOnce(); + + 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 {<filename>: 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; +} + +const assert = require$$5$1; +const path = require$$0$b; +const fs = require$$0$8; +let glob = undefined; +try { + glob = requireGlob(); +} catch (_err) { + // treat glob as optional. +} + +const defaultGlobOpts = { + nosort: true, + silent: true +}; + +// for EMFILE handling +let timeout = 0; + +const isWindows = (process.platform === "win32"); + +const defaults$2 = options => { + const methods = [ + 'unlink', + 'chmod', + 'stat', + 'lstat', + 'rmdir', + 'readdir' + ]; + methods.forEach(m => { + options[m] = options[m] || fs[m]; + m = m + 'Sync'; + options[m] = options[m] || fs[m]; + }); + + options.maxBusyTries = options.maxBusyTries || 3; + options.emfileWait = options.emfileWait || 1000; + if (options.glob === false) { + options.disableGlob = true; + } + if (options.disableGlob !== true && glob === undefined) { + throw Error('glob dependency not found, set `options.disableGlob = true` if intentional') + } + options.disableGlob = options.disableGlob || false; + options.glob = options.glob || defaultGlobOpts; +}; + +const rimraf = (p, options, cb) => { + if (typeof options === 'function') { + cb = options; + options = {}; + } + + assert(p, 'rimraf: missing path'); + assert.equal(typeof p, 'string', 'rimraf: path should be a string'); + assert.equal(typeof cb, 'function', 'rimraf: callback function required'); + assert(options, 'rimraf: invalid options argument provided'); + assert.equal(typeof options, 'object', 'rimraf: options should be object'); + + defaults$2(options); + + let busyTries = 0; + let errState = null; + let n = 0; + + const next = (er) => { + errState = errState || er; + if (--n === 0) + cb(errState); + }; + + const afterGlob = (er, results) => { + if (er) + return cb(er) + + n = results.length; + if (n === 0) + return cb() + + results.forEach(p => { + const CB = (er) => { + if (er) { + if ((er.code === "EBUSY" || er.code === "ENOTEMPTY" || er.code === "EPERM") && + busyTries < options.maxBusyTries) { + busyTries ++; + // try again, with the same exact callback as this one. + return setTimeout(() => rimraf_(p, options, CB), busyTries * 100) + } + + // this one won't happen if graceful-fs is used. + if (er.code === "EMFILE" && timeout < options.emfileWait) { + return setTimeout(() => rimraf_(p, options, CB), timeout ++) + } + + // already gone + if (er.code === "ENOENT") er = null; + } + + timeout = 0; + next(er); + }; + rimraf_(p, options, CB); + }); + }; + + if (options.disableGlob || !glob.hasMagic(p)) + return afterGlob(null, [p]) + + options.lstat(p, (er, stat) => { + if (!er) + return afterGlob(null, [p]) + + glob(p, options.glob, afterGlob); + }); + +}; + +// Two possible strategies. +// 1. Assume it's a file. unlink it, then do the dir stuff on EPERM or EISDIR +// 2. Assume it's a directory. readdir, then do the file stuff on ENOTDIR +// +// Both result in an extra syscall when you guess wrong. However, there +// are likely far more normal files in the world than directories. This +// is based on the assumption that a the average number of files per +// directory is >= 1. +// +// If anyone ever complains about this, then I guess the strategy could +// be made configurable somehow. But until then, YAGNI. +const rimraf_ = (p, options, cb) => { + assert(p); + assert(options); + assert(typeof cb === 'function'); + + // sunos lets the root user unlink directories, which is... weird. + // so we have to lstat here and make sure it's not a dir. + options.lstat(p, (er, st) => { + if (er && er.code === "ENOENT") + return cb(null) + + // Windows can EPERM on stat. Life is suffering. + if (er && er.code === "EPERM" && isWindows) + fixWinEPERM(p, options, er, cb); + + if (st && st.isDirectory()) + return rmdir(p, options, er, cb) + + options.unlink(p, er => { + if (er) { + if (er.code === "ENOENT") + return cb(null) + if (er.code === "EPERM") + return (isWindows) + ? fixWinEPERM(p, options, er, cb) + : rmdir(p, options, er, cb) + if (er.code === "EISDIR") + return rmdir(p, options, er, cb) + } + return cb(er) + }); + }); +}; + +const fixWinEPERM = (p, options, er, cb) => { + assert(p); + assert(options); + assert(typeof cb === 'function'); + + options.chmod(p, 0o666, er2 => { + if (er2) + cb(er2.code === "ENOENT" ? null : er); + else + options.stat(p, (er3, stats) => { + if (er3) + cb(er3.code === "ENOENT" ? null : er); + else if (stats.isDirectory()) + rmdir(p, options, er, cb); + else + options.unlink(p, cb); + }); + }); +}; + +const fixWinEPERMSync = (p, options, er) => { + assert(p); + assert(options); + + try { + options.chmodSync(p, 0o666); + } catch (er2) { + if (er2.code === "ENOENT") + return + else + throw er + } + + let stats; + try { + stats = options.statSync(p); + } catch (er3) { + if (er3.code === "ENOENT") + return + else + throw er + } + + if (stats.isDirectory()) + rmdirSync(p, options, er); + else + options.unlinkSync(p); +}; + +const rmdir = (p, options, originalEr, cb) => { + assert(p); + assert(options); + assert(typeof cb === 'function'); + + // try to rmdir first, and only readdir on ENOTEMPTY or EEXIST (SunOS) + // if we guessed wrong, and it's not a directory, then + // raise the original error. + options.rmdir(p, er => { + if (er && (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM")) + rmkids(p, options, cb); + else if (er && er.code === "ENOTDIR") + cb(originalEr); + else + cb(er); + }); +}; + +const rmkids = (p, options, cb) => { + assert(p); + assert(options); + assert(typeof cb === 'function'); + + options.readdir(p, (er, files) => { + if (er) + return cb(er) + let n = files.length; + if (n === 0) + return options.rmdir(p, cb) + let errState; + files.forEach(f => { + rimraf(path.join(p, f), options, er => { + if (errState) + return + if (er) + return cb(errState = er) + if (--n === 0) + options.rmdir(p, cb); + }); + }); + }); +}; + +// this looks simpler, and is strictly *faster*, but will +// tie up the JavaScript thread and fail on excessively +// deep directory trees. +const rimrafSync = (p, options) => { + options = options || {}; + defaults$2(options); + + assert(p, 'rimraf: missing path'); + assert.equal(typeof p, 'string', 'rimraf: path should be a string'); + assert(options, 'rimraf: missing options'); + assert.equal(typeof options, 'object', 'rimraf: options should be object'); + + let results; + + if (options.disableGlob || !glob.hasMagic(p)) { + results = [p]; + } else { + try { + options.lstatSync(p); + results = [p]; + } catch (er) { + results = glob.sync(p, options.glob); + } + } + + if (!results.length) + return + + for (let i = 0; i < results.length; i++) { + const p = results[i]; + + let st; + try { + st = options.lstatSync(p); + } catch (er) { + if (er.code === "ENOENT") + return + + // Windows can EPERM on stat. Life is suffering. + if (er.code === "EPERM" && isWindows) + fixWinEPERMSync(p, options, er); + } + + try { + // sunos lets the root user unlink directories, which is... weird. + if (st && st.isDirectory()) + rmdirSync(p, options, null); + else + options.unlinkSync(p); + } catch (er) { + if (er.code === "ENOENT") + return + if (er.code === "EPERM") + return isWindows ? fixWinEPERMSync(p, options, er) : rmdirSync(p, options, er) + if (er.code !== "EISDIR") + throw er + + rmdirSync(p, options, er); + } + } +}; + +const rmdirSync = (p, options, originalEr) => { + assert(p); + assert(options); + + try { + options.rmdirSync(p); + } catch (er) { + if (er.code === "ENOENT") + return + if (er.code === "ENOTDIR") + throw originalEr + if (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM") + rmkidsSync(p, options); + } +}; + +const rmkidsSync = (p, options) => { + assert(p); + assert(options); + options.readdirSync(p).forEach(f => rimrafSync(path.join(p, f), options)); + + // We only end up here once we got ENOTEMPTY at least once, and + // at this point, we are guaranteed to have removed all the kids. + // So, we know that it won't be ENOENT or ENOTDIR or anything else. + // try really hard to delete stuff on windows, because it has a + // PROFOUNDLY annoying habit of not closing handles promptly when + // files are deleted, resulting in spurious ENOTEMPTY errors. + const retries = isWindows ? 100 : 1; + let i = 0; + do { + let threw = true; + try { + const ret = options.rmdirSync(p, options); + threw = false; + return ret + } finally { + if (++i < retries && threw) + continue + } + } while (true) +}; + +var rimraf_1 = rimraf; +rimraf.sync = rimrafSync; + +/*! + * Tmp + * + * Copyright (c) 2011-2017 KARASZI Istvan <github@spam.raszi.hu> + * + * MIT Licensed + */ + +(function (module) { + /* + * Module dependencies. + */ + const fs = require$$0$8; + const os = require$$0$7; + const path = require$$0$b; + const crypto$1 = crypto; + const _c = { fs: fs.constants, os: os.constants }; + const rimraf = rimraf_1; + + /* + * The working inner variables. + */ + const + // the random characters to choose from + RANDOM_CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', + + TEMPLATE_PATTERN = /XXXXXX/, + + DEFAULT_TRIES = 3, + + CREATE_FLAGS = (_c.O_CREAT || _c.fs.O_CREAT) | (_c.O_EXCL || _c.fs.O_EXCL) | (_c.O_RDWR || _c.fs.O_RDWR), + + // constants are off on the windows platform and will not match the actual errno codes + IS_WIN32 = os.platform() === 'win32', + EBADF = _c.EBADF || _c.os.errno.EBADF, + ENOENT = _c.ENOENT || _c.os.errno.ENOENT, + + DIR_MODE = 0o700 /* 448 */, + FILE_MODE = 0o600 /* 384 */, + + EXIT = 'exit', + + // this will hold the objects need to be removed on exit + _removeObjects = [], + + // API change in fs.rmdirSync leads to error when passing in a second parameter, e.g. the callback + FN_RMDIR_SYNC = fs.rmdirSync.bind(fs), + FN_RIMRAF_SYNC = rimraf.sync; + + let + _gracefulCleanup = false; + + /** + * Gets a temporary file name. + * + * @param {(Options|tmpNameCallback)} options options or callback + * @param {?tmpNameCallback} callback the callback function + */ + function tmpName(options, callback) { + const + args = _parseArguments(options, callback), + opts = args[0], + cb = args[1]; + + try { + _assertAndSanitizeOptions(opts); + } catch (err) { + return cb(err); + } + + let tries = opts.tries; + (function _getUniqueName() { + try { + const name = _generateTmpName(opts); + + // check whether the path exists then retry if needed + fs.stat(name, function (err) { + /* istanbul ignore else */ + if (!err) { + /* istanbul ignore else */ + if (tries-- > 0) return _getUniqueName(); + + return cb(new Error('Could not get a unique tmp filename, max tries reached ' + name)); + } + + cb(null, name); + }); + } catch (err) { + cb(err); + } + }()); + } + + /** + * Synchronous version of tmpName. + * + * @param {Object} options + * @returns {string} the generated random name + * @throws {Error} if the options are invalid or could not generate a filename + */ + function tmpNameSync(options) { + const + args = _parseArguments(options), + opts = args[0]; + + _assertAndSanitizeOptions(opts); + + let tries = opts.tries; + do { + const name = _generateTmpName(opts); + try { + fs.statSync(name); + } catch (e) { + return name; + } + } while (tries-- > 0); + + throw new Error('Could not get a unique tmp filename, max tries reached'); + } + + /** + * Creates and opens a temporary file. + * + * @param {(Options|null|undefined|fileCallback)} options the config options or the callback function or null or undefined + * @param {?fileCallback} callback + */ + function file(options, callback) { + const + args = _parseArguments(options, callback), + opts = args[0], + cb = args[1]; + + // gets a temporary filename + tmpName(opts, function _tmpNameCreated(err, name) { + /* istanbul ignore else */ + if (err) return cb(err); + + // create and open the file + fs.open(name, CREATE_FLAGS, opts.mode || FILE_MODE, function _fileCreated(err, fd) { + /* istanbu ignore else */ + if (err) return cb(err); + + if (opts.discardDescriptor) { + return fs.close(fd, function _discardCallback(possibleErr) { + // the chance of getting an error on close here is rather low and might occur in the most edgiest cases only + return cb(possibleErr, name, undefined, _prepareTmpFileRemoveCallback(name, -1, opts, false)); + }); + } else { + // detachDescriptor passes the descriptor whereas discardDescriptor closes it, either way, we no longer care + // about the descriptor + const discardOrDetachDescriptor = opts.discardDescriptor || opts.detachDescriptor; + cb(null, name, fd, _prepareTmpFileRemoveCallback(name, discardOrDetachDescriptor ? -1 : fd, opts, false)); + } + }); + }); + } + + /** + * Synchronous version of file. + * + * @param {Options} options + * @returns {FileSyncObject} object consists of name, fd and removeCallback + * @throws {Error} if cannot create a file + */ + function fileSync(options) { + const + args = _parseArguments(options), + opts = args[0]; + + const discardOrDetachDescriptor = opts.discardDescriptor || opts.detachDescriptor; + const name = tmpNameSync(opts); + var fd = fs.openSync(name, CREATE_FLAGS, opts.mode || FILE_MODE); + /* istanbul ignore else */ + if (opts.discardDescriptor) { + fs.closeSync(fd); + fd = undefined; + } + + return { + name: name, + fd: fd, + removeCallback: _prepareTmpFileRemoveCallback(name, discardOrDetachDescriptor ? -1 : fd, opts, true) + }; + } + + /** + * Creates a temporary directory. + * + * @param {(Options|dirCallback)} options the options or the callback function + * @param {?dirCallback} callback + */ + function dir(options, callback) { + const + args = _parseArguments(options, callback), + opts = args[0], + cb = args[1]; + + // gets a temporary filename + tmpName(opts, function _tmpNameCreated(err, name) { + /* istanbul ignore else */ + if (err) return cb(err); + + // create the directory + fs.mkdir(name, opts.mode || DIR_MODE, function _dirCreated(err) { + /* istanbul ignore else */ + if (err) return cb(err); + + cb(null, name, _prepareTmpDirRemoveCallback(name, opts, false)); + }); + }); + } + + /** + * Synchronous version of dir. + * + * @param {Options} options + * @returns {DirSyncObject} object consists of name and removeCallback + * @throws {Error} if it cannot create a directory + */ + function dirSync(options) { + const + args = _parseArguments(options), + opts = args[0]; + + const name = tmpNameSync(opts); + fs.mkdirSync(name, opts.mode || DIR_MODE); + + return { + name: name, + removeCallback: _prepareTmpDirRemoveCallback(name, opts, true) + }; + } + + /** + * Removes files asynchronously. + * + * @param {Object} fdPath + * @param {Function} next + * @private + */ + function _removeFileAsync(fdPath, next) { + const _handler = function (err) { + if (err && !_isENOENT(err)) { + // reraise any unanticipated error + return next(err); + } + next(); + }; + + if (0 <= fdPath[0]) + fs.close(fdPath[0], function () { + fs.unlink(fdPath[1], _handler); + }); + else fs.unlink(fdPath[1], _handler); + } + + /** + * Removes files synchronously. + * + * @param {Object} fdPath + * @private + */ + function _removeFileSync(fdPath) { + let rethrownException = null; + try { + if (0 <= fdPath[0]) fs.closeSync(fdPath[0]); + } catch (e) { + // reraise any unanticipated error + if (!_isEBADF(e) && !_isENOENT(e)) throw e; + } finally { + try { + fs.unlinkSync(fdPath[1]); + } + catch (e) { + // reraise any unanticipated error + if (!_isENOENT(e)) rethrownException = e; + } + } + if (rethrownException !== null) { + throw rethrownException; + } + } + + /** + * Prepares the callback for removal of the temporary file. + * + * Returns either a sync callback or a async callback depending on whether + * fileSync or file was called, which is expressed by the sync parameter. + * + * @param {string} name the path of the file + * @param {number} fd file descriptor + * @param {Object} opts + * @param {boolean} sync + * @returns {fileCallback | fileCallbackSync} + * @private + */ + function _prepareTmpFileRemoveCallback(name, fd, opts, sync) { + const removeCallbackSync = _prepareRemoveCallback(_removeFileSync, [fd, name], sync); + const removeCallback = _prepareRemoveCallback(_removeFileAsync, [fd, name], sync, removeCallbackSync); + + if (!opts.keep) _removeObjects.unshift(removeCallbackSync); + + return sync ? removeCallbackSync : removeCallback; + } + + /** + * Prepares the callback for removal of the temporary directory. + * + * Returns either a sync callback or a async callback depending on whether + * tmpFileSync or tmpFile was called, which is expressed by the sync parameter. + * + * @param {string} name + * @param {Object} opts + * @param {boolean} sync + * @returns {Function} the callback + * @private + */ + function _prepareTmpDirRemoveCallback(name, opts, sync) { + const removeFunction = opts.unsafeCleanup ? rimraf : fs.rmdir.bind(fs); + const removeFunctionSync = opts.unsafeCleanup ? FN_RIMRAF_SYNC : FN_RMDIR_SYNC; + const removeCallbackSync = _prepareRemoveCallback(removeFunctionSync, name, sync); + const removeCallback = _prepareRemoveCallback(removeFunction, name, sync, removeCallbackSync); + if (!opts.keep) _removeObjects.unshift(removeCallbackSync); + + return sync ? removeCallbackSync : removeCallback; + } + + /** + * Creates a guarded function wrapping the removeFunction call. + * + * The cleanup callback is save to be called multiple times. + * Subsequent invocations will be ignored. + * + * @param {Function} removeFunction + * @param {string} fileOrDirName + * @param {boolean} sync + * @param {cleanupCallbackSync?} cleanupCallbackSync + * @returns {cleanupCallback | cleanupCallbackSync} + * @private + */ + function _prepareRemoveCallback(removeFunction, fileOrDirName, sync, cleanupCallbackSync) { + let called = false; + + // if sync is true, the next parameter will be ignored + return function _cleanupCallback(next) { + + /* istanbul ignore else */ + if (!called) { + // remove cleanupCallback from cache + const toRemove = cleanupCallbackSync || _cleanupCallback; + const index = _removeObjects.indexOf(toRemove); + /* istanbul ignore else */ + if (index >= 0) _removeObjects.splice(index, 1); + + called = true; + if (sync || removeFunction === FN_RMDIR_SYNC || removeFunction === FN_RIMRAF_SYNC) { + return removeFunction(fileOrDirName); + } else { + return removeFunction(fileOrDirName, next || function() {}); + } + } + }; + } + + /** + * The garbage collector. + * + * @private + */ + function _garbageCollector() { + /* istanbul ignore else */ + if (!_gracefulCleanup) return; + + // the function being called removes itself from _removeObjects, + // loop until _removeObjects is empty + while (_removeObjects.length) { + try { + _removeObjects[0](); + } catch (e) { + // already removed? + } + } + } + + /** + * Random name generator based on crypto. + * Adapted from http://blog.tompawlak.org/how-to-generate-random-values-nodejs-javascript + * + * @param {number} howMany + * @returns {string} the generated random name + * @private + */ + function _randomChars(howMany) { + let + value = [], + rnd = null; + + // make sure that we do not fail because we ran out of entropy + try { + rnd = crypto$1.randomBytes(howMany); + } catch (e) { + rnd = crypto$1.pseudoRandomBytes(howMany); + } + + for (var i = 0; i < howMany; i++) { + value.push(RANDOM_CHARS[rnd[i] % RANDOM_CHARS.length]); + } + + return value.join(''); + } + + /** + * Helper which determines whether a string s is blank, that is undefined, or empty or null. + * + * @private + * @param {string} s + * @returns {Boolean} true whether the string s is blank, false otherwise + */ + function _isBlank(s) { + return s === null || _isUndefined(s) || !s.trim(); + } + + /** + * Checks whether the `obj` parameter is defined or not. + * + * @param {Object} obj + * @returns {boolean} true if the object is undefined + * @private + */ + function _isUndefined(obj) { + return typeof obj === 'undefined'; + } + + /** + * Parses the function arguments. + * + * This function helps to have optional arguments. + * + * @param {(Options|null|undefined|Function)} options + * @param {?Function} callback + * @returns {Array} parsed arguments + * @private + */ + function _parseArguments(options, callback) { + /* istanbul ignore else */ + if (typeof options === 'function') { + return [{}, options]; + } + + /* istanbul ignore else */ + if (_isUndefined(options)) { + return [{}, callback]; + } + + // copy options so we do not leak the changes we make internally + const actualOptions = {}; + for (const key of Object.getOwnPropertyNames(options)) { + actualOptions[key] = options[key]; + } + + return [actualOptions, callback]; + } + + /** + * Generates a new temporary name. + * + * @param {Object} opts + * @returns {string} the new random name according to opts + * @private + */ + function _generateTmpName(opts) { + + const tmpDir = opts.tmpdir; + + /* istanbul ignore else */ + if (!_isUndefined(opts.name)) + return path.join(tmpDir, opts.dir, opts.name); + + /* istanbul ignore else */ + if (!_isUndefined(opts.template)) + return path.join(tmpDir, opts.dir, opts.template).replace(TEMPLATE_PATTERN, _randomChars(6)); + + // prefix and postfix + const name = [ + opts.prefix ? opts.prefix : 'tmp', + '-', + process.pid, + '-', + _randomChars(12), + opts.postfix ? '-' + opts.postfix : '' + ].join(''); + + return path.join(tmpDir, opts.dir, name); + } + + /** + * Asserts whether the specified options are valid, also sanitizes options and provides sane defaults for missing + * options. + * + * @param {Options} options + * @private + */ + function _assertAndSanitizeOptions(options) { + + options.tmpdir = _getTmpDir(options); + + const tmpDir = options.tmpdir; + + /* istanbul ignore else */ + if (!_isUndefined(options.name)) + _assertIsRelative(options.name, 'name', tmpDir); + /* istanbul ignore else */ + if (!_isUndefined(options.dir)) + _assertIsRelative(options.dir, 'dir', tmpDir); + /* istanbul ignore else */ + if (!_isUndefined(options.template)) { + _assertIsRelative(options.template, 'template', tmpDir); + if (!options.template.match(TEMPLATE_PATTERN)) + throw new Error(`Invalid template, found "${options.template}".`); + } + /* istanbul ignore else */ + if (!_isUndefined(options.tries) && isNaN(options.tries) || options.tries < 0) + throw new Error(`Invalid tries, found "${options.tries}".`); + + // if a name was specified we will try once + options.tries = _isUndefined(options.name) ? options.tries || DEFAULT_TRIES : 1; + options.keep = !!options.keep; + options.detachDescriptor = !!options.detachDescriptor; + options.discardDescriptor = !!options.discardDescriptor; + options.unsafeCleanup = !!options.unsafeCleanup; + + // sanitize dir, also keep (multiple) blanks if the user, purportedly sane, requests us to + options.dir = _isUndefined(options.dir) ? '' : path.relative(tmpDir, _resolvePath(options.dir, tmpDir)); + options.template = _isUndefined(options.template) ? undefined : path.relative(tmpDir, _resolvePath(options.template, tmpDir)); + // sanitize further if template is relative to options.dir + options.template = _isBlank(options.template) ? undefined : path.relative(options.dir, options.template); + + // for completeness' sake only, also keep (multiple) blanks if the user, purportedly sane, requests us to + options.name = _isUndefined(options.name) ? undefined : _sanitizeName(options.name); + options.prefix = _isUndefined(options.prefix) ? '' : options.prefix; + options.postfix = _isUndefined(options.postfix) ? '' : options.postfix; + } + + /** + * Resolve the specified path name in respect to tmpDir. + * + * The specified name might include relative path components, e.g. ../ + * so we need to resolve in order to be sure that is is located inside tmpDir + * + * @param name + * @param tmpDir + * @returns {string} + * @private + */ + function _resolvePath(name, tmpDir) { + const sanitizedName = _sanitizeName(name); + if (sanitizedName.startsWith(tmpDir)) { + return path.resolve(sanitizedName); + } else { + return path.resolve(path.join(tmpDir, sanitizedName)); + } + } + + /** + * Sanitize the specified path name by removing all quote characters. + * + * @param name + * @returns {string} + * @private + */ + function _sanitizeName(name) { + if (_isBlank(name)) { + return name; + } + return name.replace(/["']/g, ''); + } + + /** + * Asserts whether specified name is relative to the specified tmpDir. + * + * @param {string} name + * @param {string} option + * @param {string} tmpDir + * @throws {Error} + * @private + */ + function _assertIsRelative(name, option, tmpDir) { + if (option === 'name') { + // assert that name is not absolute and does not contain a path + if (path.isAbsolute(name)) + throw new Error(`${option} option must not contain an absolute path, found "${name}".`); + // must not fail on valid .<name> or ..<name> or similar such constructs + let basename = path.basename(name); + if (basename === '..' || basename === '.' || basename !== name) + throw new Error(`${option} option must not contain a path, found "${name}".`); + } + else { // if (option === 'dir' || option === 'template') { + // assert that dir or template are relative to tmpDir + if (path.isAbsolute(name) && !name.startsWith(tmpDir)) { + throw new Error(`${option} option must be relative to "${tmpDir}", found "${name}".`); + } + let resolvedPath = _resolvePath(name, tmpDir); + if (!resolvedPath.startsWith(tmpDir)) + throw new Error(`${option} option must be relative to "${tmpDir}", found "${resolvedPath}".`); + } + } + + /** + * Helper for testing against EBADF to compensate changes made to Node 7.x under Windows. + * + * @private + */ + function _isEBADF(error) { + return _isExpectedError(error, -EBADF, 'EBADF'); + } + + /** + * Helper for testing against ENOENT to compensate changes made to Node 7.x under Windows. + * + * @private + */ + function _isENOENT(error) { + return _isExpectedError(error, -ENOENT, 'ENOENT'); + } + + /** + * Helper to determine whether the expected error code matches the actual code and errno, + * which will differ between the supported node versions. + * + * - Node >= 7.0: + * error.code {string} + * error.errno {number} any numerical value will be negated + * + * CAVEAT + * + * On windows, the errno for EBADF is -4083 but os.constants.errno.EBADF is different and we must assume that ENOENT + * is no different here. + * + * @param {SystemError} error + * @param {number} errno + * @param {string} code + * @private + */ + function _isExpectedError(error, errno, code) { + return IS_WIN32 ? error.code === code : error.code === code && error.errno === errno; + } + + /** + * Sets the graceful cleanup. + * + * If graceful cleanup is set, tmp will remove all controlled temporary objects on process exit, otherwise the + * temporary objects will remain in place, waiting to be cleaned up on system restart or otherwise scheduled temporary + * object removals. + */ + function setGracefulCleanup() { + _gracefulCleanup = true; + } + + /** + * Returns the currently configured tmp dir from os.tmpdir(). + * + * @private + * @param {?Options} options + * @returns {string} the currently configured tmp dir + */ + function _getTmpDir(options) { + return path.resolve(_sanitizeName(options && options.tmpdir || os.tmpdir())); + } + + // Install process exit listener + process.addListener(EXIT, _garbageCollector); + + /** + * Configuration options. + * + * @typedef {Object} Options + * @property {?boolean} keep the temporary object (file or dir) will not be garbage collected + * @property {?number} tries the number of tries before give up the name generation + * @property (?int) mode the access mode, defaults are 0o700 for directories and 0o600 for files + * @property {?string} template the "mkstemp" like filename template + * @property {?string} name fixed name relative to tmpdir or the specified dir option + * @property {?string} dir tmp directory relative to the root tmp directory in use + * @property {?string} prefix prefix for the generated name + * @property {?string} postfix postfix for the generated name + * @property {?string} tmpdir the root tmp directory which overrides the os tmpdir + * @property {?boolean} unsafeCleanup recursively removes the created temporary directory, even when it's not empty + * @property {?boolean} detachDescriptor detaches the file descriptor, caller is responsible for closing the file, tmp will no longer try closing the file during garbage collection + * @property {?boolean} discardDescriptor discards the file descriptor (closes file, fd is -1), tmp will no longer try closing the file during garbage collection + */ + + /** + * @typedef {Object} FileSyncObject + * @property {string} name the name of the file + * @property {string} fd the file descriptor or -1 if the fd has been discarded + * @property {fileCallback} removeCallback the callback function to remove the file + */ + + /** + * @typedef {Object} DirSyncObject + * @property {string} name the name of the directory + * @property {fileCallback} removeCallback the callback function to remove the directory + */ + + /** + * @callback tmpNameCallback + * @param {?Error} err the error object if anything goes wrong + * @param {string} name the temporary file name + */ + + /** + * @callback fileCallback + * @param {?Error} err the error object if anything goes wrong + * @param {string} name the temporary file name + * @param {number} fd the file descriptor or -1 if the fd had been discarded + * @param {cleanupCallback} fn the cleanup callback function + */ + + /** + * @callback fileCallbackSync + * @param {?Error} err the error object if anything goes wrong + * @param {string} name the temporary file name + * @param {number} fd the file descriptor or -1 if the fd had been discarded + * @param {cleanupCallbackSync} fn the cleanup callback function + */ + + /** + * @callback dirCallback + * @param {?Error} err the error object if anything goes wrong + * @param {string} name the temporary file name + * @param {cleanupCallback} fn the cleanup callback function + */ + + /** + * @callback dirCallbackSync + * @param {?Error} err the error object if anything goes wrong + * @param {string} name the temporary file name + * @param {cleanupCallbackSync} fn the cleanup callback function + */ + + /** + * Removes the temporary created file or directory. + * + * @callback cleanupCallback + * @param {simpleCallback} [next] function to call whenever the tmp object needs to be removed + */ + + /** + * Removes the temporary created file or directory. + * + * @callback cleanupCallbackSync + */ + + /** + * Callback function for function composition. + * @see {@link https://github.com/raszi/node-tmp/issues/57|raszi/node-tmp#57} + * + * @callback simpleCallback + */ + + // exporting all the needed methods + + // evaluate _getTmpDir() lazily, mainly for simplifying testing but it also will + // allow users to reconfigure the temporary directory + Object.defineProperty(module.exports, 'tmpdir', { + enumerable: true, + configurable: false, + get: function () { + return _getTmpDir(); + } + }); + + module.exports.dir = dir; + module.exports.dirSync = dirSync; + + module.exports.file = file; + module.exports.fileSync = fileSync; + + module.exports.tmpName = tmpName; + module.exports.tmpNameSync = tmpNameSync; + + module.exports.setGracefulCleanup = setGracefulCleanup; +} (tmp)); + +var tmpExports = tmp.exports; + +(function (module) { + + const { promisify } = require$$0$9; + const tmp = tmpExports; + + // file + module.exports.fileSync = tmp.fileSync; + const fileWithOptions = promisify((options, cb) => + tmp.file(options, (err, path, fd, cleanup) => + err ? cb(err) : cb(undefined, { path, fd, cleanup: promisify(cleanup) }) + ) + ); + module.exports.file = async (options) => fileWithOptions(options); + + module.exports.withFile = async function withFile(fn, options) { + const { path, fd, cleanup } = await module.exports.file(options); + try { + return await fn({ path, fd }); + } finally { + await cleanup(); + } + }; + + + // directory + module.exports.dirSync = tmp.dirSync; + const dirWithOptions = promisify((options, cb) => + tmp.dir(options, (err, path, cleanup) => + err ? cb(err) : cb(undefined, { path, cleanup: promisify(cleanup) }) + ) + ); + module.exports.dir = async (options) => dirWithOptions(options); + + module.exports.withDir = async function withDir(fn, options) { + const { path, cleanup } = await module.exports.dir(options); + try { + return await fn({ path }); + } finally { + await cleanup(); + } + }; + + + // name generation + module.exports.tmpNameSync = tmp.tmpNameSync; + module.exports.tmpName = promisify(tmp.tmpName); + + module.exports.tmpdir = tmp.tmpdir; + + module.exports.setGracefulCleanup = tmp.setGracefulCleanup; +} (tmpPromise)); + +var tmpPromiseExports = tmpPromise.exports; + +/** + * Uploads a spec to the API registry for usage in ReadMe + * + * @param {String} spec path to a bundled/validated spec file + * @returns {String} a UUID in the API registry + */ +async function streamSpecToRegistry(spec) { + const spinner = ora({ text: 'Staging your API definition for upload...', ...oraOptions() }).start(); + // Create a temporary file to write the bundled spec to, + // which we will then stream into the form data body + const { path } = await tmpPromiseExports.file({ prefix: 'rdme-openapi-', postfix: '.json' }); + debug(`creating temporary file at ${path}`); + await fs$i.writeFileSync(path, spec); + const stream = fs$i.createReadStream(path); + debug('file and stream created, streaming into form data payload'); + const formData = new FormData(); + formData.append('spec', { + type: 'application/json', + name: 'openapi.json', + [Symbol.toStringTag]: 'File', + stream() { + return stream; + }, + }); + const options = { + body: formData, + headers: { + Accept: 'application/json', + }, + method: 'POST', + }; + return readmeAPIFetch('/api/v1/api-registry', options) + .then(handleRes) + .then(body => { + spinner.stop(); + return body.registryUUID; + }) + .catch(e => { + spinner.fail(); + throw e; + }); +} + +class OpenAPICommand extends Command { + constructor() { + super(); + this.command = 'openapi'; + this.usage = 'openapi [file|url] [options]'; + this.description = 'Upload, or resync, your OpenAPI/Swagger definition to ReadMe.'; + this.cmdCategory = CommandCategories.APIS; + this.hiddenArgs = ['spec']; + this.args = [ + this.getKeyArg(), + { + name: 'id', + type: String, + description: "Unique identifier for your API definition. Use this if you're re-uploading an existing API definition.", + }, + this.getVersionArg(), + { + name: 'spec', + type: String, + defaultOption: true, + }, + this.getWorkingDirArg(), + { + name: 'useSpecVersion', + type: Boolean, + description: 'Uses the version listed in the `info.version` field in the API definition for the project version parameter.', + }, + { + name: 'raw', + type: Boolean, + description: 'Return the command results as a JSON object instead of a pretty output.', + }, + this.getGitHubArg(), + { + name: 'create', + type: Boolean, + description: 'Bypasses the create/update prompt and creates a new API definition.', + }, + { + name: 'update', + type: Boolean, + description: "Automatically update an existing API definition in ReadMe if it's the only one associated with the current version.", + }, + this.getTitleArg(), + { + name: 'dryRun', + type: Boolean, + description: 'Runs the command without creating/updating any API Definitions in ReadMe. Useful for debugging.', + }, + ]; + } + async run(opts) { + await super.run(opts); + const { dryRun, key, id, spec, create, raw, title, useSpecVersion, version, workingDirectory, update } = opts; + let selectedVersion = version; + let isUpdate; + const spinner = ora({ ...oraOptions() }); + /** + * The `version` and `update` parameters are not typically ones we'd want to include + * in GitHub Actions workflow files, so we're going to collect them in this object. + */ + const ignoredGHAParameters = { version: undefined, update: undefined }; + if (dryRun) { + Command.warn('🎭 dry run option detected! No API definitions will be created or updated in ReadMe.'); + } + if (create && update) { + throw new Error('The `--create` and `--update` options cannot be used simultaneously. Please use one or the other!'); + } + if (workingDirectory) { + const previousWorkingDirectory = process.cwd(); + process.chdir(workingDirectory); + Command.debug(`switching working directory from ${previousWorkingDirectory} to ${process.cwd()}`); + } + if (version && id) { + Command.warn("We'll be using the version associated with the `--id` option, so the `--version` option will be ignored."); + } + if (create && id) { + Command.warn("We'll be using the `--create` option, so the `--id` parameter will be ignored."); + } + if (update && id) { + Command.warn("We'll be updating the API definition associated with the `--id` parameter, so the `--update` parameter will be ignored."); + } + // Reason we're hardcoding in command here is because `swagger` command + // relies on this and we don't want to use `swagger` in this function + const { preparedSpec, specFileType, specPath, specType, specVersion } = await prepareOas(spec, 'openapi', { + title, + }); + if (useSpecVersion) { + Command.info(`Using the version specified in your API definition for your ReadMe project version (${specVersion})`); + selectedVersion = specVersion; + } + if (create || !id) { + selectedVersion = await getProjectVersion(selectedVersion, key); + } + Command.debug(`selectedVersion: ${selectedVersion}`); + const success = async (data) => { + const message = !isUpdate + ? `You've successfully uploaded a new ${specType} file to your ReadMe project!` + : `You've successfully updated an existing ${specType} file on your ReadMe project!`; + const body = await handleRes(data, false); + const output = { + commandType: isUpdate ? 'update' : 'create', + docs: data.headers.get('location'), + // eslint-disable-next-line no-underscore-dangle + id: body._id, + specPath, + specType, + version: selectedVersion, + }; + const prettyOutput = [ + message, + '', + `\t${chalk$5.green(output.docs)}`, + '', + `To update your ${specType} definition, run the following:`, + '', + `\t${chalk$5.green(`rdme openapi ${specPath} --key=<key> --id=${output.id}`)}`, + ].join('\n'); + return Promise.resolve(raw ? JSON.stringify(output, null, 2) : prettyOutput).then(msg => createGHA(msg, this.command, this.args, { + ...opts, + spec: specPath, + // eslint-disable-next-line no-underscore-dangle + id: body._id, + version: selectedVersion, + ...ignoredGHAParameters, + })); + }; + const error = (res) => { + return handleRes(res).catch(err => { + // If we receive an APIError, no changes needed! Throw it as is. + if (err.name === 'APIError') { + throw err; + } + // If we receive certain text responses, it's likely a 5xx error from our server. + if (typeof err === 'string' && + (err.includes('<title>Application Error') || // Heroku error + err.includes('520: Web server is returning an unknown error')) // Cloudflare error + ) { + throw new Error("We're sorry, your upload request timed out. Please try again or split your file up into smaller chunks."); + } + // As a fallback, we throw a more generic error. + throw new Error(`Yikes, something went wrong! Please try uploading your spec again and if the problem persists, get in touch with our support team at ${chalk$5.underline('support@readme.io')}.`); + }); + }; + const registryUUID = await streamSpecToRegistry(preparedSpec); + const options = { + headers: cleanHeaders(key, new Headers$2({ + Accept: 'application/json', + 'Content-Type': 'application/json', + 'x-readme-version': selectedVersion, + })), + body: JSON.stringify({ registryUUID }), + }; + function createSpec() { + if (dryRun) { + return `🎭 dry run! The API Definition located at ${specPath} will be created for this project version: ${selectedVersion}`; + } + options.method = 'post'; + spinner.start('Creating your API docs in ReadMe...'); + return readmeAPIFetch('/api/v1/api-specification', options, { + filePath: specPath, + fileType: specFileType, + }).then(res => { + if (res.ok) { + spinner.succeed(`${spinner.text} done! 🦉`); + return success(res); + } + spinner.fail(); + return error(res); + }); + } + function updateSpec(specId) { + if (dryRun) { + return `🎭 dry run! The API Definition located at ${specPath} will update this API Definition ID: ${specId}`; + } + isUpdate = true; + options.method = 'put'; + spinner.start('Updating your API docs in ReadMe...'); + return readmeAPIFetch(`/api/v1/api-specification/${specId}`, options, { + filePath: specPath, + fileType: specFileType, + }).then(res => { + if (res.ok) { + spinner.succeed(`${spinner.text} done! 🦉`); + return success(res); + } + spinner.fail(); + return error(res); + }); + } + /* + Create a new OAS file in Readme: + - Enter flow if user does not pass an id as cli arg + - Check to see if any existing files exist with a specific version + - If none exist, default to creating a new instance of a spec + - If found, prompt user to either create a new spec or update an existing one + */ + function getSpecs(url) { + return readmeAPIFetch(url, { + method: 'get', + headers: cleanHeaders(key, new Headers$2({ + 'x-readme-version': selectedVersion, + })), + }); + } + if (create) { + ignoredGHAParameters.id = undefined; + delete ignoredGHAParameters.version; + return createSpec(); + } + if (!id) { + Command.debug('no id parameter, retrieving list of API specs'); + const apiSettings = await getSpecs('/api/v1/api-specification'); + const totalPages = Math.ceil(parseInt(apiSettings.headers.get('x-total-count'), 10) / 10); + const parsedDocs = parse$1(apiSettings.headers.get('link')); + Command.debug(`total pages: ${totalPages}`); + Command.debug(`pagination result: ${JSON.stringify(parsedDocs)}`); + const apiSettingsBody = await handleRes(apiSettings); + if (!apiSettingsBody.length) + return createSpec(); + if (update) { + if (apiSettingsBody.length > 1) { + throw new Error(`The \`--update\` option cannot be used when there's more than one API definition available (found ${apiSettingsBody.length}).`); + } + const { _id: specId } = apiSettingsBody[0]; + return updateSpec(specId); + } + // @todo: figure out how to add a stricter type here, see: + // https://github.com/readmeio/rdme/pull/570#discussion_r949715913 + const { option } = await promptTerminal(createOasPrompt(apiSettingsBody, parsedDocs, totalPages, getSpecs)); + Command.debug(`selection result: ${option}`); + return option === 'create' ? createSpec() : updateSpec(option); + } + /* + Update an existing OAS file in Readme: + - Enter flow if user passes an id as cli arg + */ + return updateSpec(id); + } +} + +var pluralize$1 = {exports: {}}; + +/* global define */ + +(function (module, exports) { + (function (root, pluralize) { + /* istanbul ignore else */ + if (typeof commonjsRequire === 'function' && 'object' === 'object' && 'object' === 'object') { + // Node. + module.exports = pluralize(); + } else { + // Browser global. + root.pluralize = pluralize(); + } + })(commonjsGlobal, function () { + // Rule storage - pluralize and singularize need to be run sequentially, + // while other rules can be optimized using an object for instant lookups. + var pluralRules = []; + var singularRules = []; + var uncountables = {}; + var irregularPlurals = {}; + var irregularSingles = {}; + + /** + * Sanitize a pluralization rule to a usable regular expression. + * + * @param {(RegExp|string)} rule + * @return {RegExp} + */ + function sanitizeRule (rule) { + if (typeof rule === 'string') { + return new RegExp('^' + rule + '$', 'i'); + } + + return rule; + } + + /** + * Pass in a word token to produce a function that can replicate the case on + * another word. + * + * @param {string} word + * @param {string} token + * @return {Function} + */ + function restoreCase (word, token) { + // Tokens are an exact match. + if (word === token) return token; + + // Lower cased words. E.g. "hello". + if (word === word.toLowerCase()) return token.toLowerCase(); + + // Upper cased words. E.g. "WHISKY". + if (word === word.toUpperCase()) return token.toUpperCase(); + + // Title cased words. E.g. "Title". + if (word[0] === word[0].toUpperCase()) { + return token.charAt(0).toUpperCase() + token.substr(1).toLowerCase(); + } + + // Lower cased words. E.g. "test". + return token.toLowerCase(); + } + + /** + * Interpolate a regexp string. + * + * @param {string} str + * @param {Array} args + * @return {string} + */ + function interpolate (str, args) { + return str.replace(/\$(\d{1,2})/g, function (match, index) { + return args[index] || ''; + }); + } + + /** + * Replace a word using a rule. + * + * @param {string} word + * @param {Array} rule + * @return {string} + */ + function replace (word, rule) { + return word.replace(rule[0], function (match, index) { + var result = interpolate(rule[1], arguments); + + if (match === '') { + return restoreCase(word[index - 1], result); + } + + return restoreCase(match, result); + }); + } + + /** + * Sanitize a word by passing in the word and sanitization rules. + * + * @param {string} token + * @param {string} word + * @param {Array} rules + * @return {string} + */ + function sanitizeWord (token, word, rules) { + // Empty string or doesn't need fixing. + if (!token.length || uncountables.hasOwnProperty(token)) { + return word; + } + + var len = rules.length; + + // Iterate over the sanitization rules and use the first one to match. + while (len--) { + var rule = rules[len]; + + if (rule[0].test(word)) return replace(word, rule); + } + + return word; + } + + /** + * Replace a word with the updated word. + * + * @param {Object} replaceMap + * @param {Object} keepMap + * @param {Array} rules + * @return {Function} + */ + function replaceWord (replaceMap, keepMap, rules) { + return function (word) { + // Get the correct token and case restoration functions. + var token = word.toLowerCase(); + + // Check against the keep object map. + if (keepMap.hasOwnProperty(token)) { + return restoreCase(word, token); + } + + // Check against the replacement map for a direct word replacement. + if (replaceMap.hasOwnProperty(token)) { + return restoreCase(word, replaceMap[token]); + } + + // Run all the rules against the word. + return sanitizeWord(token, word, rules); + }; + } + + /** + * Check if a word is part of the map. + */ + function checkWord (replaceMap, keepMap, rules, bool) { + return function (word) { + var token = word.toLowerCase(); + + if (keepMap.hasOwnProperty(token)) return true; + if (replaceMap.hasOwnProperty(token)) return false; + + return sanitizeWord(token, token, rules) === token; + }; + } + + /** + * Pluralize or singularize a word based on the passed in count. + * + * @param {string} word The word to pluralize + * @param {number} count How many of the word exist + * @param {boolean} inclusive Whether to prefix with the number (e.g. 3 ducks) + * @return {string} + */ + function pluralize (word, count, inclusive) { + var pluralized = count === 1 + ? pluralize.singular(word) : pluralize.plural(word); + + return (inclusive ? count + ' ' : '') + pluralized; + } + + /** + * Pluralize a word. + * + * @type {Function} + */ + pluralize.plural = replaceWord( + irregularSingles, irregularPlurals, pluralRules + ); + + /** + * Check if a word is plural. + * + * @type {Function} + */ + pluralize.isPlural = checkWord( + irregularSingles, irregularPlurals, pluralRules + ); + + /** + * Singularize a word. + * + * @type {Function} + */ + pluralize.singular = replaceWord( + irregularPlurals, irregularSingles, singularRules + ); + + /** + * Check if a word is singular. + * + * @type {Function} + */ + pluralize.isSingular = checkWord( + irregularPlurals, irregularSingles, singularRules + ); + + /** + * Add a pluralization rule to the collection. + * + * @param {(string|RegExp)} rule + * @param {string} replacement + */ + pluralize.addPluralRule = function (rule, replacement) { + pluralRules.push([sanitizeRule(rule), replacement]); + }; + + /** + * Add a singularization rule to the collection. + * + * @param {(string|RegExp)} rule + * @param {string} replacement + */ + pluralize.addSingularRule = function (rule, replacement) { + singularRules.push([sanitizeRule(rule), replacement]); + }; + + /** + * Add an uncountable word rule. + * + * @param {(string|RegExp)} word + */ + pluralize.addUncountableRule = function (word) { + if (typeof word === 'string') { + uncountables[word.toLowerCase()] = true; + return; + } + + // Set singular and plural references for the word. + pluralize.addPluralRule(word, '$0'); + pluralize.addSingularRule(word, '$0'); + }; + + /** + * Add an irregular word definition. + * + * @param {string} single + * @param {string} plural + */ + pluralize.addIrregularRule = function (single, plural) { + plural = plural.toLowerCase(); + single = single.toLowerCase(); + + irregularSingles[single] = plural; + irregularPlurals[plural] = single; + }; + + /** + * Irregular rules. + */ + [ + // Pronouns. + ['I', 'we'], + ['me', 'us'], + ['he', 'they'], + ['she', 'they'], + ['them', 'them'], + ['myself', 'ourselves'], + ['yourself', 'yourselves'], + ['itself', 'themselves'], + ['herself', 'themselves'], + ['himself', 'themselves'], + ['themself', 'themselves'], + ['is', 'are'], + ['was', 'were'], + ['has', 'have'], + ['this', 'these'], + ['that', 'those'], + // Words ending in with a consonant and `o`. + ['echo', 'echoes'], + ['dingo', 'dingoes'], + ['volcano', 'volcanoes'], + ['tornado', 'tornadoes'], + ['torpedo', 'torpedoes'], + // Ends with `us`. + ['genus', 'genera'], + ['viscus', 'viscera'], + // Ends with `ma`. + ['stigma', 'stigmata'], + ['stoma', 'stomata'], + ['dogma', 'dogmata'], + ['lemma', 'lemmata'], + ['schema', 'schemata'], + ['anathema', 'anathemata'], + // Other irregular rules. + ['ox', 'oxen'], + ['axe', 'axes'], + ['die', 'dice'], + ['yes', 'yeses'], + ['foot', 'feet'], + ['eave', 'eaves'], + ['goose', 'geese'], + ['tooth', 'teeth'], + ['quiz', 'quizzes'], + ['human', 'humans'], + ['proof', 'proofs'], + ['carve', 'carves'], + ['valve', 'valves'], + ['looey', 'looies'], + ['thief', 'thieves'], + ['groove', 'grooves'], + ['pickaxe', 'pickaxes'], + ['passerby', 'passersby'] + ].forEach(function (rule) { + return pluralize.addIrregularRule(rule[0], rule[1]); + }); + + /** + * Pluralization rules. + */ + [ + [/s?$/i, 's'], + [/[^\u0000-\u007F]$/i, '$0'], + [/([^aeiou]ese)$/i, '$1'], + [/(ax|test)is$/i, '$1es'], + [/(alias|[^aou]us|t[lm]as|gas|ris)$/i, '$1es'], + [/(e[mn]u)s?$/i, '$1s'], + [/([^l]ias|[aeiou]las|[ejzr]as|[iu]am)$/i, '$1'], + [/(alumn|syllab|vir|radi|nucle|fung|cact|stimul|termin|bacill|foc|uter|loc|strat)(?:us|i)$/i, '$1i'], + [/(alumn|alg|vertebr)(?:a|ae)$/i, '$1ae'], + [/(seraph|cherub)(?:im)?$/i, '$1im'], + [/(her|at|gr)o$/i, '$1oes'], + [/(agend|addend|millenni|dat|extrem|bacteri|desiderat|strat|candelabr|errat|ov|symposi|curricul|automat|quor)(?:a|um)$/i, '$1a'], + [/(apheli|hyperbat|periheli|asyndet|noumen|phenomen|criteri|organ|prolegomen|hedr|automat)(?:a|on)$/i, '$1a'], + [/sis$/i, 'ses'], + [/(?:(kni|wi|li)fe|(ar|l|ea|eo|oa|hoo)f)$/i, '$1$2ves'], + [/([^aeiouy]|qu)y$/i, '$1ies'], + [/([^ch][ieo][ln])ey$/i, '$1ies'], + [/(x|ch|ss|sh|zz)$/i, '$1es'], + [/(matr|cod|mur|sil|vert|ind|append)(?:ix|ex)$/i, '$1ices'], + [/\b((?:tit)?m|l)(?:ice|ouse)$/i, '$1ice'], + [/(pe)(?:rson|ople)$/i, '$1ople'], + [/(child)(?:ren)?$/i, '$1ren'], + [/eaux$/i, '$0'], + [/m[ae]n$/i, 'men'], + ['thou', 'you'] + ].forEach(function (rule) { + return pluralize.addPluralRule(rule[0], rule[1]); + }); + + /** + * Singularization rules. + */ + [ + [/s$/i, ''], + [/(ss)$/i, '$1'], + [/(wi|kni|(?:after|half|high|low|mid|non|night|[^\w]|^)li)ves$/i, '$1fe'], + [/(ar|(?:wo|[ae])l|[eo][ao])ves$/i, '$1f'], + [/ies$/i, 'y'], + [/\b([pl]|zomb|(?:neck|cross)?t|coll|faer|food|gen|goon|group|lass|talk|goal|cut)ies$/i, '$1ie'], + [/\b(mon|smil)ies$/i, '$1ey'], + [/\b((?:tit)?m|l)ice$/i, '$1ouse'], + [/(seraph|cherub)im$/i, '$1'], + [/(x|ch|ss|sh|zz|tto|go|cho|alias|[^aou]us|t[lm]as|gas|(?:her|at|gr)o|[aeiou]ris)(?:es)?$/i, '$1'], + [/(analy|diagno|parenthe|progno|synop|the|empha|cri|ne)(?:sis|ses)$/i, '$1sis'], + [/(movie|twelve|abuse|e[mn]u)s$/i, '$1'], + [/(test)(?:is|es)$/i, '$1is'], + [/(alumn|syllab|vir|radi|nucle|fung|cact|stimul|termin|bacill|foc|uter|loc|strat)(?:us|i)$/i, '$1us'], + [/(agend|addend|millenni|dat|extrem|bacteri|desiderat|strat|candelabr|errat|ov|symposi|curricul|quor)a$/i, '$1um'], + [/(apheli|hyperbat|periheli|asyndet|noumen|phenomen|criteri|organ|prolegomen|hedr|automat)a$/i, '$1on'], + [/(alumn|alg|vertebr)ae$/i, '$1a'], + [/(cod|mur|sil|vert|ind)ices$/i, '$1ex'], + [/(matr|append)ices$/i, '$1ix'], + [/(pe)(rson|ople)$/i, '$1rson'], + [/(child)ren$/i, '$1'], + [/(eau)x?$/i, '$1'], + [/men$/i, 'man'] + ].forEach(function (rule) { + return pluralize.addSingularRule(rule[0], rule[1]); + }); + + /** + * Uncountable rules. + */ + [ + // Singular words with no plurals. + 'adulthood', + 'advice', + 'agenda', + 'aid', + 'aircraft', + 'alcohol', + 'ammo', + 'analytics', + 'anime', + 'athletics', + 'audio', + 'bison', + 'blood', + 'bream', + 'buffalo', + 'butter', + 'carp', + 'cash', + 'chassis', + 'chess', + 'clothing', + 'cod', + 'commerce', + 'cooperation', + 'corps', + 'debris', + 'diabetes', + 'digestion', + 'elk', + 'energy', + 'equipment', + 'excretion', + 'expertise', + 'firmware', + 'flounder', + 'fun', + 'gallows', + 'garbage', + 'graffiti', + 'hardware', + 'headquarters', + 'health', + 'herpes', + 'highjinks', + 'homework', + 'housework', + 'information', + 'jeans', + 'justice', + 'kudos', + 'labour', + 'literature', + 'machinery', + 'mackerel', + 'mail', + 'media', + 'mews', + 'moose', + 'music', + 'mud', + 'manga', + 'news', + 'only', + 'personnel', + 'pike', + 'plankton', + 'pliers', + 'police', + 'pollution', + 'premises', + 'rain', + 'research', + 'rice', + 'salmon', + 'scissors', + 'series', + 'sewage', + 'shambles', + 'shrimp', + 'software', + 'species', + 'staff', + 'swine', + 'tennis', + 'traffic', + 'transportation', + 'trout', + 'tuna', + 'wealth', + 'welfare', + 'whiting', + 'wildebeest', + 'wildlife', + 'you', + /pok[eé]mon$/i, + // Regexes. + /[^aeiou]ese$/i, // "chinese", "japanese" + /deer$/i, // "deer", "reindeer" + /fish$/i, // "fish", "blowfish", "angelfish" + /measles$/i, + /o[iu]s$/i, // "carnivorous" + /pox$/i, // "chickpox", "smallpox" + /sheep$/i + ].forEach(pluralize.addUncountableRule); + + return pluralize; + }); +} (pluralize$1)); + +var pluralizeExports = pluralize$1.exports; +var pluralize = /*@__PURE__*/getDefaultExportFromCjs(pluralizeExports); + +var src$2 = {}; + +var createStream$1 = {}; + +var alignTableData$1 = {}; + +var alignString$1 = {}; + +var stringWidth$1 = {exports: {}}; + +var emojiRegex$1 = function () { + // https://mths.be/emoji + return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83C\uDFF4\u200D\u2620)\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF4\uD83C\uDDF2|\uD83C\uDDF6\uD83C\uDDE6|[#\*0-9]\uFE0F\u20E3|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g; +}; + +const stripAnsi = stripAnsi$4; +const isFullwidthCodePoint$1 = isFullwidthCodePointExports; +const emojiRegex = emojiRegex$1; + +const stringWidth = string => { + if (typeof string !== 'string' || string.length === 0) { + return 0; + } + + string = stripAnsi(string); + + if (string.length === 0) { + return 0; + } + + string = string.replace(emojiRegex(), ' '); + + let width = 0; + + for (let i = 0; i < string.length; i++) { + const code = string.codePointAt(i); + + // Ignore control characters + if (code <= 0x1F || (code >= 0x7F && code <= 0x9F)) { + continue; + } + + // Ignore combining characters + if (code >= 0x300 && code <= 0x36F) { + continue; + } + + // Surrogates + if (code > 0xFFFF) { + i++; + } + + width += isFullwidthCodePoint$1(code) ? 2 : 1; + } + + return width; +}; + +stringWidth$1.exports = stringWidth; +// TODO: remove this in the next major version +stringWidth$1.exports.default = stringWidth; + +var stringWidthExports = stringWidth$1.exports; + +var utils$1 = {}; + +const regex = '[\uD800-\uDBFF][\uDC00-\uDFFF]'; + +const astralRegex$1 = options => options && options.exact ? new RegExp(`^${regex}$`) : new RegExp(regex, 'g'); + +var astralRegex_1 = astralRegex$1; + +var ansiStyles$3 = {exports: {}}; + +var colorName$1; +var hasRequiredColorName$1; + +function requireColorName$1 () { + if (hasRequiredColorName$1) return colorName$1; + hasRequiredColorName$1 = 1; + + colorName$1 = { + "aliceblue": [240, 248, 255], + "antiquewhite": [250, 235, 215], + "aqua": [0, 255, 255], + "aquamarine": [127, 255, 212], + "azure": [240, 255, 255], + "beige": [245, 245, 220], + "bisque": [255, 228, 196], + "black": [0, 0, 0], + "blanchedalmond": [255, 235, 205], + "blue": [0, 0, 255], + "blueviolet": [138, 43, 226], + "brown": [165, 42, 42], + "burlywood": [222, 184, 135], + "cadetblue": [95, 158, 160], + "chartreuse": [127, 255, 0], + "chocolate": [210, 105, 30], + "coral": [255, 127, 80], + "cornflowerblue": [100, 149, 237], + "cornsilk": [255, 248, 220], + "crimson": [220, 20, 60], + "cyan": [0, 255, 255], + "darkblue": [0, 0, 139], + "darkcyan": [0, 139, 139], + "darkgoldenrod": [184, 134, 11], + "darkgray": [169, 169, 169], + "darkgreen": [0, 100, 0], + "darkgrey": [169, 169, 169], + "darkkhaki": [189, 183, 107], + "darkmagenta": [139, 0, 139], + "darkolivegreen": [85, 107, 47], + "darkorange": [255, 140, 0], + "darkorchid": [153, 50, 204], + "darkred": [139, 0, 0], + "darksalmon": [233, 150, 122], + "darkseagreen": [143, 188, 143], + "darkslateblue": [72, 61, 139], + "darkslategray": [47, 79, 79], + "darkslategrey": [47, 79, 79], + "darkturquoise": [0, 206, 209], + "darkviolet": [148, 0, 211], + "deeppink": [255, 20, 147], + "deepskyblue": [0, 191, 255], + "dimgray": [105, 105, 105], + "dimgrey": [105, 105, 105], + "dodgerblue": [30, 144, 255], + "firebrick": [178, 34, 34], + "floralwhite": [255, 250, 240], + "forestgreen": [34, 139, 34], + "fuchsia": [255, 0, 255], + "gainsboro": [220, 220, 220], + "ghostwhite": [248, 248, 255], + "gold": [255, 215, 0], + "goldenrod": [218, 165, 32], + "gray": [128, 128, 128], + "green": [0, 128, 0], + "greenyellow": [173, 255, 47], + "grey": [128, 128, 128], + "honeydew": [240, 255, 240], + "hotpink": [255, 105, 180], + "indianred": [205, 92, 92], + "indigo": [75, 0, 130], + "ivory": [255, 255, 240], + "khaki": [240, 230, 140], + "lavender": [230, 230, 250], + "lavenderblush": [255, 240, 245], + "lawngreen": [124, 252, 0], + "lemonchiffon": [255, 250, 205], + "lightblue": [173, 216, 230], + "lightcoral": [240, 128, 128], + "lightcyan": [224, 255, 255], + "lightgoldenrodyellow": [250, 250, 210], + "lightgray": [211, 211, 211], + "lightgreen": [144, 238, 144], + "lightgrey": [211, 211, 211], + "lightpink": [255, 182, 193], + "lightsalmon": [255, 160, 122], + "lightseagreen": [32, 178, 170], + "lightskyblue": [135, 206, 250], + "lightslategray": [119, 136, 153], + "lightslategrey": [119, 136, 153], + "lightsteelblue": [176, 196, 222], + "lightyellow": [255, 255, 224], + "lime": [0, 255, 0], + "limegreen": [50, 205, 50], + "linen": [250, 240, 230], + "magenta": [255, 0, 255], + "maroon": [128, 0, 0], + "mediumaquamarine": [102, 205, 170], + "mediumblue": [0, 0, 205], + "mediumorchid": [186, 85, 211], + "mediumpurple": [147, 112, 219], + "mediumseagreen": [60, 179, 113], + "mediumslateblue": [123, 104, 238], + "mediumspringgreen": [0, 250, 154], + "mediumturquoise": [72, 209, 204], + "mediumvioletred": [199, 21, 133], + "midnightblue": [25, 25, 112], + "mintcream": [245, 255, 250], + "mistyrose": [255, 228, 225], + "moccasin": [255, 228, 181], + "navajowhite": [255, 222, 173], + "navy": [0, 0, 128], + "oldlace": [253, 245, 230], + "olive": [128, 128, 0], + "olivedrab": [107, 142, 35], + "orange": [255, 165, 0], + "orangered": [255, 69, 0], + "orchid": [218, 112, 214], + "palegoldenrod": [238, 232, 170], + "palegreen": [152, 251, 152], + "paleturquoise": [175, 238, 238], + "palevioletred": [219, 112, 147], + "papayawhip": [255, 239, 213], + "peachpuff": [255, 218, 185], + "peru": [205, 133, 63], + "pink": [255, 192, 203], + "plum": [221, 160, 221], + "powderblue": [176, 224, 230], + "purple": [128, 0, 128], + "rebeccapurple": [102, 51, 153], + "red": [255, 0, 0], + "rosybrown": [188, 143, 143], + "royalblue": [65, 105, 225], + "saddlebrown": [139, 69, 19], + "salmon": [250, 128, 114], + "sandybrown": [244, 164, 96], + "seagreen": [46, 139, 87], + "seashell": [255, 245, 238], + "sienna": [160, 82, 45], + "silver": [192, 192, 192], + "skyblue": [135, 206, 235], + "slateblue": [106, 90, 205], + "slategray": [112, 128, 144], + "slategrey": [112, 128, 144], + "snow": [255, 250, 250], + "springgreen": [0, 255, 127], + "steelblue": [70, 130, 180], + "tan": [210, 180, 140], + "teal": [0, 128, 128], + "thistle": [216, 191, 216], + "tomato": [255, 99, 71], + "turquoise": [64, 224, 208], + "violet": [238, 130, 238], + "wheat": [245, 222, 179], + "white": [255, 255, 255], + "whitesmoke": [245, 245, 245], + "yellow": [255, 255, 0], + "yellowgreen": [154, 205, 50] + }; + return colorName$1; +} + +/* MIT license */ + +var conversions$2; +var hasRequiredConversions$1; + +function requireConversions$1 () { + if (hasRequiredConversions$1) return conversions$2; + hasRequiredConversions$1 = 1; + /* eslint-disable no-mixed-operators */ + const cssKeywords = requireColorName$1(); + + // NOTE: conversions should only return primitive values (i.e. arrays, or + // values that give correct `typeof` results). + // do not use box values types (i.e. Number(), String(), etc.) + + const reverseKeywords = {}; + for (const key of Object.keys(cssKeywords)) { + reverseKeywords[cssKeywords[key]] = key; + } + + const convert = { + rgb: {channels: 3, labels: 'rgb'}, + hsl: {channels: 3, labels: 'hsl'}, + hsv: {channels: 3, labels: 'hsv'}, + hwb: {channels: 3, labels: 'hwb'}, + cmyk: {channels: 4, labels: 'cmyk'}, + xyz: {channels: 3, labels: 'xyz'}, + lab: {channels: 3, labels: 'lab'}, + lch: {channels: 3, labels: 'lch'}, + hex: {channels: 1, labels: ['hex']}, + keyword: {channels: 1, labels: ['keyword']}, + ansi16: {channels: 1, labels: ['ansi16']}, + ansi256: {channels: 1, labels: ['ansi256']}, + hcg: {channels: 3, labels: ['h', 'c', 'g']}, + apple: {channels: 3, labels: ['r16', 'g16', 'b16']}, + gray: {channels: 1, labels: ['gray']} + }; + + conversions$2 = convert; + + // Hide .channels and .labels properties + for (const model of Object.keys(convert)) { + if (!('channels' in convert[model])) { + throw new Error('missing channels property: ' + model); + } + + if (!('labels' in convert[model])) { + throw new Error('missing channel labels property: ' + model); + } + + if (convert[model].labels.length !== convert[model].channels) { + throw new Error('channel and label counts mismatch: ' + model); + } + + const {channels, labels} = convert[model]; + delete convert[model].channels; + delete convert[model].labels; + Object.defineProperty(convert[model], 'channels', {value: channels}); + Object.defineProperty(convert[model], 'labels', {value: labels}); + } + + convert.rgb.hsl = function (rgb) { + const r = rgb[0] / 255; + const g = rgb[1] / 255; + const b = rgb[2] / 255; + const min = Math.min(r, g, b); + const max = Math.max(r, g, b); + const delta = max - min; + let h; + let s; + + if (max === min) { + h = 0; + } else if (r === max) { + h = (g - b) / delta; + } else if (g === max) { + h = 2 + (b - r) / delta; + } else if (b === max) { + h = 4 + (r - g) / delta; + } + + h = Math.min(h * 60, 360); + + if (h < 0) { + h += 360; + } + + const l = (min + max) / 2; + + if (max === min) { + s = 0; + } else if (l <= 0.5) { + s = delta / (max + min); + } else { + s = delta / (2 - max - min); + } + + return [h, s * 100, l * 100]; + }; + + convert.rgb.hsv = function (rgb) { + let rdif; + let gdif; + let bdif; + let h; + let s; + + const r = rgb[0] / 255; + const g = rgb[1] / 255; + const b = rgb[2] / 255; + const v = Math.max(r, g, b); + const diff = v - Math.min(r, g, b); + const diffc = function (c) { + return (v - c) / 6 / diff + 1 / 2; + }; + + if (diff === 0) { + h = 0; + s = 0; + } else { + s = diff / v; + rdif = diffc(r); + gdif = diffc(g); + bdif = diffc(b); + + if (r === v) { + h = bdif - gdif; + } else if (g === v) { + h = (1 / 3) + rdif - bdif; + } else if (b === v) { + h = (2 / 3) + gdif - rdif; + } + + if (h < 0) { + h += 1; + } else if (h > 1) { + h -= 1; + } + } + + return [ + h * 360, + s * 100, + v * 100 + ]; + }; + + convert.rgb.hwb = function (rgb) { + const r = rgb[0]; + const g = rgb[1]; + let b = rgb[2]; + const h = convert.rgb.hsl(rgb)[0]; + const w = 1 / 255 * Math.min(r, Math.min(g, b)); + + b = 1 - 1 / 255 * Math.max(r, Math.max(g, b)); + + return [h, w * 100, b * 100]; + }; + + convert.rgb.cmyk = function (rgb) { + const r = rgb[0] / 255; + const g = rgb[1] / 255; + const b = rgb[2] / 255; + + const k = Math.min(1 - r, 1 - g, 1 - b); + const c = (1 - r - k) / (1 - k) || 0; + const m = (1 - g - k) / (1 - k) || 0; + const y = (1 - b - k) / (1 - k) || 0; + + return [c * 100, m * 100, y * 100, k * 100]; + }; + + function comparativeDistance(x, y) { + /* + See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance + */ + return ( + ((x[0] - y[0]) ** 2) + + ((x[1] - y[1]) ** 2) + + ((x[2] - y[2]) ** 2) + ); + } + + convert.rgb.keyword = function (rgb) { + const reversed = reverseKeywords[rgb]; + if (reversed) { + return reversed; + } + + let currentClosestDistance = Infinity; + let currentClosestKeyword; + + for (const keyword of Object.keys(cssKeywords)) { + const value = cssKeywords[keyword]; + + // Compute comparative distance + const distance = comparativeDistance(rgb, value); + + // Check if its less, if so set as closest + if (distance < currentClosestDistance) { + currentClosestDistance = distance; + currentClosestKeyword = keyword; + } + } + + return currentClosestKeyword; + }; + + convert.keyword.rgb = function (keyword) { + return cssKeywords[keyword]; + }; + + convert.rgb.xyz = function (rgb) { + let r = rgb[0] / 255; + let g = rgb[1] / 255; + let b = rgb[2] / 255; + + // Assume sRGB + r = r > 0.04045 ? (((r + 0.055) / 1.055) ** 2.4) : (r / 12.92); + g = g > 0.04045 ? (((g + 0.055) / 1.055) ** 2.4) : (g / 12.92); + b = b > 0.04045 ? (((b + 0.055) / 1.055) ** 2.4) : (b / 12.92); + + const x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805); + const y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722); + const z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505); + + return [x * 100, y * 100, z * 100]; + }; + + convert.rgb.lab = function (rgb) { + const xyz = convert.rgb.xyz(rgb); + let x = xyz[0]; + let y = xyz[1]; + let z = xyz[2]; + + x /= 95.047; + y /= 100; + z /= 108.883; + + x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116); + y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116); + z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116); + + const l = (116 * y) - 16; + const a = 500 * (x - y); + const b = 200 * (y - z); + + return [l, a, b]; + }; + + convert.hsl.rgb = function (hsl) { + const h = hsl[0] / 360; + const s = hsl[1] / 100; + const l = hsl[2] / 100; + let t2; + let t3; + let val; + + if (s === 0) { + val = l * 255; + return [val, val, val]; + } + + if (l < 0.5) { + t2 = l * (1 + s); + } else { + t2 = l + s - l * s; + } + + const t1 = 2 * l - t2; + + const rgb = [0, 0, 0]; + for (let i = 0; i < 3; i++) { + t3 = h + 1 / 3 * -(i - 1); + if (t3 < 0) { + t3++; + } + + if (t3 > 1) { + t3--; + } + + if (6 * t3 < 1) { + val = t1 + (t2 - t1) * 6 * t3; + } else if (2 * t3 < 1) { + val = t2; + } else if (3 * t3 < 2) { + val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; + } else { + val = t1; + } + + rgb[i] = val * 255; + } + + return rgb; + }; + + convert.hsl.hsv = function (hsl) { + const h = hsl[0]; + let s = hsl[1] / 100; + let l = hsl[2] / 100; + let smin = s; + const lmin = Math.max(l, 0.01); + + l *= 2; + s *= (l <= 1) ? l : 2 - l; + smin *= lmin <= 1 ? lmin : 2 - lmin; + const v = (l + s) / 2; + const sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s); + + return [h, sv * 100, v * 100]; + }; + + convert.hsv.rgb = function (hsv) { + const h = hsv[0] / 60; + const s = hsv[1] / 100; + let v = hsv[2] / 100; + const hi = Math.floor(h) % 6; + + const f = h - Math.floor(h); + const p = 255 * v * (1 - s); + const q = 255 * v * (1 - (s * f)); + const t = 255 * v * (1 - (s * (1 - f))); + v *= 255; + + switch (hi) { + case 0: + return [v, t, p]; + case 1: + return [q, v, p]; + case 2: + return [p, v, t]; + case 3: + return [p, q, v]; + case 4: + return [t, p, v]; + case 5: + return [v, p, q]; + } + }; + + convert.hsv.hsl = function (hsv) { + const h = hsv[0]; + const s = hsv[1] / 100; + const v = hsv[2] / 100; + const vmin = Math.max(v, 0.01); + let sl; + let l; + + l = (2 - s) * v; + const lmin = (2 - s) * vmin; + sl = s * vmin; + sl /= (lmin <= 1) ? lmin : 2 - lmin; + sl = sl || 0; + l /= 2; + + return [h, sl * 100, l * 100]; + }; + + // http://dev.w3.org/csswg/css-color/#hwb-to-rgb + convert.hwb.rgb = function (hwb) { + const h = hwb[0] / 360; + let wh = hwb[1] / 100; + let bl = hwb[2] / 100; + const ratio = wh + bl; + let f; + + // Wh + bl cant be > 1 + if (ratio > 1) { + wh /= ratio; + bl /= ratio; + } + + const i = Math.floor(6 * h); + const v = 1 - bl; + f = 6 * h - i; + + if ((i & 0x01) !== 0) { + f = 1 - f; + } + + const n = wh + f * (v - wh); // Linear interpolation + + let r; + let g; + let b; + /* eslint-disable max-statements-per-line,no-multi-spaces */ + switch (i) { + default: + case 6: + case 0: r = v; g = n; b = wh; break; + case 1: r = n; g = v; b = wh; break; + case 2: r = wh; g = v; b = n; break; + case 3: r = wh; g = n; b = v; break; + case 4: r = n; g = wh; b = v; break; + case 5: r = v; g = wh; b = n; break; + } + /* eslint-enable max-statements-per-line,no-multi-spaces */ + + return [r * 255, g * 255, b * 255]; + }; + + convert.cmyk.rgb = function (cmyk) { + const c = cmyk[0] / 100; + const m = cmyk[1] / 100; + const y = cmyk[2] / 100; + const k = cmyk[3] / 100; + + const r = 1 - Math.min(1, c * (1 - k) + k); + const g = 1 - Math.min(1, m * (1 - k) + k); + const b = 1 - Math.min(1, y * (1 - k) + k); + + return [r * 255, g * 255, b * 255]; + }; + + convert.xyz.rgb = function (xyz) { + const x = xyz[0] / 100; + const y = xyz[1] / 100; + const z = xyz[2] / 100; + let r; + let g; + let b; + + r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986); + g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415); + b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570); + + // Assume sRGB + r = r > 0.0031308 + ? ((1.055 * (r ** (1.0 / 2.4))) - 0.055) + : r * 12.92; + + g = g > 0.0031308 + ? ((1.055 * (g ** (1.0 / 2.4))) - 0.055) + : g * 12.92; + + b = b > 0.0031308 + ? ((1.055 * (b ** (1.0 / 2.4))) - 0.055) + : b * 12.92; + + r = Math.min(Math.max(0, r), 1); + g = Math.min(Math.max(0, g), 1); + b = Math.min(Math.max(0, b), 1); + + return [r * 255, g * 255, b * 255]; + }; + + convert.xyz.lab = function (xyz) { + let x = xyz[0]; + let y = xyz[1]; + let z = xyz[2]; + + x /= 95.047; + y /= 100; + z /= 108.883; + + x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116); + y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116); + z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116); + + const l = (116 * y) - 16; + const a = 500 * (x - y); + const b = 200 * (y - z); + + return [l, a, b]; + }; + + convert.lab.xyz = function (lab) { + const l = lab[0]; + const a = lab[1]; + const b = lab[2]; + let x; + let y; + let z; + + y = (l + 16) / 116; + x = a / 500 + y; + z = y - b / 200; + + const y2 = y ** 3; + const x2 = x ** 3; + const z2 = z ** 3; + y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787; + x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787; + z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787; + + x *= 95.047; + y *= 100; + z *= 108.883; + + return [x, y, z]; + }; + + convert.lab.lch = function (lab) { + const l = lab[0]; + const a = lab[1]; + const b = lab[2]; + let h; + + const hr = Math.atan2(b, a); + h = hr * 360 / 2 / Math.PI; + + if (h < 0) { + h += 360; + } + + const c = Math.sqrt(a * a + b * b); + + return [l, c, h]; + }; + + convert.lch.lab = function (lch) { + const l = lch[0]; + const c = lch[1]; + const h = lch[2]; + + const hr = h / 360 * 2 * Math.PI; + const a = c * Math.cos(hr); + const b = c * Math.sin(hr); + + return [l, a, b]; + }; + + convert.rgb.ansi16 = function (args, saturation = null) { + const [r, g, b] = args; + let value = saturation === null ? convert.rgb.hsv(args)[2] : saturation; // Hsv -> ansi16 optimization + + value = Math.round(value / 50); + + if (value === 0) { + return 30; + } + + let ansi = 30 + + ((Math.round(b / 255) << 2) + | (Math.round(g / 255) << 1) + | Math.round(r / 255)); + + if (value === 2) { + ansi += 60; + } + + return ansi; + }; + + convert.hsv.ansi16 = function (args) { + // Optimization here; we already know the value and don't need to get + // it converted for us. + return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]); + }; + + convert.rgb.ansi256 = function (args) { + const r = args[0]; + const g = args[1]; + const b = args[2]; + + // We use the extended greyscale palette here, with the exception of + // black and white. normal palette only has 4 greyscale shades. + if (r === g && g === b) { + if (r < 8) { + return 16; + } + + if (r > 248) { + return 231; + } + + return Math.round(((r - 8) / 247) * 24) + 232; + } + + const ansi = 16 + + (36 * Math.round(r / 255 * 5)) + + (6 * Math.round(g / 255 * 5)) + + Math.round(b / 255 * 5); + + return ansi; + }; + + convert.ansi16.rgb = function (args) { + let color = args % 10; + + // Handle greyscale + if (color === 0 || color === 7) { + if (args > 50) { + color += 3.5; + } + + color = color / 10.5 * 255; + + return [color, color, color]; + } + + const mult = (~~(args > 50) + 1) * 0.5; + const r = ((color & 1) * mult) * 255; + const g = (((color >> 1) & 1) * mult) * 255; + const b = (((color >> 2) & 1) * mult) * 255; + + return [r, g, b]; + }; + + convert.ansi256.rgb = function (args) { + // Handle greyscale + if (args >= 232) { + const c = (args - 232) * 10 + 8; + return [c, c, c]; + } + + args -= 16; + + let rem; + const r = Math.floor(args / 36) / 5 * 255; + const g = Math.floor((rem = args % 36) / 6) / 5 * 255; + const b = (rem % 6) / 5 * 255; + + return [r, g, b]; + }; + + convert.rgb.hex = function (args) { + const integer = ((Math.round(args[0]) & 0xFF) << 16) + + ((Math.round(args[1]) & 0xFF) << 8) + + (Math.round(args[2]) & 0xFF); + + const string = integer.toString(16).toUpperCase(); + return '000000'.substring(string.length) + string; + }; + + convert.hex.rgb = function (args) { + const match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i); + if (!match) { + return [0, 0, 0]; + } + + let colorString = match[0]; + + if (match[0].length === 3) { + colorString = colorString.split('').map(char => { + return char + char; + }).join(''); + } + + const integer = parseInt(colorString, 16); + const r = (integer >> 16) & 0xFF; + const g = (integer >> 8) & 0xFF; + const b = integer & 0xFF; + + return [r, g, b]; + }; + + convert.rgb.hcg = function (rgb) { + const r = rgb[0] / 255; + const g = rgb[1] / 255; + const b = rgb[2] / 255; + const max = Math.max(Math.max(r, g), b); + const min = Math.min(Math.min(r, g), b); + const chroma = (max - min); + let grayscale; + let hue; + + if (chroma < 1) { + grayscale = min / (1 - chroma); + } else { + grayscale = 0; + } + + if (chroma <= 0) { + hue = 0; + } else + if (max === r) { + hue = ((g - b) / chroma) % 6; + } else + if (max === g) { + hue = 2 + (b - r) / chroma; + } else { + hue = 4 + (r - g) / chroma; + } + + hue /= 6; + hue %= 1; + + return [hue * 360, chroma * 100, grayscale * 100]; + }; + + convert.hsl.hcg = function (hsl) { + const s = hsl[1] / 100; + const l = hsl[2] / 100; + + const c = l < 0.5 ? (2.0 * s * l) : (2.0 * s * (1.0 - l)); + + let f = 0; + if (c < 1.0) { + f = (l - 0.5 * c) / (1.0 - c); + } + + return [hsl[0], c * 100, f * 100]; + }; + + convert.hsv.hcg = function (hsv) { + const s = hsv[1] / 100; + const v = hsv[2] / 100; + + const c = s * v; + let f = 0; + + if (c < 1.0) { + f = (v - c) / (1 - c); + } + + return [hsv[0], c * 100, f * 100]; + }; + + convert.hcg.rgb = function (hcg) { + const h = hcg[0] / 360; + const c = hcg[1] / 100; + const g = hcg[2] / 100; + + if (c === 0.0) { + return [g * 255, g * 255, g * 255]; + } + + const pure = [0, 0, 0]; + const hi = (h % 1) * 6; + const v = hi % 1; + const w = 1 - v; + let mg = 0; + + /* eslint-disable max-statements-per-line */ + switch (Math.floor(hi)) { + case 0: + pure[0] = 1; pure[1] = v; pure[2] = 0; break; + case 1: + pure[0] = w; pure[1] = 1; pure[2] = 0; break; + case 2: + pure[0] = 0; pure[1] = 1; pure[2] = v; break; + case 3: + pure[0] = 0; pure[1] = w; pure[2] = 1; break; + case 4: + pure[0] = v; pure[1] = 0; pure[2] = 1; break; + default: + pure[0] = 1; pure[1] = 0; pure[2] = w; + } + /* eslint-enable max-statements-per-line */ + + mg = (1.0 - c) * g; + + return [ + (c * pure[0] + mg) * 255, + (c * pure[1] + mg) * 255, + (c * pure[2] + mg) * 255 + ]; + }; + + convert.hcg.hsv = function (hcg) { + const c = hcg[1] / 100; + const g = hcg[2] / 100; + + const v = c + g * (1.0 - c); + let f = 0; + + if (v > 0.0) { + f = c / v; + } + + return [hcg[0], f * 100, v * 100]; + }; + + convert.hcg.hsl = function (hcg) { + const c = hcg[1] / 100; + const g = hcg[2] / 100; + + const l = g * (1.0 - c) + 0.5 * c; + let s = 0; + + if (l > 0.0 && l < 0.5) { + s = c / (2 * l); + } else + if (l >= 0.5 && l < 1.0) { + s = c / (2 * (1 - l)); + } + + return [hcg[0], s * 100, l * 100]; + }; + + convert.hcg.hwb = function (hcg) { + const c = hcg[1] / 100; + const g = hcg[2] / 100; + const v = c + g * (1.0 - c); + return [hcg[0], (v - c) * 100, (1 - v) * 100]; + }; + + convert.hwb.hcg = function (hwb) { + const w = hwb[1] / 100; + const b = hwb[2] / 100; + const v = 1 - b; + const c = v - w; + let g = 0; + + if (c < 1) { + g = (v - c) / (1 - c); + } + + return [hwb[0], c * 100, g * 100]; + }; + + convert.apple.rgb = function (apple) { + return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255]; + }; + + convert.rgb.apple = function (rgb) { + return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535]; + }; + + convert.gray.rgb = function (args) { + return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255]; + }; + + convert.gray.hsl = function (args) { + return [0, 0, args[0]]; + }; + + convert.gray.hsv = convert.gray.hsl; + + convert.gray.hwb = function (gray) { + return [0, 100, gray[0]]; + }; + + convert.gray.cmyk = function (gray) { + return [0, 0, 0, gray[0]]; + }; + + convert.gray.lab = function (gray) { + return [gray[0], 0, 0]; + }; + + convert.gray.hex = function (gray) { + const val = Math.round(gray[0] / 100 * 255) & 0xFF; + const integer = (val << 16) + (val << 8) + val; + + const string = integer.toString(16).toUpperCase(); + return '000000'.substring(string.length) + string; + }; + + convert.rgb.gray = function (rgb) { + const val = (rgb[0] + rgb[1] + rgb[2]) / 3; + return [val / 255 * 100]; + }; + return conversions$2; +} + +var route$1; +var hasRequiredRoute$1; + +function requireRoute$1 () { + if (hasRequiredRoute$1) return route$1; + hasRequiredRoute$1 = 1; + const conversions = requireConversions$1(); + + /* + This function routes a model to all other models. + + all functions that are routed have a property `.conversion` attached + to the returned synthetic function. This property is an array + of strings, each with the steps in between the 'from' and 'to' + color models (inclusive). + + conversions that are not possible simply are not included. + */ + + function buildGraph() { + const graph = {}; + // https://jsperf.com/object-keys-vs-for-in-with-closure/3 + const models = Object.keys(conversions); + + for (let len = models.length, i = 0; i < len; i++) { + graph[models[i]] = { + // http://jsperf.com/1-vs-infinity + // micro-opt, but this is simple. + distance: -1, + parent: null + }; + } + + return graph; + } + + // https://en.wikipedia.org/wiki/Breadth-first_search + function deriveBFS(fromModel) { + const graph = buildGraph(); + const queue = [fromModel]; // Unshift -> queue -> pop + + graph[fromModel].distance = 0; + + while (queue.length) { + const current = queue.pop(); + const adjacents = Object.keys(conversions[current]); + + for (let len = adjacents.length, i = 0; i < len; i++) { + const adjacent = adjacents[i]; + const node = graph[adjacent]; + + if (node.distance === -1) { + node.distance = graph[current].distance + 1; + node.parent = current; + queue.unshift(adjacent); + } + } + } + + return graph; + } + + function link(from, to) { + return function (args) { + return to(from(args)); + }; + } + + function wrapConversion(toModel, graph) { + const path = [graph[toModel].parent, toModel]; + let fn = conversions[graph[toModel].parent][toModel]; + + let cur = graph[toModel].parent; + while (graph[cur].parent) { + path.unshift(graph[cur].parent); + fn = link(conversions[graph[cur].parent][cur], fn); + cur = graph[cur].parent; + } + + fn.conversion = path; + return fn; + } + + route$1 = function (fromModel) { + const graph = deriveBFS(fromModel); + const conversion = {}; + + const models = Object.keys(graph); + for (let len = models.length, i = 0; i < len; i++) { + const toModel = models[i]; + const node = graph[toModel]; + + if (node.parent === null) { + // No possible conversion, or this node is the source model. + continue; + } + + conversion[toModel] = wrapConversion(toModel, graph); + } + + return conversion; + }; + return route$1; +} + +var colorConvert$1; +var hasRequiredColorConvert$1; + +function requireColorConvert$1 () { + if (hasRequiredColorConvert$1) return colorConvert$1; + hasRequiredColorConvert$1 = 1; + const conversions = requireConversions$1(); + const route = requireRoute$1(); + + const convert = {}; + + const models = Object.keys(conversions); + + function wrapRaw(fn) { + const wrappedFn = function (...args) { + const arg0 = args[0]; + if (arg0 === undefined || arg0 === null) { + return arg0; + } + + if (arg0.length > 1) { + args = arg0; + } + + return fn(args); + }; + + // Preserve .conversion property if there is one + if ('conversion' in fn) { + wrappedFn.conversion = fn.conversion; + } + + return wrappedFn; + } + + function wrapRounded(fn) { + const wrappedFn = function (...args) { + const arg0 = args[0]; + + if (arg0 === undefined || arg0 === null) { + return arg0; + } + + if (arg0.length > 1) { + args = arg0; + } + + const result = fn(args); + + // We're assuming the result is an array here. + // see notice in conversions.js; don't use box types + // in conversion functions. + if (typeof result === 'object') { + for (let len = result.length, i = 0; i < len; i++) { + result[i] = Math.round(result[i]); + } + } + + return result; + }; + + // Preserve .conversion property if there is one + if ('conversion' in fn) { + wrappedFn.conversion = fn.conversion; + } + + return wrappedFn; + } + + models.forEach(fromModel => { + convert[fromModel] = {}; + + Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels}); + Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels}); + + const routes = route(fromModel); + const routeModels = Object.keys(routes); + + routeModels.forEach(toModel => { + const fn = routes[toModel]; + + convert[fromModel][toModel] = wrapRounded(fn); + convert[fromModel][toModel].raw = wrapRaw(fn); + }); + }); + + colorConvert$1 = convert; + return colorConvert$1; +} + +ansiStyles$3.exports; + +(function (module) { + + const wrapAnsi16 = (fn, offset) => (...args) => { + const code = fn(...args); + return `\u001B[${code + offset}m`; + }; + + const wrapAnsi256 = (fn, offset) => (...args) => { + const code = fn(...args); + return `\u001B[${38 + offset};5;${code}m`; + }; + + const wrapAnsi16m = (fn, offset) => (...args) => { + const rgb = fn(...args); + return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; + }; + + const ansi2ansi = n => n; + const rgb2rgb = (r, g, b) => [r, g, b]; + + const setLazyProperty = (object, property, get) => { + Object.defineProperty(object, property, { + get: () => { + const value = get(); + + Object.defineProperty(object, property, { + value, + enumerable: true, + configurable: true + }); + + return value; + }, + enumerable: true, + configurable: true + }); + }; + + /** @type {typeof import('color-convert')} */ + let colorConvert; + const makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => { + if (colorConvert === undefined) { + colorConvert = requireColorConvert$1(); + } + + const offset = isBackground ? 10 : 0; + const styles = {}; + + for (const [sourceSpace, suite] of Object.entries(colorConvert)) { + const name = sourceSpace === 'ansi16' ? 'ansi' : sourceSpace; + if (sourceSpace === targetSpace) { + styles[name] = wrap(identity, offset); + } else if (typeof suite === 'object') { + styles[name] = wrap(suite[targetSpace], offset); + } + } + + return styles; + }; + + function assembleStyles() { + const codes = new Map(); + const styles = { + modifier: { + reset: [0, 0], + // 21 isn't widely supported and 22 does the same thing + bold: [1, 22], + dim: [2, 22], + italic: [3, 23], + underline: [4, 24], + inverse: [7, 27], + hidden: [8, 28], + strikethrough: [9, 29] + }, + color: { + black: [30, 39], + red: [31, 39], + green: [32, 39], + yellow: [33, 39], + blue: [34, 39], + magenta: [35, 39], + cyan: [36, 39], + white: [37, 39], + + // Bright color + blackBright: [90, 39], + redBright: [91, 39], + greenBright: [92, 39], + yellowBright: [93, 39], + blueBright: [94, 39], + magentaBright: [95, 39], + cyanBright: [96, 39], + whiteBright: [97, 39] + }, + bgColor: { + bgBlack: [40, 49], + bgRed: [41, 49], + bgGreen: [42, 49], + bgYellow: [43, 49], + bgBlue: [44, 49], + bgMagenta: [45, 49], + bgCyan: [46, 49], + bgWhite: [47, 49], + + // Bright color + bgBlackBright: [100, 49], + bgRedBright: [101, 49], + bgGreenBright: [102, 49], + bgYellowBright: [103, 49], + bgBlueBright: [104, 49], + bgMagentaBright: [105, 49], + bgCyanBright: [106, 49], + bgWhiteBright: [107, 49] + } + }; + + // Alias bright black as gray (and grey) + styles.color.gray = styles.color.blackBright; + styles.bgColor.bgGray = styles.bgColor.bgBlackBright; + styles.color.grey = styles.color.blackBright; + styles.bgColor.bgGrey = styles.bgColor.bgBlackBright; + + for (const [groupName, group] of Object.entries(styles)) { + for (const [styleName, style] of Object.entries(group)) { + styles[styleName] = { + open: `\u001B[${style[0]}m`, + close: `\u001B[${style[1]}m` + }; + + group[styleName] = styles[styleName]; + + codes.set(style[0], style[1]); + } + + Object.defineProperty(styles, groupName, { + value: group, + enumerable: false + }); + } + + Object.defineProperty(styles, 'codes', { + value: codes, + enumerable: false + }); + + styles.color.close = '\u001B[39m'; + styles.bgColor.close = '\u001B[49m'; + + setLazyProperty(styles.color, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, false)); + setLazyProperty(styles.color, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, false)); + setLazyProperty(styles.color, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, false)); + setLazyProperty(styles.bgColor, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, true)); + setLazyProperty(styles.bgColor, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, true)); + setLazyProperty(styles.bgColor, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, true)); + + return styles; + } + + // Make the export immutable + Object.defineProperty(module, 'exports', { + enumerable: true, + get: assembleStyles + }); +} (ansiStyles$3)); + +var ansiStylesExports$1 = ansiStyles$3.exports; + +const isFullwidthCodePoint = isFullwidthCodePointExports; +const astralRegex = astralRegex_1; +const ansiStyles$2 = ansiStylesExports$1; + +const ESCAPES$1 = [ + '\u001B', + '\u009B' +]; + +const wrapAnsi = code => `${ESCAPES$1[0]}[${code}m`; + +const checkAnsi = (ansiCodes, isEscapes, endAnsiCode) => { + let output = []; + ansiCodes = [...ansiCodes]; + + for (let ansiCode of ansiCodes) { + const ansiCodeOrigin = ansiCode; + if (ansiCode.includes(';')) { + ansiCode = ansiCode.split(';')[0][0] + '0'; + } + + const item = ansiStyles$2.codes.get(Number.parseInt(ansiCode, 10)); + if (item) { + const indexEscape = ansiCodes.indexOf(item.toString()); + if (indexEscape === -1) { + output.push(wrapAnsi(isEscapes ? item : ansiCodeOrigin)); + } else { + ansiCodes.splice(indexEscape, 1); + } + } else if (isEscapes) { + output.push(wrapAnsi(0)); + break; + } else { + output.push(wrapAnsi(ansiCodeOrigin)); + } + } + + if (isEscapes) { + output = output.filter((element, index) => output.indexOf(element) === index); + + if (endAnsiCode !== undefined) { + const fistEscapeCode = wrapAnsi(ansiStyles$2.codes.get(Number.parseInt(endAnsiCode, 10))); + output = output.reduce((current, next) => next === fistEscapeCode ? [next, ...current] : [...current, next], []); + } + } + + return output.join(''); +}; + +var sliceAnsi = (string, begin, end) => { + const characters = [...string]; + const ansiCodes = []; + + let stringEnd = typeof end === 'number' ? end : characters.length; + let isInsideEscape = false; + let ansiCode; + let visible = 0; + let output = ''; + + for (const [index, character] of characters.entries()) { + let leftEscape = false; + + if (ESCAPES$1.includes(character)) { + const code = /\d[^m]*/.exec(string.slice(index, index + 18)); + ansiCode = code && code.length > 0 ? code[0] : undefined; + + if (visible < stringEnd) { + isInsideEscape = true; + + if (ansiCode !== undefined) { + ansiCodes.push(ansiCode); + } + } + } else if (isInsideEscape && character === 'm') { + isInsideEscape = false; + leftEscape = true; + } + + if (!isInsideEscape && !leftEscape) { + visible++; + } + + if (!astralRegex({exact: true}).test(character) && isFullwidthCodePoint(character.codePointAt())) { + visible++; + + if (typeof end !== 'number') { + stringEnd++; + } + } + + if (visible > begin && visible <= stringEnd) { + output += character; + } else if (visible === begin && !isInsideEscape && ansiCode !== undefined) { + output = checkAnsi(ansiCodes); + } else if (visible >= stringEnd) { + output += checkAnsi(ansiCodes, true, ansiCode); + break; + } + } + + return output; +}; + +var getBorderCharacters$1 = {}; + +/* eslint-disable sort-keys-fix/sort-keys-fix */ +Object.defineProperty(getBorderCharacters$1, "__esModule", { value: true }); +getBorderCharacters$1.getBorderCharacters = void 0; +const getBorderCharacters = (name) => { + if (name === 'honeywell') { + return { + topBody: '═', + topJoin: '╤', + topLeft: '╔', + topRight: '╗', + bottomBody: '═', + bottomJoin: '╧', + bottomLeft: '╚', + bottomRight: '╝', + bodyLeft: '║', + bodyRight: '║', + bodyJoin: '│', + headerJoin: '┬', + joinBody: '─', + joinLeft: '╟', + joinRight: '╢', + joinJoin: '┼', + joinMiddleDown: '┬', + joinMiddleUp: '┴', + joinMiddleLeft: '┤', + joinMiddleRight: '├', + }; + } + if (name === 'norc') { + return { + topBody: '─', + topJoin: '┬', + topLeft: '┌', + topRight: '┐', + bottomBody: '─', + bottomJoin: '┴', + bottomLeft: '└', + bottomRight: '┘', + bodyLeft: '│', + bodyRight: '│', + bodyJoin: '│', + headerJoin: '┬', + joinBody: '─', + joinLeft: '├', + joinRight: '┤', + joinJoin: '┼', + joinMiddleDown: '┬', + joinMiddleUp: '┴', + joinMiddleLeft: '┤', + joinMiddleRight: '├', + }; + } + if (name === 'ramac') { + return { + topBody: '-', + topJoin: '+', + topLeft: '+', + topRight: '+', + bottomBody: '-', + bottomJoin: '+', + bottomLeft: '+', + bottomRight: '+', + bodyLeft: '|', + bodyRight: '|', + bodyJoin: '|', + headerJoin: '+', + joinBody: '-', + joinLeft: '|', + joinRight: '|', + joinJoin: '|', + joinMiddleDown: '+', + joinMiddleUp: '+', + joinMiddleLeft: '+', + joinMiddleRight: '+', + }; + } + if (name === 'void') { + return { + topBody: '', + topJoin: '', + topLeft: '', + topRight: '', + bottomBody: '', + bottomJoin: '', + bottomLeft: '', + bottomRight: '', + bodyLeft: '', + bodyRight: '', + bodyJoin: '', + headerJoin: '', + joinBody: '', + joinLeft: '', + joinRight: '', + joinJoin: '', + joinMiddleDown: '', + joinMiddleUp: '', + joinMiddleLeft: '', + joinMiddleRight: '', + }; + } + throw new Error('Unknown border template "' + name + '".'); +}; +getBorderCharacters$1.getBorderCharacters = getBorderCharacters; + +(function (exports) { + var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.isCellInRange = exports.areCellEqual = exports.calculateRangeCoordinate = exports.findOriginalRowIndex = exports.flatten = exports.extractTruncates = exports.sumArray = exports.sequence = exports.distributeUnevenly = exports.countSpaceSequence = exports.groupBySizes = exports.makeBorderConfig = exports.splitAnsi = exports.normalizeString = void 0; + const slice_ansi_1 = __importDefault(sliceAnsi); + const string_width_1 = __importDefault(stringWidthExports); + const strip_ansi_1 = __importDefault(stripAnsi$4); + const getBorderCharacters_1 = getBorderCharacters$1; + /** + * Converts Windows-style newline to Unix-style + * + * @internal + */ + const normalizeString = (input) => { + return input.replace(/\r\n/g, '\n'); + }; + exports.normalizeString = normalizeString; + /** + * Splits ansi string by newlines + * + * @internal + */ + const splitAnsi = (input) => { + const lengths = (0, strip_ansi_1.default)(input).split('\n').map(string_width_1.default); + const result = []; + let startIndex = 0; + lengths.forEach((length) => { + result.push(length === 0 ? '' : (0, slice_ansi_1.default)(input, startIndex, startIndex + length)); + // Plus 1 for the newline character itself + startIndex += length + 1; + }); + return result; + }; + exports.splitAnsi = splitAnsi; + /** + * Merges user provided border characters with the default border ("honeywell") characters. + * + * @internal + */ + const makeBorderConfig = (border) => { + return { + ...(0, getBorderCharacters_1.getBorderCharacters)('honeywell'), + ...border, + }; + }; + exports.makeBorderConfig = makeBorderConfig; + /** + * Groups the array into sub-arrays by sizes. + * + * @internal + * @example + * groupBySizes(['a', 'b', 'c', 'd', 'e'], [2, 1, 2]) = [ ['a', 'b'], ['c'], ['d', 'e'] ] + */ + const groupBySizes = (array, sizes) => { + let startIndex = 0; + return sizes.map((size) => { + const group = array.slice(startIndex, startIndex + size); + startIndex += size; + return group; + }); + }; + exports.groupBySizes = groupBySizes; + /** + * Counts the number of continuous spaces in a string + * + * @internal + * @example + * countGroupSpaces('a bc de f') = 3 + */ + const countSpaceSequence = (input) => { + var _a, _b; + return (_b = (_a = input.match(/\s+/g)) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0; + }; + exports.countSpaceSequence = countSpaceSequence; + /** + * Creates the non-increasing number array given sum and length + * whose the difference between maximum and minimum is not greater than 1 + * + * @internal + * @example + * distributeUnevenly(6, 3) = [2, 2, 2] + * distributeUnevenly(8, 3) = [3, 3, 2] + */ + const distributeUnevenly = (sum, length) => { + const result = Array.from({ length }).fill(Math.floor(sum / length)); + return result.map((element, index) => { + return element + (index < sum % length ? 1 : 0); + }); + }; + exports.distributeUnevenly = distributeUnevenly; + const sequence = (start, end) => { + return Array.from({ length: end - start + 1 }, (_, index) => { + return index + start; + }); + }; + exports.sequence = sequence; + const sumArray = (array) => { + return array.reduce((accumulator, element) => { + return accumulator + element; + }, 0); + }; + exports.sumArray = sumArray; + const extractTruncates = (config) => { + return config.columns.map(({ truncate }) => { + return truncate; + }); + }; + exports.extractTruncates = extractTruncates; + const flatten = (array) => { + return [].concat(...array); + }; + exports.flatten = flatten; + const findOriginalRowIndex = (mappedRowHeights, mappedRowIndex) => { + const rowIndexMapping = (0, exports.flatten)(mappedRowHeights.map((height, index) => { + return Array.from({ length: height }, () => { + return index; + }); + })); + return rowIndexMapping[mappedRowIndex]; + }; + exports.findOriginalRowIndex = findOriginalRowIndex; + const calculateRangeCoordinate = (spanningCellConfig) => { + const { row, col, colSpan = 1, rowSpan = 1 } = spanningCellConfig; + return { bottomRight: { col: col + colSpan - 1, + row: row + rowSpan - 1 }, + topLeft: { col, + row } }; + }; + exports.calculateRangeCoordinate = calculateRangeCoordinate; + const areCellEqual = (cell1, cell2) => { + return cell1.row === cell2.row && cell1.col === cell2.col; + }; + exports.areCellEqual = areCellEqual; + const isCellInRange = (cell, { topLeft, bottomRight }) => { + return (topLeft.row <= cell.row && + cell.row <= bottomRight.row && + topLeft.col <= cell.col && + cell.col <= bottomRight.col); + }; + exports.isCellInRange = isCellInRange; + +} (utils$1)); + +var __importDefault$4 = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(alignString$1, "__esModule", { value: true }); +alignString$1.alignString = void 0; +const string_width_1$2 = __importDefault$4(stringWidthExports); +const utils_1$e = utils$1; +const alignLeft = (subject, width) => { + return subject + ' '.repeat(width); +}; +const alignRight = (subject, width) => { + return ' '.repeat(width) + subject; +}; +const alignCenter = (subject, width) => { + return ' '.repeat(Math.floor(width / 2)) + subject + ' '.repeat(Math.ceil(width / 2)); +}; +const alignJustify = (subject, width) => { + const spaceSequenceCount = (0, utils_1$e.countSpaceSequence)(subject); + if (spaceSequenceCount === 0) { + return alignLeft(subject, width); + } + const addingSpaces = (0, utils_1$e.distributeUnevenly)(width, spaceSequenceCount); + if (Math.max(...addingSpaces) > 3) { + return alignLeft(subject, width); + } + let spaceSequenceIndex = 0; + return subject.replace(/\s+/g, (groupSpace) => { + return groupSpace + ' '.repeat(addingSpaces[spaceSequenceIndex++]); + }); +}; +/** + * Pads a string to the left and/or right to position the subject + * text in a desired alignment within a container. + */ +const alignString = (subject, containerWidth, alignment) => { + const subjectWidth = (0, string_width_1$2.default)(subject); + if (subjectWidth === containerWidth) { + return subject; + } + if (subjectWidth > containerWidth) { + throw new Error('Subject parameter value width cannot be greater than the container width.'); + } + if (subjectWidth === 0) { + return ' '.repeat(containerWidth); + } + const availableWidth = containerWidth - subjectWidth; + if (alignment === 'left') { + return alignLeft(subject, availableWidth); + } + if (alignment === 'right') { + return alignRight(subject, availableWidth); + } + if (alignment === 'justify') { + return alignJustify(subject, availableWidth); + } + return alignCenter(subject, availableWidth); +}; +alignString$1.alignString = alignString; + +Object.defineProperty(alignTableData$1, "__esModule", { value: true }); +alignTableData$1.alignTableData = void 0; +const alignString_1$1 = alignString$1; +const alignTableData = (rows, config) => { + return rows.map((row, rowIndex) => { + return row.map((cell, cellIndex) => { + var _a; + const { width, alignment } = config.columns[cellIndex]; + const containingRange = (_a = config.spanningCellManager) === null || _a === void 0 ? void 0 : _a.getContainingRange({ col: cellIndex, + row: rowIndex }, { mapped: true }); + if (containingRange) { + return cell; + } + return (0, alignString_1$1.alignString)(cell, width, alignment); + }); + }); +}; +alignTableData$1.alignTableData = alignTableData; + +var calculateRowHeights$1 = {}; + +var calculateCellHeight$1 = {}; + +var wrapCell$1 = {}; + +var wrapString$1 = {}; + +var __importDefault$3 = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(wrapString$1, "__esModule", { value: true }); +wrapString$1.wrapString = void 0; +const slice_ansi_1$1 = __importDefault$3(sliceAnsi); +const string_width_1$1 = __importDefault$3(stringWidthExports); +/** + * Creates an array of strings split into groups the length of size. + * This function works with strings that contain ASCII characters. + * + * wrapText is different from would-be "chunk" implementation + * in that whitespace characters that occur on a chunk size limit are trimmed. + * + */ +const wrapString = (subject, size) => { + let subjectSlice = subject; + const chunks = []; + do { + chunks.push((0, slice_ansi_1$1.default)(subjectSlice, 0, size)); + subjectSlice = (0, slice_ansi_1$1.default)(subjectSlice, size).trim(); + } while ((0, string_width_1$1.default)(subjectSlice)); + return chunks; +}; +wrapString$1.wrapString = wrapString; + +var wrapWord$1 = {}; + +var __importDefault$2 = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(wrapWord$1, "__esModule", { value: true }); +wrapWord$1.wrapWord = void 0; +const slice_ansi_1 = __importDefault$2(sliceAnsi); +const strip_ansi_1 = __importDefault$2(stripAnsi$4); +const calculateStringLengths = (input, size) => { + let subject = (0, strip_ansi_1.default)(input); + const chunks = []; + // https://regex101.com/r/gY5kZ1/1 + const re = new RegExp('(^.{1,' + String(Math.max(size, 1)) + '}(\\s+|$))|(^.{1,' + String(Math.max(size - 1, 1)) + '}(\\\\|/|_|\\.|,|;|-))'); + do { + let chunk; + const match = re.exec(subject); + if (match) { + chunk = match[0]; + subject = subject.slice(chunk.length); + const trimmedLength = chunk.trim().length; + const offset = chunk.length - trimmedLength; + chunks.push([trimmedLength, offset]); + } + else { + chunk = subject.slice(0, size); + subject = subject.slice(size); + chunks.push([chunk.length, 0]); + } + } while (subject.length); + return chunks; +}; +const wrapWord = (input, size) => { + const result = []; + let startIndex = 0; + calculateStringLengths(input, size).forEach(([length, offset]) => { + result.push((0, slice_ansi_1.default)(input, startIndex, startIndex + length)); + startIndex += length + offset; + }); + return result; +}; +wrapWord$1.wrapWord = wrapWord; + +Object.defineProperty(wrapCell$1, "__esModule", { value: true }); +wrapCell$1.wrapCell = void 0; +const utils_1$d = utils$1; +const wrapString_1 = wrapString$1; +const wrapWord_1 = wrapWord$1; +/** + * Wrap a single cell value into a list of lines + * + * Always wraps on newlines, for the remainder uses either word or string wrapping + * depending on user configuration. + * + */ +const wrapCell = (cellValue, cellWidth, useWrapWord) => { + // First split on literal newlines + const cellLines = (0, utils_1$d.splitAnsi)(cellValue); + // Then iterate over the list and word-wrap every remaining line if necessary. + for (let lineNr = 0; lineNr < cellLines.length;) { + let lineChunks; + if (useWrapWord) { + lineChunks = (0, wrapWord_1.wrapWord)(cellLines[lineNr], cellWidth); + } + else { + lineChunks = (0, wrapString_1.wrapString)(cellLines[lineNr], cellWidth); + } + // Replace our original array element with whatever the wrapping returned + cellLines.splice(lineNr, 1, ...lineChunks); + lineNr += lineChunks.length; + } + return cellLines; +}; +wrapCell$1.wrapCell = wrapCell; + +Object.defineProperty(calculateCellHeight$1, "__esModule", { value: true }); +calculateCellHeight$1.calculateCellHeight = void 0; +const wrapCell_1$1 = wrapCell$1; +/** + * Calculates height of cell content in regard to its width and word wrapping. + */ +const calculateCellHeight = (value, columnWidth, useWrapWord = false) => { + return (0, wrapCell_1$1.wrapCell)(value, columnWidth, useWrapWord).length; +}; +calculateCellHeight$1.calculateCellHeight = calculateCellHeight; + +Object.defineProperty(calculateRowHeights$1, "__esModule", { value: true }); +calculateRowHeights$1.calculateRowHeights = void 0; +const calculateCellHeight_1 = calculateCellHeight$1; +const utils_1$c = utils$1; +/** + * Produces an array of values that describe the largest value length (height) in every row. + */ +const calculateRowHeights = (rows, config) => { + const rowHeights = []; + for (const [rowIndex, row] of rows.entries()) { + let rowHeight = 1; + row.forEach((cell, cellIndex) => { + var _a; + const containingRange = (_a = config.spanningCellManager) === null || _a === void 0 ? void 0 : _a.getContainingRange({ col: cellIndex, + row: rowIndex }); + if (!containingRange) { + const cellHeight = (0, calculateCellHeight_1.calculateCellHeight)(cell, config.columns[cellIndex].width, config.columns[cellIndex].wrapWord); + rowHeight = Math.max(rowHeight, cellHeight); + return; + } + const { topLeft, bottomRight, height } = containingRange; + // bottom-most cell of a range needs to contain all remain lines of spanning cells + if (rowIndex === bottomRight.row) { + const totalOccupiedSpanningCellHeight = (0, utils_1$c.sumArray)(rowHeights.slice(topLeft.row)); + const totalHorizontalBorderHeight = bottomRight.row - topLeft.row; + const totalHiddenHorizontalBorderHeight = (0, utils_1$c.sequence)(topLeft.row + 1, bottomRight.row).filter((horizontalBorderIndex) => { + var _a; + /* istanbul ignore next */ + return !((_a = config.drawHorizontalLine) === null || _a === void 0 ? void 0 : _a.call(config, horizontalBorderIndex, rows.length)); + }).length; + const cellHeight = height - totalOccupiedSpanningCellHeight - totalHorizontalBorderHeight + totalHiddenHorizontalBorderHeight; + rowHeight = Math.max(rowHeight, cellHeight); + } + // otherwise, just depend on other sibling cell heights in the row + }); + rowHeights.push(rowHeight); + } + return rowHeights; +}; +calculateRowHeights$1.calculateRowHeights = calculateRowHeights; + +var drawBorder = {}; + +var drawContent$1 = {}; + +Object.defineProperty(drawContent$1, "__esModule", { value: true }); +drawContent$1.drawContent = void 0; +const drawContent = (parameters) => { + const { contents, separatorGetter, drawSeparator, spanningCellManager, rowIndex, elementType } = parameters; + const contentSize = contents.length; + const result = []; + if (drawSeparator(0, contentSize)) { + result.push(separatorGetter(0, contentSize)); + } + contents.forEach((content, contentIndex) => { + if (!elementType || elementType === 'border' || elementType === 'row') { + result.push(content); + } + if (elementType === 'cell' && rowIndex === undefined) { + result.push(content); + } + if (elementType === 'cell' && rowIndex !== undefined) { + /* istanbul ignore next */ + const containingRange = spanningCellManager === null || spanningCellManager === void 0 ? void 0 : spanningCellManager.getContainingRange({ col: contentIndex, + row: rowIndex }); + // when drawing content row, just add a cell when it is a normal cell + // or belongs to first column of spanning cell + if (!containingRange || contentIndex === containingRange.topLeft.col) { + result.push(content); + } + } + // Only append the middle separator if the content is not the last + if (contentIndex + 1 < contentSize && drawSeparator(contentIndex + 1, contentSize)) { + const separator = separatorGetter(contentIndex + 1, contentSize); + if (elementType === 'cell' && rowIndex !== undefined) { + const currentCell = { col: contentIndex + 1, + row: rowIndex }; + /* istanbul ignore next */ + const containingRange = spanningCellManager === null || spanningCellManager === void 0 ? void 0 : spanningCellManager.getContainingRange(currentCell); + if (!containingRange || containingRange.topLeft.col === currentCell.col) { + result.push(separator); + } + } + else { + result.push(separator); + } + } + }); + if (drawSeparator(contentSize, contentSize)) { + result.push(separatorGetter(contentSize, contentSize)); + } + return result.join(''); +}; +drawContent$1.drawContent = drawContent; + +(function (exports) { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.createTableBorderGetter = exports.drawBorderBottom = exports.drawBorderJoin = exports.drawBorderTop = exports.drawBorder = exports.createSeparatorGetter = exports.drawBorderSegments = void 0; + const drawContent_1 = drawContent$1; + const drawBorderSegments = (columnWidths, parameters) => { + const { separator, horizontalBorderIndex, spanningCellManager } = parameters; + return columnWidths.map((columnWidth, columnIndex) => { + const normalSegment = separator.body.repeat(columnWidth); + if (horizontalBorderIndex === undefined) { + return normalSegment; + } + /* istanbul ignore next */ + const range = spanningCellManager === null || spanningCellManager === void 0 ? void 0 : spanningCellManager.getContainingRange({ col: columnIndex, + row: horizontalBorderIndex }); + if (!range) { + return normalSegment; + } + const { topLeft } = range; + // draw border segments as usual for top border of spanning cell + if (horizontalBorderIndex === topLeft.row) { + return normalSegment; + } + // if for first column/row of spanning cell, just skip + if (columnIndex !== topLeft.col) { + return ''; + } + return range.extractBorderContent(horizontalBorderIndex); + }); + }; + exports.drawBorderSegments = drawBorderSegments; + const createSeparatorGetter = (dependencies) => { + const { separator, spanningCellManager, horizontalBorderIndex, rowCount } = dependencies; + // eslint-disable-next-line complexity + return (verticalBorderIndex, columnCount) => { + const inSameRange = spanningCellManager === null || spanningCellManager === void 0 ? void 0 : spanningCellManager.inSameRange; + if (horizontalBorderIndex !== undefined && inSameRange) { + const topCell = { col: verticalBorderIndex, + row: horizontalBorderIndex - 1 }; + const leftCell = { col: verticalBorderIndex - 1, + row: horizontalBorderIndex }; + const oppositeCell = { col: verticalBorderIndex - 1, + row: horizontalBorderIndex - 1 }; + const currentCell = { col: verticalBorderIndex, + row: horizontalBorderIndex }; + const pairs = [ + [oppositeCell, topCell], + [topCell, currentCell], + [currentCell, leftCell], + [leftCell, oppositeCell], + ]; + // left side of horizontal border + if (verticalBorderIndex === 0) { + if (inSameRange(currentCell, topCell) && separator.bodyJoinOuter) { + return separator.bodyJoinOuter; + } + return separator.left; + } + // right side of horizontal border + if (verticalBorderIndex === columnCount) { + if (inSameRange(oppositeCell, leftCell) && separator.bodyJoinOuter) { + return separator.bodyJoinOuter; + } + return separator.right; + } + // top horizontal border + if (horizontalBorderIndex === 0) { + if (inSameRange(currentCell, leftCell)) { + return separator.body; + } + return separator.join; + } + // bottom horizontal border + if (horizontalBorderIndex === rowCount) { + if (inSameRange(topCell, oppositeCell)) { + return separator.body; + } + return separator.join; + } + const sameRangeCount = pairs.map((pair) => { + return inSameRange(...pair); + }).filter(Boolean).length; + // four cells are belongs to different spanning cells + if (sameRangeCount === 0) { + return separator.join; + } + // belong to one spanning cell + if (sameRangeCount === 4) { + return ''; + } + // belongs to two spanning cell + if (sameRangeCount === 2) { + if (inSameRange(...pairs[1]) && inSameRange(...pairs[3]) && separator.bodyJoinInner) { + return separator.bodyJoinInner; + } + return separator.body; + } + /* istanbul ignore next */ + if (sameRangeCount === 1) { + if (!separator.joinRight || !separator.joinLeft || !separator.joinUp || !separator.joinDown) { + throw new Error(`Can not get border separator for position [${horizontalBorderIndex}, ${verticalBorderIndex}]`); + } + if (inSameRange(...pairs[0])) { + return separator.joinDown; + } + if (inSameRange(...pairs[1])) { + return separator.joinLeft; + } + if (inSameRange(...pairs[2])) { + return separator.joinUp; + } + return separator.joinRight; + } + /* istanbul ignore next */ + throw new Error('Invalid case'); + } + if (verticalBorderIndex === 0) { + return separator.left; + } + if (verticalBorderIndex === columnCount) { + return separator.right; + } + return separator.join; + }; + }; + exports.createSeparatorGetter = createSeparatorGetter; + const drawBorder = (columnWidths, parameters) => { + const borderSegments = (0, exports.drawBorderSegments)(columnWidths, parameters); + const { drawVerticalLine, horizontalBorderIndex, spanningCellManager } = parameters; + return (0, drawContent_1.drawContent)({ + contents: borderSegments, + drawSeparator: drawVerticalLine, + elementType: 'border', + rowIndex: horizontalBorderIndex, + separatorGetter: (0, exports.createSeparatorGetter)(parameters), + spanningCellManager, + }) + '\n'; + }; + exports.drawBorder = drawBorder; + const drawBorderTop = (columnWidths, parameters) => { + const { border } = parameters; + const result = (0, exports.drawBorder)(columnWidths, { + ...parameters, + separator: { + body: border.topBody, + join: border.topJoin, + left: border.topLeft, + right: border.topRight, + }, + }); + if (result === '\n') { + return ''; + } + return result; + }; + exports.drawBorderTop = drawBorderTop; + const drawBorderJoin = (columnWidths, parameters) => { + const { border } = parameters; + return (0, exports.drawBorder)(columnWidths, { + ...parameters, + separator: { + body: border.joinBody, + bodyJoinInner: border.bodyJoin, + bodyJoinOuter: border.bodyLeft, + join: border.joinJoin, + joinDown: border.joinMiddleDown, + joinLeft: border.joinMiddleLeft, + joinRight: border.joinMiddleRight, + joinUp: border.joinMiddleUp, + left: border.joinLeft, + right: border.joinRight, + }, + }); + }; + exports.drawBorderJoin = drawBorderJoin; + const drawBorderBottom = (columnWidths, parameters) => { + const { border } = parameters; + return (0, exports.drawBorder)(columnWidths, { + ...parameters, + separator: { + body: border.bottomBody, + join: border.bottomJoin, + left: border.bottomLeft, + right: border.bottomRight, + }, + }); + }; + exports.drawBorderBottom = drawBorderBottom; + const createTableBorderGetter = (columnWidths, parameters) => { + return (index, size) => { + const drawBorderParameters = { ...parameters, + horizontalBorderIndex: index }; + if (index === 0) { + return (0, exports.drawBorderTop)(columnWidths, drawBorderParameters); + } + else if (index === size) { + return (0, exports.drawBorderBottom)(columnWidths, drawBorderParameters); + } + return (0, exports.drawBorderJoin)(columnWidths, drawBorderParameters); + }; + }; + exports.createTableBorderGetter = createTableBorderGetter; + +} (drawBorder)); + +var drawRow$1 = {}; + +Object.defineProperty(drawRow$1, "__esModule", { value: true }); +drawRow$1.drawRow = void 0; +const drawContent_1$1 = drawContent$1; +const drawRow = (row, config) => { + const { border, drawVerticalLine, rowIndex, spanningCellManager } = config; + return (0, drawContent_1$1.drawContent)({ + contents: row, + drawSeparator: drawVerticalLine, + elementType: 'cell', + rowIndex, + separatorGetter: (index, columnCount) => { + if (index === 0) { + return border.bodyLeft; + } + if (index === columnCount) { + return border.bodyRight; + } + return border.bodyJoin; + }, + spanningCellManager, + }) + '\n'; +}; +drawRow$1.drawRow = drawRow; + +var makeStreamConfig$1 = {}; + +var validateConfig$1 = {}; + +var validators = {}; + +(function (exports) { + exports["config.json"] = validate43; + const schema13 = { + "$id": "config.json", + "$schema": "http://json-schema.org/draft-07/schema#", + "type": "object", + "properties": { + "border": { + "$ref": "shared.json#/definitions/borders" + }, + "header": { + "type": "object", + "properties": { + "content": { + "type": "string" + }, + "alignment": { + "$ref": "shared.json#/definitions/alignment" + }, + "wrapWord": { + "type": "boolean" + }, + "truncate": { + "type": "integer" + }, + "paddingLeft": { + "type": "integer" + }, + "paddingRight": { + "type": "integer" + } + }, + "required": ["content"], + "additionalProperties": false + }, + "columns": { + "$ref": "shared.json#/definitions/columns" + }, + "columnDefault": { + "$ref": "shared.json#/definitions/column" + }, + "drawVerticalLine": { + "typeof": "function" + }, + "drawHorizontalLine": { + "typeof": "function" + }, + "singleLine": { + "typeof": "boolean" + }, + "spanningCells": { + "type": "array", + "items": { + "type": "object", + "properties": { + "col": { + "type": "integer", + "minimum": 0 + }, + "row": { + "type": "integer", + "minimum": 0 + }, + "colSpan": { + "type": "integer", + "minimum": 1 + }, + "rowSpan": { + "type": "integer", + "minimum": 1 + }, + "alignment": { + "$ref": "shared.json#/definitions/alignment" + }, + "verticalAlignment": { + "$ref": "shared.json#/definitions/verticalAlignment" + }, + "wrapWord": { + "type": "boolean" + }, + "truncate": { + "type": "integer" + }, + "paddingLeft": { + "type": "integer" + }, + "paddingRight": { + "type": "integer" + } + }, + "required": ["row", "col"], + "additionalProperties": false + } + } + }, + "additionalProperties": false + }; + const schema15 = { + "type": "object", + "properties": { + "topBody": { + "$ref": "#/definitions/border" + }, + "topJoin": { + "$ref": "#/definitions/border" + }, + "topLeft": { + "$ref": "#/definitions/border" + }, + "topRight": { + "$ref": "#/definitions/border" + }, + "bottomBody": { + "$ref": "#/definitions/border" + }, + "bottomJoin": { + "$ref": "#/definitions/border" + }, + "bottomLeft": { + "$ref": "#/definitions/border" + }, + "bottomRight": { + "$ref": "#/definitions/border" + }, + "bodyLeft": { + "$ref": "#/definitions/border" + }, + "bodyRight": { + "$ref": "#/definitions/border" + }, + "bodyJoin": { + "$ref": "#/definitions/border" + }, + "headerJoin": { + "$ref": "#/definitions/border" + }, + "joinBody": { + "$ref": "#/definitions/border" + }, + "joinLeft": { + "$ref": "#/definitions/border" + }, + "joinRight": { + "$ref": "#/definitions/border" + }, + "joinJoin": { + "$ref": "#/definitions/border" + }, + "joinMiddleUp": { + "$ref": "#/definitions/border" + }, + "joinMiddleDown": { + "$ref": "#/definitions/border" + }, + "joinMiddleLeft": { + "$ref": "#/definitions/border" + }, + "joinMiddleRight": { + "$ref": "#/definitions/border" + } + }, + "additionalProperties": false + }; + const func8 = Object.prototype.hasOwnProperty; + function validate46(data, { instancePath = "", parentData, parentDataProperty, rootData = data } = {}) { + let vErrors = null; + let errors = 0; + if (typeof data !== "string") { + const err0 = { + instancePath, + schemaPath: "#/type", + keyword: "type", + params: { + type: "string" + }, + message: "must be string" + }; + if (vErrors === null) { + vErrors = [err0]; + } + else { + vErrors.push(err0); + } + errors++; + } + validate46.errors = vErrors; + return errors === 0; + } + function validate45(data, { instancePath = "", parentData, parentDataProperty, rootData = data } = {}) { + let vErrors = null; + let errors = 0; + if (data && typeof data == "object" && !Array.isArray(data)) { + for (const key0 in data) { + if (!(func8.call(schema15.properties, key0))) { + const err0 = { + instancePath, + schemaPath: "#/additionalProperties", + keyword: "additionalProperties", + params: { + additionalProperty: key0 + }, + message: "must NOT have additional properties" + }; + if (vErrors === null) { + vErrors = [err0]; + } + else { + vErrors.push(err0); + } + errors++; + } + } + if (data.topBody !== undefined) { + if (!(validate46(data.topBody, { + instancePath: instancePath + "/topBody", + parentData: data, + parentDataProperty: "topBody", + rootData + }))) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.topJoin !== undefined) { + if (!(validate46(data.topJoin, { + instancePath: instancePath + "/topJoin", + parentData: data, + parentDataProperty: "topJoin", + rootData + }))) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.topLeft !== undefined) { + if (!(validate46(data.topLeft, { + instancePath: instancePath + "/topLeft", + parentData: data, + parentDataProperty: "topLeft", + rootData + }))) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.topRight !== undefined) { + if (!(validate46(data.topRight, { + instancePath: instancePath + "/topRight", + parentData: data, + parentDataProperty: "topRight", + rootData + }))) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.bottomBody !== undefined) { + if (!(validate46(data.bottomBody, { + instancePath: instancePath + "/bottomBody", + parentData: data, + parentDataProperty: "bottomBody", + rootData + }))) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.bottomJoin !== undefined) { + if (!(validate46(data.bottomJoin, { + instancePath: instancePath + "/bottomJoin", + parentData: data, + parentDataProperty: "bottomJoin", + rootData + }))) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.bottomLeft !== undefined) { + if (!(validate46(data.bottomLeft, { + instancePath: instancePath + "/bottomLeft", + parentData: data, + parentDataProperty: "bottomLeft", + rootData + }))) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.bottomRight !== undefined) { + if (!(validate46(data.bottomRight, { + instancePath: instancePath + "/bottomRight", + parentData: data, + parentDataProperty: "bottomRight", + rootData + }))) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.bodyLeft !== undefined) { + if (!(validate46(data.bodyLeft, { + instancePath: instancePath + "/bodyLeft", + parentData: data, + parentDataProperty: "bodyLeft", + rootData + }))) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.bodyRight !== undefined) { + if (!(validate46(data.bodyRight, { + instancePath: instancePath + "/bodyRight", + parentData: data, + parentDataProperty: "bodyRight", + rootData + }))) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.bodyJoin !== undefined) { + if (!(validate46(data.bodyJoin, { + instancePath: instancePath + "/bodyJoin", + parentData: data, + parentDataProperty: "bodyJoin", + rootData + }))) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.headerJoin !== undefined) { + if (!(validate46(data.headerJoin, { + instancePath: instancePath + "/headerJoin", + parentData: data, + parentDataProperty: "headerJoin", + rootData + }))) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.joinBody !== undefined) { + if (!(validate46(data.joinBody, { + instancePath: instancePath + "/joinBody", + parentData: data, + parentDataProperty: "joinBody", + rootData + }))) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.joinLeft !== undefined) { + if (!(validate46(data.joinLeft, { + instancePath: instancePath + "/joinLeft", + parentData: data, + parentDataProperty: "joinLeft", + rootData + }))) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.joinRight !== undefined) { + if (!(validate46(data.joinRight, { + instancePath: instancePath + "/joinRight", + parentData: data, + parentDataProperty: "joinRight", + rootData + }))) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.joinJoin !== undefined) { + if (!(validate46(data.joinJoin, { + instancePath: instancePath + "/joinJoin", + parentData: data, + parentDataProperty: "joinJoin", + rootData + }))) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.joinMiddleUp !== undefined) { + if (!(validate46(data.joinMiddleUp, { + instancePath: instancePath + "/joinMiddleUp", + parentData: data, + parentDataProperty: "joinMiddleUp", + rootData + }))) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.joinMiddleDown !== undefined) { + if (!(validate46(data.joinMiddleDown, { + instancePath: instancePath + "/joinMiddleDown", + parentData: data, + parentDataProperty: "joinMiddleDown", + rootData + }))) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.joinMiddleLeft !== undefined) { + if (!(validate46(data.joinMiddleLeft, { + instancePath: instancePath + "/joinMiddleLeft", + parentData: data, + parentDataProperty: "joinMiddleLeft", + rootData + }))) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.joinMiddleRight !== undefined) { + if (!(validate46(data.joinMiddleRight, { + instancePath: instancePath + "/joinMiddleRight", + parentData: data, + parentDataProperty: "joinMiddleRight", + rootData + }))) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + } + else { + const err1 = { + instancePath, + schemaPath: "#/type", + keyword: "type", + params: { + type: "object" + }, + message: "must be object" + }; + if (vErrors === null) { + vErrors = [err1]; + } + else { + vErrors.push(err1); + } + errors++; + } + validate45.errors = vErrors; + return errors === 0; + } + const schema17 = { + "type": "string", + "enum": ["left", "right", "center", "justify"] + }; + equal$1.default; + function validate68(data, { instancePath = "", parentData, parentDataProperty, rootData = data } = {}) { + let vErrors = null; + let errors = 0; + if (typeof data !== "string") { + const err0 = { + instancePath, + schemaPath: "#/type", + keyword: "type", + params: { + type: "string" + }, + message: "must be string" + }; + if (vErrors === null) { + vErrors = [err0]; + } + else { + vErrors.push(err0); + } + errors++; + } + if (!((((data === "left") || (data === "right")) || (data === "center")) || (data === "justify"))) { + const err1 = { + instancePath, + schemaPath: "#/enum", + keyword: "enum", + params: { + allowedValues: schema17.enum + }, + message: "must be equal to one of the allowed values" + }; + if (vErrors === null) { + vErrors = [err1]; + } + else { + vErrors.push(err1); + } + errors++; + } + validate68.errors = vErrors; + return errors === 0; + } + const pattern0 = new RegExp("^[0-9]+$", "u"); + function validate72(data, { instancePath = "", parentData, parentDataProperty, rootData = data } = {}) { + let vErrors = null; + let errors = 0; + if (typeof data !== "string") { + const err0 = { + instancePath, + schemaPath: "#/type", + keyword: "type", + params: { + type: "string" + }, + message: "must be string" + }; + if (vErrors === null) { + vErrors = [err0]; + } + else { + vErrors.push(err0); + } + errors++; + } + if (!((((data === "left") || (data === "right")) || (data === "center")) || (data === "justify"))) { + const err1 = { + instancePath, + schemaPath: "#/enum", + keyword: "enum", + params: { + allowedValues: schema17.enum + }, + message: "must be equal to one of the allowed values" + }; + if (vErrors === null) { + vErrors = [err1]; + } + else { + vErrors.push(err1); + } + errors++; + } + validate72.errors = vErrors; + return errors === 0; + } + const schema21 = { + "type": "string", + "enum": ["top", "middle", "bottom"] + }; + function validate74(data, { instancePath = "", parentData, parentDataProperty, rootData = data } = {}) { + let vErrors = null; + let errors = 0; + if (typeof data !== "string") { + const err0 = { + instancePath, + schemaPath: "#/type", + keyword: "type", + params: { + type: "string" + }, + message: "must be string" + }; + if (vErrors === null) { + vErrors = [err0]; + } + else { + vErrors.push(err0); + } + errors++; + } + if (!(((data === "top") || (data === "middle")) || (data === "bottom"))) { + const err1 = { + instancePath, + schemaPath: "#/enum", + keyword: "enum", + params: { + allowedValues: schema21.enum + }, + message: "must be equal to one of the allowed values" + }; + if (vErrors === null) { + vErrors = [err1]; + } + else { + vErrors.push(err1); + } + errors++; + } + validate74.errors = vErrors; + return errors === 0; + } + function validate71(data, { instancePath = "", parentData, parentDataProperty, rootData = data } = {}) { + let vErrors = null; + let errors = 0; + if (data && typeof data == "object" && !Array.isArray(data)) { + for (const key0 in data) { + if (!(((((((key0 === "alignment") || (key0 === "verticalAlignment")) || (key0 === "width")) || (key0 === "wrapWord")) || (key0 === "truncate")) || (key0 === "paddingLeft")) || (key0 === "paddingRight"))) { + const err0 = { + instancePath, + schemaPath: "#/additionalProperties", + keyword: "additionalProperties", + params: { + additionalProperty: key0 + }, + message: "must NOT have additional properties" + }; + if (vErrors === null) { + vErrors = [err0]; + } + else { + vErrors.push(err0); + } + errors++; + } + } + if (data.alignment !== undefined) { + if (!(validate72(data.alignment, { + instancePath: instancePath + "/alignment", + parentData: data, + parentDataProperty: "alignment", + rootData + }))) { + vErrors = vErrors === null ? validate72.errors : vErrors.concat(validate72.errors); + errors = vErrors.length; + } + } + if (data.verticalAlignment !== undefined) { + if (!(validate74(data.verticalAlignment, { + instancePath: instancePath + "/verticalAlignment", + parentData: data, + parentDataProperty: "verticalAlignment", + rootData + }))) { + vErrors = vErrors === null ? validate74.errors : vErrors.concat(validate74.errors); + errors = vErrors.length; + } + } + if (data.width !== undefined) { + let data2 = data.width; + if (!(((typeof data2 == "number") && (!(data2 % 1) && !isNaN(data2))) && (isFinite(data2)))) { + const err1 = { + instancePath: instancePath + "/width", + schemaPath: "#/properties/width/type", + keyword: "type", + params: { + type: "integer" + }, + message: "must be integer" + }; + if (vErrors === null) { + vErrors = [err1]; + } + else { + vErrors.push(err1); + } + errors++; + } + if ((typeof data2 == "number") && (isFinite(data2))) { + if (data2 < 1 || isNaN(data2)) { + const err2 = { + instancePath: instancePath + "/width", + schemaPath: "#/properties/width/minimum", + keyword: "minimum", + params: { + comparison: ">=", + limit: 1 + }, + message: "must be >= 1" + }; + if (vErrors === null) { + vErrors = [err2]; + } + else { + vErrors.push(err2); + } + errors++; + } + } + } + if (data.wrapWord !== undefined) { + if (typeof data.wrapWord !== "boolean") { + const err3 = { + instancePath: instancePath + "/wrapWord", + schemaPath: "#/properties/wrapWord/type", + keyword: "type", + params: { + type: "boolean" + }, + message: "must be boolean" + }; + if (vErrors === null) { + vErrors = [err3]; + } + else { + vErrors.push(err3); + } + errors++; + } + } + if (data.truncate !== undefined) { + let data4 = data.truncate; + if (!(((typeof data4 == "number") && (!(data4 % 1) && !isNaN(data4))) && (isFinite(data4)))) { + const err4 = { + instancePath: instancePath + "/truncate", + schemaPath: "#/properties/truncate/type", + keyword: "type", + params: { + type: "integer" + }, + message: "must be integer" + }; + if (vErrors === null) { + vErrors = [err4]; + } + else { + vErrors.push(err4); + } + errors++; + } + } + if (data.paddingLeft !== undefined) { + let data5 = data.paddingLeft; + if (!(((typeof data5 == "number") && (!(data5 % 1) && !isNaN(data5))) && (isFinite(data5)))) { + const err5 = { + instancePath: instancePath + "/paddingLeft", + schemaPath: "#/properties/paddingLeft/type", + keyword: "type", + params: { + type: "integer" + }, + message: "must be integer" + }; + if (vErrors === null) { + vErrors = [err5]; + } + else { + vErrors.push(err5); + } + errors++; + } + } + if (data.paddingRight !== undefined) { + let data6 = data.paddingRight; + if (!(((typeof data6 == "number") && (!(data6 % 1) && !isNaN(data6))) && (isFinite(data6)))) { + const err6 = { + instancePath: instancePath + "/paddingRight", + schemaPath: "#/properties/paddingRight/type", + keyword: "type", + params: { + type: "integer" + }, + message: "must be integer" + }; + if (vErrors === null) { + vErrors = [err6]; + } + else { + vErrors.push(err6); + } + errors++; + } + } + } + else { + const err7 = { + instancePath, + schemaPath: "#/type", + keyword: "type", + params: { + type: "object" + }, + message: "must be object" + }; + if (vErrors === null) { + vErrors = [err7]; + } + else { + vErrors.push(err7); + } + errors++; + } + validate71.errors = vErrors; + return errors === 0; + } + function validate70(data, { instancePath = "", parentData, parentDataProperty, rootData = data } = {}) { + let vErrors = null; + let errors = 0; + const _errs0 = errors; + let valid0 = false; + let passing0 = null; + const _errs1 = errors; + if (data && typeof data == "object" && !Array.isArray(data)) { + for (const key0 in data) { + if (!(pattern0.test(key0))) { + const err0 = { + instancePath, + schemaPath: "#/oneOf/0/additionalProperties", + keyword: "additionalProperties", + params: { + additionalProperty: key0 + }, + message: "must NOT have additional properties" + }; + if (vErrors === null) { + vErrors = [err0]; + } + else { + vErrors.push(err0); + } + errors++; + } + } + for (const key1 in data) { + if (pattern0.test(key1)) { + if (!(validate71(data[key1], { + instancePath: instancePath + "/" + key1.replace(/~/g, "~0").replace(/\//g, "~1"), + parentData: data, + parentDataProperty: key1, + rootData + }))) { + vErrors = vErrors === null ? validate71.errors : vErrors.concat(validate71.errors); + errors = vErrors.length; + } + } + } + } + else { + const err1 = { + instancePath, + schemaPath: "#/oneOf/0/type", + keyword: "type", + params: { + type: "object" + }, + message: "must be object" + }; + if (vErrors === null) { + vErrors = [err1]; + } + else { + vErrors.push(err1); + } + errors++; + } + var _valid0 = _errs1 === errors; + if (_valid0) { + valid0 = true; + passing0 = 0; + } + const _errs5 = errors; + if (Array.isArray(data)) { + const len0 = data.length; + for (let i0 = 0; i0 < len0; i0++) { + if (!(validate71(data[i0], { + instancePath: instancePath + "/" + i0, + parentData: data, + parentDataProperty: i0, + rootData + }))) { + vErrors = vErrors === null ? validate71.errors : vErrors.concat(validate71.errors); + errors = vErrors.length; + } + } + } + else { + const err2 = { + instancePath, + schemaPath: "#/oneOf/1/type", + keyword: "type", + params: { + type: "array" + }, + message: "must be array" + }; + if (vErrors === null) { + vErrors = [err2]; + } + else { + vErrors.push(err2); + } + errors++; + } + var _valid0 = _errs5 === errors; + if (_valid0 && valid0) { + valid0 = false; + passing0 = [passing0, 1]; + } + else { + if (_valid0) { + valid0 = true; + passing0 = 1; + } + } + if (!valid0) { + const err3 = { + instancePath, + schemaPath: "#/oneOf", + keyword: "oneOf", + params: { + passingSchemas: passing0 + }, + message: "must match exactly one schema in oneOf" + }; + if (vErrors === null) { + vErrors = [err3]; + } + else { + vErrors.push(err3); + } + errors++; + } + else { + errors = _errs0; + if (vErrors !== null) { + if (_errs0) { + vErrors.length = _errs0; + } + else { + vErrors = null; + } + } + } + validate70.errors = vErrors; + return errors === 0; + } + function validate79(data, { instancePath = "", parentData, parentDataProperty, rootData = data } = {}) { + let vErrors = null; + let errors = 0; + if (data && typeof data == "object" && !Array.isArray(data)) { + for (const key0 in data) { + if (!(((((((key0 === "alignment") || (key0 === "verticalAlignment")) || (key0 === "width")) || (key0 === "wrapWord")) || (key0 === "truncate")) || (key0 === "paddingLeft")) || (key0 === "paddingRight"))) { + const err0 = { + instancePath, + schemaPath: "#/additionalProperties", + keyword: "additionalProperties", + params: { + additionalProperty: key0 + }, + message: "must NOT have additional properties" + }; + if (vErrors === null) { + vErrors = [err0]; + } + else { + vErrors.push(err0); + } + errors++; + } + } + if (data.alignment !== undefined) { + if (!(validate72(data.alignment, { + instancePath: instancePath + "/alignment", + parentData: data, + parentDataProperty: "alignment", + rootData + }))) { + vErrors = vErrors === null ? validate72.errors : vErrors.concat(validate72.errors); + errors = vErrors.length; + } + } + if (data.verticalAlignment !== undefined) { + if (!(validate74(data.verticalAlignment, { + instancePath: instancePath + "/verticalAlignment", + parentData: data, + parentDataProperty: "verticalAlignment", + rootData + }))) { + vErrors = vErrors === null ? validate74.errors : vErrors.concat(validate74.errors); + errors = vErrors.length; + } + } + if (data.width !== undefined) { + let data2 = data.width; + if (!(((typeof data2 == "number") && (!(data2 % 1) && !isNaN(data2))) && (isFinite(data2)))) { + const err1 = { + instancePath: instancePath + "/width", + schemaPath: "#/properties/width/type", + keyword: "type", + params: { + type: "integer" + }, + message: "must be integer" + }; + if (vErrors === null) { + vErrors = [err1]; + } + else { + vErrors.push(err1); + } + errors++; + } + if ((typeof data2 == "number") && (isFinite(data2))) { + if (data2 < 1 || isNaN(data2)) { + const err2 = { + instancePath: instancePath + "/width", + schemaPath: "#/properties/width/minimum", + keyword: "minimum", + params: { + comparison: ">=", + limit: 1 + }, + message: "must be >= 1" + }; + if (vErrors === null) { + vErrors = [err2]; + } + else { + vErrors.push(err2); + } + errors++; + } + } + } + if (data.wrapWord !== undefined) { + if (typeof data.wrapWord !== "boolean") { + const err3 = { + instancePath: instancePath + "/wrapWord", + schemaPath: "#/properties/wrapWord/type", + keyword: "type", + params: { + type: "boolean" + }, + message: "must be boolean" + }; + if (vErrors === null) { + vErrors = [err3]; + } + else { + vErrors.push(err3); + } + errors++; + } + } + if (data.truncate !== undefined) { + let data4 = data.truncate; + if (!(((typeof data4 == "number") && (!(data4 % 1) && !isNaN(data4))) && (isFinite(data4)))) { + const err4 = { + instancePath: instancePath + "/truncate", + schemaPath: "#/properties/truncate/type", + keyword: "type", + params: { + type: "integer" + }, + message: "must be integer" + }; + if (vErrors === null) { + vErrors = [err4]; + } + else { + vErrors.push(err4); + } + errors++; + } + } + if (data.paddingLeft !== undefined) { + let data5 = data.paddingLeft; + if (!(((typeof data5 == "number") && (!(data5 % 1) && !isNaN(data5))) && (isFinite(data5)))) { + const err5 = { + instancePath: instancePath + "/paddingLeft", + schemaPath: "#/properties/paddingLeft/type", + keyword: "type", + params: { + type: "integer" + }, + message: "must be integer" + }; + if (vErrors === null) { + vErrors = [err5]; + } + else { + vErrors.push(err5); + } + errors++; + } + } + if (data.paddingRight !== undefined) { + let data6 = data.paddingRight; + if (!(((typeof data6 == "number") && (!(data6 % 1) && !isNaN(data6))) && (isFinite(data6)))) { + const err6 = { + instancePath: instancePath + "/paddingRight", + schemaPath: "#/properties/paddingRight/type", + keyword: "type", + params: { + type: "integer" + }, + message: "must be integer" + }; + if (vErrors === null) { + vErrors = [err6]; + } + else { + vErrors.push(err6); + } + errors++; + } + } + } + else { + const err7 = { + instancePath, + schemaPath: "#/type", + keyword: "type", + params: { + type: "object" + }, + message: "must be object" + }; + if (vErrors === null) { + vErrors = [err7]; + } + else { + vErrors.push(err7); + } + errors++; + } + validate79.errors = vErrors; + return errors === 0; + } + function validate84(data, { instancePath = "", parentData, parentDataProperty, rootData = data } = {}) { + let vErrors = null; + let errors = 0; + if (typeof data !== "string") { + const err0 = { + instancePath, + schemaPath: "#/type", + keyword: "type", + params: { + type: "string" + }, + message: "must be string" + }; + if (vErrors === null) { + vErrors = [err0]; + } + else { + vErrors.push(err0); + } + errors++; + } + if (!(((data === "top") || (data === "middle")) || (data === "bottom"))) { + const err1 = { + instancePath, + schemaPath: "#/enum", + keyword: "enum", + params: { + allowedValues: schema21.enum + }, + message: "must be equal to one of the allowed values" + }; + if (vErrors === null) { + vErrors = [err1]; + } + else { + vErrors.push(err1); + } + errors++; + } + validate84.errors = vErrors; + return errors === 0; + } + function validate43(data, { instancePath = "", parentData, parentDataProperty, rootData = data } = {}) { + let vErrors = null; + let errors = 0; + if (data && typeof data == "object" && !Array.isArray(data)) { + for (const key0 in data) { + if (!((((((((key0 === "border") || (key0 === "header")) || (key0 === "columns")) || (key0 === "columnDefault")) || (key0 === "drawVerticalLine")) || (key0 === "drawHorizontalLine")) || (key0 === "singleLine")) || (key0 === "spanningCells"))) { + const err0 = { + instancePath, + schemaPath: "#/additionalProperties", + keyword: "additionalProperties", + params: { + additionalProperty: key0 + }, + message: "must NOT have additional properties" + }; + if (vErrors === null) { + vErrors = [err0]; + } + else { + vErrors.push(err0); + } + errors++; + } + } + if (data.border !== undefined) { + if (!(validate45(data.border, { + instancePath: instancePath + "/border", + parentData: data, + parentDataProperty: "border", + rootData + }))) { + vErrors = vErrors === null ? validate45.errors : vErrors.concat(validate45.errors); + errors = vErrors.length; + } + } + if (data.header !== undefined) { + let data1 = data.header; + if (data1 && typeof data1 == "object" && !Array.isArray(data1)) { + if (data1.content === undefined) { + const err1 = { + instancePath: instancePath + "/header", + schemaPath: "#/properties/header/required", + keyword: "required", + params: { + missingProperty: "content" + }, + message: "must have required property '" + "content" + "'" + }; + if (vErrors === null) { + vErrors = [err1]; + } + else { + vErrors.push(err1); + } + errors++; + } + for (const key1 in data1) { + if (!((((((key1 === "content") || (key1 === "alignment")) || (key1 === "wrapWord")) || (key1 === "truncate")) || (key1 === "paddingLeft")) || (key1 === "paddingRight"))) { + const err2 = { + instancePath: instancePath + "/header", + schemaPath: "#/properties/header/additionalProperties", + keyword: "additionalProperties", + params: { + additionalProperty: key1 + }, + message: "must NOT have additional properties" + }; + if (vErrors === null) { + vErrors = [err2]; + } + else { + vErrors.push(err2); + } + errors++; + } + } + if (data1.content !== undefined) { + if (typeof data1.content !== "string") { + const err3 = { + instancePath: instancePath + "/header/content", + schemaPath: "#/properties/header/properties/content/type", + keyword: "type", + params: { + type: "string" + }, + message: "must be string" + }; + if (vErrors === null) { + vErrors = [err3]; + } + else { + vErrors.push(err3); + } + errors++; + } + } + if (data1.alignment !== undefined) { + if (!(validate68(data1.alignment, { + instancePath: instancePath + "/header/alignment", + parentData: data1, + parentDataProperty: "alignment", + rootData + }))) { + vErrors = vErrors === null ? validate68.errors : vErrors.concat(validate68.errors); + errors = vErrors.length; + } + } + if (data1.wrapWord !== undefined) { + if (typeof data1.wrapWord !== "boolean") { + const err4 = { + instancePath: instancePath + "/header/wrapWord", + schemaPath: "#/properties/header/properties/wrapWord/type", + keyword: "type", + params: { + type: "boolean" + }, + message: "must be boolean" + }; + if (vErrors === null) { + vErrors = [err4]; + } + else { + vErrors.push(err4); + } + errors++; + } + } + if (data1.truncate !== undefined) { + let data5 = data1.truncate; + if (!(((typeof data5 == "number") && (!(data5 % 1) && !isNaN(data5))) && (isFinite(data5)))) { + const err5 = { + instancePath: instancePath + "/header/truncate", + schemaPath: "#/properties/header/properties/truncate/type", + keyword: "type", + params: { + type: "integer" + }, + message: "must be integer" + }; + if (vErrors === null) { + vErrors = [err5]; + } + else { + vErrors.push(err5); + } + errors++; + } + } + if (data1.paddingLeft !== undefined) { + let data6 = data1.paddingLeft; + if (!(((typeof data6 == "number") && (!(data6 % 1) && !isNaN(data6))) && (isFinite(data6)))) { + const err6 = { + instancePath: instancePath + "/header/paddingLeft", + schemaPath: "#/properties/header/properties/paddingLeft/type", + keyword: "type", + params: { + type: "integer" + }, + message: "must be integer" + }; + if (vErrors === null) { + vErrors = [err6]; + } + else { + vErrors.push(err6); + } + errors++; + } + } + if (data1.paddingRight !== undefined) { + let data7 = data1.paddingRight; + if (!(((typeof data7 == "number") && (!(data7 % 1) && !isNaN(data7))) && (isFinite(data7)))) { + const err7 = { + instancePath: instancePath + "/header/paddingRight", + schemaPath: "#/properties/header/properties/paddingRight/type", + keyword: "type", + params: { + type: "integer" + }, + message: "must be integer" + }; + if (vErrors === null) { + vErrors = [err7]; + } + else { + vErrors.push(err7); + } + errors++; + } + } + } + else { + const err8 = { + instancePath: instancePath + "/header", + schemaPath: "#/properties/header/type", + keyword: "type", + params: { + type: "object" + }, + message: "must be object" + }; + if (vErrors === null) { + vErrors = [err8]; + } + else { + vErrors.push(err8); + } + errors++; + } + } + if (data.columns !== undefined) { + if (!(validate70(data.columns, { + instancePath: instancePath + "/columns", + parentData: data, + parentDataProperty: "columns", + rootData + }))) { + vErrors = vErrors === null ? validate70.errors : vErrors.concat(validate70.errors); + errors = vErrors.length; + } + } + if (data.columnDefault !== undefined) { + if (!(validate79(data.columnDefault, { + instancePath: instancePath + "/columnDefault", + parentData: data, + parentDataProperty: "columnDefault", + rootData + }))) { + vErrors = vErrors === null ? validate79.errors : vErrors.concat(validate79.errors); + errors = vErrors.length; + } + } + if (data.drawVerticalLine !== undefined) { + if (typeof data.drawVerticalLine != "function") { + const err9 = { + instancePath: instancePath + "/drawVerticalLine", + schemaPath: "#/properties/drawVerticalLine/typeof", + keyword: "typeof", + params: {}, + message: "must pass \"typeof\" keyword validation" + }; + if (vErrors === null) { + vErrors = [err9]; + } + else { + vErrors.push(err9); + } + errors++; + } + } + if (data.drawHorizontalLine !== undefined) { + if (typeof data.drawHorizontalLine != "function") { + const err10 = { + instancePath: instancePath + "/drawHorizontalLine", + schemaPath: "#/properties/drawHorizontalLine/typeof", + keyword: "typeof", + params: {}, + message: "must pass \"typeof\" keyword validation" + }; + if (vErrors === null) { + vErrors = [err10]; + } + else { + vErrors.push(err10); + } + errors++; + } + } + if (data.singleLine !== undefined) { + if (typeof data.singleLine != "boolean") { + const err11 = { + instancePath: instancePath + "/singleLine", + schemaPath: "#/properties/singleLine/typeof", + keyword: "typeof", + params: {}, + message: "must pass \"typeof\" keyword validation" + }; + if (vErrors === null) { + vErrors = [err11]; + } + else { + vErrors.push(err11); + } + errors++; + } + } + if (data.spanningCells !== undefined) { + let data13 = data.spanningCells; + if (Array.isArray(data13)) { + const len0 = data13.length; + for (let i0 = 0; i0 < len0; i0++) { + let data14 = data13[i0]; + if (data14 && typeof data14 == "object" && !Array.isArray(data14)) { + if (data14.row === undefined) { + const err12 = { + instancePath: instancePath + "/spanningCells/" + i0, + schemaPath: "#/properties/spanningCells/items/required", + keyword: "required", + params: { + missingProperty: "row" + }, + message: "must have required property '" + "row" + "'" + }; + if (vErrors === null) { + vErrors = [err12]; + } + else { + vErrors.push(err12); + } + errors++; + } + if (data14.col === undefined) { + const err13 = { + instancePath: instancePath + "/spanningCells/" + i0, + schemaPath: "#/properties/spanningCells/items/required", + keyword: "required", + params: { + missingProperty: "col" + }, + message: "must have required property '" + "col" + "'" + }; + if (vErrors === null) { + vErrors = [err13]; + } + else { + vErrors.push(err13); + } + errors++; + } + for (const key2 in data14) { + if (!(func8.call(schema13.properties.spanningCells.items.properties, key2))) { + const err14 = { + instancePath: instancePath + "/spanningCells/" + i0, + schemaPath: "#/properties/spanningCells/items/additionalProperties", + keyword: "additionalProperties", + params: { + additionalProperty: key2 + }, + message: "must NOT have additional properties" + }; + if (vErrors === null) { + vErrors = [err14]; + } + else { + vErrors.push(err14); + } + errors++; + } + } + if (data14.col !== undefined) { + let data15 = data14.col; + if (!(((typeof data15 == "number") && (!(data15 % 1) && !isNaN(data15))) && (isFinite(data15)))) { + const err15 = { + instancePath: instancePath + "/spanningCells/" + i0 + "/col", + schemaPath: "#/properties/spanningCells/items/properties/col/type", + keyword: "type", + params: { + type: "integer" + }, + message: "must be integer" + }; + if (vErrors === null) { + vErrors = [err15]; + } + else { + vErrors.push(err15); + } + errors++; + } + if ((typeof data15 == "number") && (isFinite(data15))) { + if (data15 < 0 || isNaN(data15)) { + const err16 = { + instancePath: instancePath + "/spanningCells/" + i0 + "/col", + schemaPath: "#/properties/spanningCells/items/properties/col/minimum", + keyword: "minimum", + params: { + comparison: ">=", + limit: 0 + }, + message: "must be >= 0" + }; + if (vErrors === null) { + vErrors = [err16]; + } + else { + vErrors.push(err16); + } + errors++; + } + } + } + if (data14.row !== undefined) { + let data16 = data14.row; + if (!(((typeof data16 == "number") && (!(data16 % 1) && !isNaN(data16))) && (isFinite(data16)))) { + const err17 = { + instancePath: instancePath + "/spanningCells/" + i0 + "/row", + schemaPath: "#/properties/spanningCells/items/properties/row/type", + keyword: "type", + params: { + type: "integer" + }, + message: "must be integer" + }; + if (vErrors === null) { + vErrors = [err17]; + } + else { + vErrors.push(err17); + } + errors++; + } + if ((typeof data16 == "number") && (isFinite(data16))) { + if (data16 < 0 || isNaN(data16)) { + const err18 = { + instancePath: instancePath + "/spanningCells/" + i0 + "/row", + schemaPath: "#/properties/spanningCells/items/properties/row/minimum", + keyword: "minimum", + params: { + comparison: ">=", + limit: 0 + }, + message: "must be >= 0" + }; + if (vErrors === null) { + vErrors = [err18]; + } + else { + vErrors.push(err18); + } + errors++; + } + } + } + if (data14.colSpan !== undefined) { + let data17 = data14.colSpan; + if (!(((typeof data17 == "number") && (!(data17 % 1) && !isNaN(data17))) && (isFinite(data17)))) { + const err19 = { + instancePath: instancePath + "/spanningCells/" + i0 + "/colSpan", + schemaPath: "#/properties/spanningCells/items/properties/colSpan/type", + keyword: "type", + params: { + type: "integer" + }, + message: "must be integer" + }; + if (vErrors === null) { + vErrors = [err19]; + } + else { + vErrors.push(err19); + } + errors++; + } + if ((typeof data17 == "number") && (isFinite(data17))) { + if (data17 < 1 || isNaN(data17)) { + const err20 = { + instancePath: instancePath + "/spanningCells/" + i0 + "/colSpan", + schemaPath: "#/properties/spanningCells/items/properties/colSpan/minimum", + keyword: "minimum", + params: { + comparison: ">=", + limit: 1 + }, + message: "must be >= 1" + }; + if (vErrors === null) { + vErrors = [err20]; + } + else { + vErrors.push(err20); + } + errors++; + } + } + } + if (data14.rowSpan !== undefined) { + let data18 = data14.rowSpan; + if (!(((typeof data18 == "number") && (!(data18 % 1) && !isNaN(data18))) && (isFinite(data18)))) { + const err21 = { + instancePath: instancePath + "/spanningCells/" + i0 + "/rowSpan", + schemaPath: "#/properties/spanningCells/items/properties/rowSpan/type", + keyword: "type", + params: { + type: "integer" + }, + message: "must be integer" + }; + if (vErrors === null) { + vErrors = [err21]; + } + else { + vErrors.push(err21); + } + errors++; + } + if ((typeof data18 == "number") && (isFinite(data18))) { + if (data18 < 1 || isNaN(data18)) { + const err22 = { + instancePath: instancePath + "/spanningCells/" + i0 + "/rowSpan", + schemaPath: "#/properties/spanningCells/items/properties/rowSpan/minimum", + keyword: "minimum", + params: { + comparison: ">=", + limit: 1 + }, + message: "must be >= 1" + }; + if (vErrors === null) { + vErrors = [err22]; + } + else { + vErrors.push(err22); + } + errors++; + } + } + } + if (data14.alignment !== undefined) { + if (!(validate68(data14.alignment, { + instancePath: instancePath + "/spanningCells/" + i0 + "/alignment", + parentData: data14, + parentDataProperty: "alignment", + rootData + }))) { + vErrors = vErrors === null ? validate68.errors : vErrors.concat(validate68.errors); + errors = vErrors.length; + } + } + if (data14.verticalAlignment !== undefined) { + if (!(validate84(data14.verticalAlignment, { + instancePath: instancePath + "/spanningCells/" + i0 + "/verticalAlignment", + parentData: data14, + parentDataProperty: "verticalAlignment", + rootData + }))) { + vErrors = vErrors === null ? validate84.errors : vErrors.concat(validate84.errors); + errors = vErrors.length; + } + } + if (data14.wrapWord !== undefined) { + if (typeof data14.wrapWord !== "boolean") { + const err23 = { + instancePath: instancePath + "/spanningCells/" + i0 + "/wrapWord", + schemaPath: "#/properties/spanningCells/items/properties/wrapWord/type", + keyword: "type", + params: { + type: "boolean" + }, + message: "must be boolean" + }; + if (vErrors === null) { + vErrors = [err23]; + } + else { + vErrors.push(err23); + } + errors++; + } + } + if (data14.truncate !== undefined) { + let data22 = data14.truncate; + if (!(((typeof data22 == "number") && (!(data22 % 1) && !isNaN(data22))) && (isFinite(data22)))) { + const err24 = { + instancePath: instancePath + "/spanningCells/" + i0 + "/truncate", + schemaPath: "#/properties/spanningCells/items/properties/truncate/type", + keyword: "type", + params: { + type: "integer" + }, + message: "must be integer" + }; + if (vErrors === null) { + vErrors = [err24]; + } + else { + vErrors.push(err24); + } + errors++; + } + } + if (data14.paddingLeft !== undefined) { + let data23 = data14.paddingLeft; + if (!(((typeof data23 == "number") && (!(data23 % 1) && !isNaN(data23))) && (isFinite(data23)))) { + const err25 = { + instancePath: instancePath + "/spanningCells/" + i0 + "/paddingLeft", + schemaPath: "#/properties/spanningCells/items/properties/paddingLeft/type", + keyword: "type", + params: { + type: "integer" + }, + message: "must be integer" + }; + if (vErrors === null) { + vErrors = [err25]; + } + else { + vErrors.push(err25); + } + errors++; + } + } + if (data14.paddingRight !== undefined) { + let data24 = data14.paddingRight; + if (!(((typeof data24 == "number") && (!(data24 % 1) && !isNaN(data24))) && (isFinite(data24)))) { + const err26 = { + instancePath: instancePath + "/spanningCells/" + i0 + "/paddingRight", + schemaPath: "#/properties/spanningCells/items/properties/paddingRight/type", + keyword: "type", + params: { + type: "integer" + }, + message: "must be integer" + }; + if (vErrors === null) { + vErrors = [err26]; + } + else { + vErrors.push(err26); + } + errors++; + } + } + } + else { + const err27 = { + instancePath: instancePath + "/spanningCells/" + i0, + schemaPath: "#/properties/spanningCells/items/type", + keyword: "type", + params: { + type: "object" + }, + message: "must be object" + }; + if (vErrors === null) { + vErrors = [err27]; + } + else { + vErrors.push(err27); + } + errors++; + } + } + } + else { + const err28 = { + instancePath: instancePath + "/spanningCells", + schemaPath: "#/properties/spanningCells/type", + keyword: "type", + params: { + type: "array" + }, + message: "must be array" + }; + if (vErrors === null) { + vErrors = [err28]; + } + else { + vErrors.push(err28); + } + errors++; + } + } + } + else { + const err29 = { + instancePath, + schemaPath: "#/type", + keyword: "type", + params: { + type: "object" + }, + message: "must be object" + }; + if (vErrors === null) { + vErrors = [err29]; + } + else { + vErrors.push(err29); + } + errors++; + } + validate43.errors = vErrors; + return errors === 0; + } + exports["streamConfig.json"] = validate86; + function validate87(data, { instancePath = "", parentData, parentDataProperty, rootData = data } = {}) { + let vErrors = null; + let errors = 0; + if (data && typeof data == "object" && !Array.isArray(data)) { + for (const key0 in data) { + if (!(func8.call(schema15.properties, key0))) { + const err0 = { + instancePath, + schemaPath: "#/additionalProperties", + keyword: "additionalProperties", + params: { + additionalProperty: key0 + }, + message: "must NOT have additional properties" + }; + if (vErrors === null) { + vErrors = [err0]; + } + else { + vErrors.push(err0); + } + errors++; + } + } + if (data.topBody !== undefined) { + if (!(validate46(data.topBody, { + instancePath: instancePath + "/topBody", + parentData: data, + parentDataProperty: "topBody", + rootData + }))) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.topJoin !== undefined) { + if (!(validate46(data.topJoin, { + instancePath: instancePath + "/topJoin", + parentData: data, + parentDataProperty: "topJoin", + rootData + }))) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.topLeft !== undefined) { + if (!(validate46(data.topLeft, { + instancePath: instancePath + "/topLeft", + parentData: data, + parentDataProperty: "topLeft", + rootData + }))) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.topRight !== undefined) { + if (!(validate46(data.topRight, { + instancePath: instancePath + "/topRight", + parentData: data, + parentDataProperty: "topRight", + rootData + }))) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.bottomBody !== undefined) { + if (!(validate46(data.bottomBody, { + instancePath: instancePath + "/bottomBody", + parentData: data, + parentDataProperty: "bottomBody", + rootData + }))) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.bottomJoin !== undefined) { + if (!(validate46(data.bottomJoin, { + instancePath: instancePath + "/bottomJoin", + parentData: data, + parentDataProperty: "bottomJoin", + rootData + }))) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.bottomLeft !== undefined) { + if (!(validate46(data.bottomLeft, { + instancePath: instancePath + "/bottomLeft", + parentData: data, + parentDataProperty: "bottomLeft", + rootData + }))) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.bottomRight !== undefined) { + if (!(validate46(data.bottomRight, { + instancePath: instancePath + "/bottomRight", + parentData: data, + parentDataProperty: "bottomRight", + rootData + }))) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.bodyLeft !== undefined) { + if (!(validate46(data.bodyLeft, { + instancePath: instancePath + "/bodyLeft", + parentData: data, + parentDataProperty: "bodyLeft", + rootData + }))) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.bodyRight !== undefined) { + if (!(validate46(data.bodyRight, { + instancePath: instancePath + "/bodyRight", + parentData: data, + parentDataProperty: "bodyRight", + rootData + }))) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.bodyJoin !== undefined) { + if (!(validate46(data.bodyJoin, { + instancePath: instancePath + "/bodyJoin", + parentData: data, + parentDataProperty: "bodyJoin", + rootData + }))) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.headerJoin !== undefined) { + if (!(validate46(data.headerJoin, { + instancePath: instancePath + "/headerJoin", + parentData: data, + parentDataProperty: "headerJoin", + rootData + }))) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.joinBody !== undefined) { + if (!(validate46(data.joinBody, { + instancePath: instancePath + "/joinBody", + parentData: data, + parentDataProperty: "joinBody", + rootData + }))) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.joinLeft !== undefined) { + if (!(validate46(data.joinLeft, { + instancePath: instancePath + "/joinLeft", + parentData: data, + parentDataProperty: "joinLeft", + rootData + }))) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.joinRight !== undefined) { + if (!(validate46(data.joinRight, { + instancePath: instancePath + "/joinRight", + parentData: data, + parentDataProperty: "joinRight", + rootData + }))) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.joinJoin !== undefined) { + if (!(validate46(data.joinJoin, { + instancePath: instancePath + "/joinJoin", + parentData: data, + parentDataProperty: "joinJoin", + rootData + }))) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.joinMiddleUp !== undefined) { + if (!(validate46(data.joinMiddleUp, { + instancePath: instancePath + "/joinMiddleUp", + parentData: data, + parentDataProperty: "joinMiddleUp", + rootData + }))) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.joinMiddleDown !== undefined) { + if (!(validate46(data.joinMiddleDown, { + instancePath: instancePath + "/joinMiddleDown", + parentData: data, + parentDataProperty: "joinMiddleDown", + rootData + }))) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.joinMiddleLeft !== undefined) { + if (!(validate46(data.joinMiddleLeft, { + instancePath: instancePath + "/joinMiddleLeft", + parentData: data, + parentDataProperty: "joinMiddleLeft", + rootData + }))) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.joinMiddleRight !== undefined) { + if (!(validate46(data.joinMiddleRight, { + instancePath: instancePath + "/joinMiddleRight", + parentData: data, + parentDataProperty: "joinMiddleRight", + rootData + }))) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + } + else { + const err1 = { + instancePath, + schemaPath: "#/type", + keyword: "type", + params: { + type: "object" + }, + message: "must be object" + }; + if (vErrors === null) { + vErrors = [err1]; + } + else { + vErrors.push(err1); + } + errors++; + } + validate87.errors = vErrors; + return errors === 0; + } + function validate109(data, { instancePath = "", parentData, parentDataProperty, rootData = data } = {}) { + let vErrors = null; + let errors = 0; + const _errs0 = errors; + let valid0 = false; + let passing0 = null; + const _errs1 = errors; + if (data && typeof data == "object" && !Array.isArray(data)) { + for (const key0 in data) { + if (!(pattern0.test(key0))) { + const err0 = { + instancePath, + schemaPath: "#/oneOf/0/additionalProperties", + keyword: "additionalProperties", + params: { + additionalProperty: key0 + }, + message: "must NOT have additional properties" + }; + if (vErrors === null) { + vErrors = [err0]; + } + else { + vErrors.push(err0); + } + errors++; + } + } + for (const key1 in data) { + if (pattern0.test(key1)) { + if (!(validate71(data[key1], { + instancePath: instancePath + "/" + key1.replace(/~/g, "~0").replace(/\//g, "~1"), + parentData: data, + parentDataProperty: key1, + rootData + }))) { + vErrors = vErrors === null ? validate71.errors : vErrors.concat(validate71.errors); + errors = vErrors.length; + } + } + } + } + else { + const err1 = { + instancePath, + schemaPath: "#/oneOf/0/type", + keyword: "type", + params: { + type: "object" + }, + message: "must be object" + }; + if (vErrors === null) { + vErrors = [err1]; + } + else { + vErrors.push(err1); + } + errors++; + } + var _valid0 = _errs1 === errors; + if (_valid0) { + valid0 = true; + passing0 = 0; + } + const _errs5 = errors; + if (Array.isArray(data)) { + const len0 = data.length; + for (let i0 = 0; i0 < len0; i0++) { + if (!(validate71(data[i0], { + instancePath: instancePath + "/" + i0, + parentData: data, + parentDataProperty: i0, + rootData + }))) { + vErrors = vErrors === null ? validate71.errors : vErrors.concat(validate71.errors); + errors = vErrors.length; + } + } + } + else { + const err2 = { + instancePath, + schemaPath: "#/oneOf/1/type", + keyword: "type", + params: { + type: "array" + }, + message: "must be array" + }; + if (vErrors === null) { + vErrors = [err2]; + } + else { + vErrors.push(err2); + } + errors++; + } + var _valid0 = _errs5 === errors; + if (_valid0 && valid0) { + valid0 = false; + passing0 = [passing0, 1]; + } + else { + if (_valid0) { + valid0 = true; + passing0 = 1; + } + } + if (!valid0) { + const err3 = { + instancePath, + schemaPath: "#/oneOf", + keyword: "oneOf", + params: { + passingSchemas: passing0 + }, + message: "must match exactly one schema in oneOf" + }; + if (vErrors === null) { + vErrors = [err3]; + } + else { + vErrors.push(err3); + } + errors++; + } + else { + errors = _errs0; + if (vErrors !== null) { + if (_errs0) { + vErrors.length = _errs0; + } + else { + vErrors = null; + } + } + } + validate109.errors = vErrors; + return errors === 0; + } + function validate113(data, { instancePath = "", parentData, parentDataProperty, rootData = data } = {}) { + let vErrors = null; + let errors = 0; + if (data && typeof data == "object" && !Array.isArray(data)) { + for (const key0 in data) { + if (!(((((((key0 === "alignment") || (key0 === "verticalAlignment")) || (key0 === "width")) || (key0 === "wrapWord")) || (key0 === "truncate")) || (key0 === "paddingLeft")) || (key0 === "paddingRight"))) { + const err0 = { + instancePath, + schemaPath: "#/additionalProperties", + keyword: "additionalProperties", + params: { + additionalProperty: key0 + }, + message: "must NOT have additional properties" + }; + if (vErrors === null) { + vErrors = [err0]; + } + else { + vErrors.push(err0); + } + errors++; + } + } + if (data.alignment !== undefined) { + if (!(validate72(data.alignment, { + instancePath: instancePath + "/alignment", + parentData: data, + parentDataProperty: "alignment", + rootData + }))) { + vErrors = vErrors === null ? validate72.errors : vErrors.concat(validate72.errors); + errors = vErrors.length; + } + } + if (data.verticalAlignment !== undefined) { + if (!(validate74(data.verticalAlignment, { + instancePath: instancePath + "/verticalAlignment", + parentData: data, + parentDataProperty: "verticalAlignment", + rootData + }))) { + vErrors = vErrors === null ? validate74.errors : vErrors.concat(validate74.errors); + errors = vErrors.length; + } + } + if (data.width !== undefined) { + let data2 = data.width; + if (!(((typeof data2 == "number") && (!(data2 % 1) && !isNaN(data2))) && (isFinite(data2)))) { + const err1 = { + instancePath: instancePath + "/width", + schemaPath: "#/properties/width/type", + keyword: "type", + params: { + type: "integer" + }, + message: "must be integer" + }; + if (vErrors === null) { + vErrors = [err1]; + } + else { + vErrors.push(err1); + } + errors++; + } + if ((typeof data2 == "number") && (isFinite(data2))) { + if (data2 < 1 || isNaN(data2)) { + const err2 = { + instancePath: instancePath + "/width", + schemaPath: "#/properties/width/minimum", + keyword: "minimum", + params: { + comparison: ">=", + limit: 1 + }, + message: "must be >= 1" + }; + if (vErrors === null) { + vErrors = [err2]; + } + else { + vErrors.push(err2); + } + errors++; + } + } + } + if (data.wrapWord !== undefined) { + if (typeof data.wrapWord !== "boolean") { + const err3 = { + instancePath: instancePath + "/wrapWord", + schemaPath: "#/properties/wrapWord/type", + keyword: "type", + params: { + type: "boolean" + }, + message: "must be boolean" + }; + if (vErrors === null) { + vErrors = [err3]; + } + else { + vErrors.push(err3); + } + errors++; + } + } + if (data.truncate !== undefined) { + let data4 = data.truncate; + if (!(((typeof data4 == "number") && (!(data4 % 1) && !isNaN(data4))) && (isFinite(data4)))) { + const err4 = { + instancePath: instancePath + "/truncate", + schemaPath: "#/properties/truncate/type", + keyword: "type", + params: { + type: "integer" + }, + message: "must be integer" + }; + if (vErrors === null) { + vErrors = [err4]; + } + else { + vErrors.push(err4); + } + errors++; + } + } + if (data.paddingLeft !== undefined) { + let data5 = data.paddingLeft; + if (!(((typeof data5 == "number") && (!(data5 % 1) && !isNaN(data5))) && (isFinite(data5)))) { + const err5 = { + instancePath: instancePath + "/paddingLeft", + schemaPath: "#/properties/paddingLeft/type", + keyword: "type", + params: { + type: "integer" + }, + message: "must be integer" + }; + if (vErrors === null) { + vErrors = [err5]; + } + else { + vErrors.push(err5); + } + errors++; + } + } + if (data.paddingRight !== undefined) { + let data6 = data.paddingRight; + if (!(((typeof data6 == "number") && (!(data6 % 1) && !isNaN(data6))) && (isFinite(data6)))) { + const err6 = { + instancePath: instancePath + "/paddingRight", + schemaPath: "#/properties/paddingRight/type", + keyword: "type", + params: { + type: "integer" + }, + message: "must be integer" + }; + if (vErrors === null) { + vErrors = [err6]; + } + else { + vErrors.push(err6); + } + errors++; + } + } + } + else { + const err7 = { + instancePath, + schemaPath: "#/type", + keyword: "type", + params: { + type: "object" + }, + message: "must be object" + }; + if (vErrors === null) { + vErrors = [err7]; + } + else { + vErrors.push(err7); + } + errors++; + } + validate113.errors = vErrors; + return errors === 0; + } + function validate86(data, { instancePath = "", parentData, parentDataProperty, rootData = data } = {}) { + let vErrors = null; + let errors = 0; + if (data && typeof data == "object" && !Array.isArray(data)) { + if (data.columnDefault === undefined) { + const err0 = { + instancePath, + schemaPath: "#/required", + keyword: "required", + params: { + missingProperty: "columnDefault" + }, + message: "must have required property '" + "columnDefault" + "'" + }; + if (vErrors === null) { + vErrors = [err0]; + } + else { + vErrors.push(err0); + } + errors++; + } + if (data.columnCount === undefined) { + const err1 = { + instancePath, + schemaPath: "#/required", + keyword: "required", + params: { + missingProperty: "columnCount" + }, + message: "must have required property '" + "columnCount" + "'" + }; + if (vErrors === null) { + vErrors = [err1]; + } + else { + vErrors.push(err1); + } + errors++; + } + for (const key0 in data) { + if (!(((((key0 === "border") || (key0 === "columns")) || (key0 === "columnDefault")) || (key0 === "columnCount")) || (key0 === "drawVerticalLine"))) { + const err2 = { + instancePath, + schemaPath: "#/additionalProperties", + keyword: "additionalProperties", + params: { + additionalProperty: key0 + }, + message: "must NOT have additional properties" + }; + if (vErrors === null) { + vErrors = [err2]; + } + else { + vErrors.push(err2); + } + errors++; + } + } + if (data.border !== undefined) { + if (!(validate87(data.border, { + instancePath: instancePath + "/border", + parentData: data, + parentDataProperty: "border", + rootData + }))) { + vErrors = vErrors === null ? validate87.errors : vErrors.concat(validate87.errors); + errors = vErrors.length; + } + } + if (data.columns !== undefined) { + if (!(validate109(data.columns, { + instancePath: instancePath + "/columns", + parentData: data, + parentDataProperty: "columns", + rootData + }))) { + vErrors = vErrors === null ? validate109.errors : vErrors.concat(validate109.errors); + errors = vErrors.length; + } + } + if (data.columnDefault !== undefined) { + if (!(validate113(data.columnDefault, { + instancePath: instancePath + "/columnDefault", + parentData: data, + parentDataProperty: "columnDefault", + rootData + }))) { + vErrors = vErrors === null ? validate113.errors : vErrors.concat(validate113.errors); + errors = vErrors.length; + } + } + if (data.columnCount !== undefined) { + let data3 = data.columnCount; + if (!(((typeof data3 == "number") && (!(data3 % 1) && !isNaN(data3))) && (isFinite(data3)))) { + const err3 = { + instancePath: instancePath + "/columnCount", + schemaPath: "#/properties/columnCount/type", + keyword: "type", + params: { + type: "integer" + }, + message: "must be integer" + }; + if (vErrors === null) { + vErrors = [err3]; + } + else { + vErrors.push(err3); + } + errors++; + } + if ((typeof data3 == "number") && (isFinite(data3))) { + if (data3 < 1 || isNaN(data3)) { + const err4 = { + instancePath: instancePath + "/columnCount", + schemaPath: "#/properties/columnCount/minimum", + keyword: "minimum", + params: { + comparison: ">=", + limit: 1 + }, + message: "must be >= 1" + }; + if (vErrors === null) { + vErrors = [err4]; + } + else { + vErrors.push(err4); + } + errors++; + } + } + } + if (data.drawVerticalLine !== undefined) { + if (typeof data.drawVerticalLine != "function") { + const err5 = { + instancePath: instancePath + "/drawVerticalLine", + schemaPath: "#/properties/drawVerticalLine/typeof", + keyword: "typeof", + params: {}, + message: "must pass \"typeof\" keyword validation" + }; + if (vErrors === null) { + vErrors = [err5]; + } + else { + vErrors.push(err5); + } + errors++; + } + } + } + else { + const err6 = { + instancePath, + schemaPath: "#/type", + keyword: "type", + params: { + type: "object" + }, + message: "must be object" + }; + if (vErrors === null) { + vErrors = [err6]; + } + else { + vErrors.push(err6); + } + errors++; + } + validate86.errors = vErrors; + return errors === 0; + } + +} (validators)); + +var __importDefault$1 = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(validateConfig$1, "__esModule", { value: true }); +validateConfig$1.validateConfig = void 0; +const validators_1 = __importDefault$1(validators); +const validateConfig = (schemaId, config) => { + const validate = validators_1.default[schemaId]; + if (!validate(config) && validate.errors) { + // eslint-disable-next-line promise/prefer-await-to-callbacks + const errors = validate.errors.map((error) => { + return { + message: error.message, + params: error.params, + schemaPath: error.schemaPath, + }; + }); + /* eslint-disable no-console */ + console.log('config', config); + console.log('errors', errors); + /* eslint-enable no-console */ + throw new Error('Invalid config.'); + } +}; +validateConfig$1.validateConfig = validateConfig; + +Object.defineProperty(makeStreamConfig$1, "__esModule", { value: true }); +makeStreamConfig$1.makeStreamConfig = void 0; +const utils_1$b = utils$1; +const validateConfig_1$1 = validateConfig$1; +/** + * Creates a configuration for every column using default + * values for the missing configuration properties. + */ +const makeColumnsConfig$1 = (columnCount, columns = {}, columnDefault) => { + return Array.from({ length: columnCount }).map((_, index) => { + return { + alignment: 'left', + paddingLeft: 1, + paddingRight: 1, + truncate: Number.POSITIVE_INFINITY, + verticalAlignment: 'top', + wrapWord: false, + ...columnDefault, + ...columns[index], + }; + }); +}; +/** + * Makes a new configuration object out of the userConfig object + * using default values for the missing configuration properties. + */ +const makeStreamConfig = (config) => { + (0, validateConfig_1$1.validateConfig)('streamConfig.json', config); + if (config.columnDefault.width === undefined) { + throw new Error('Must provide config.columnDefault.width when creating a stream.'); + } + return { + drawVerticalLine: () => { + return true; + }, + ...config, + border: (0, utils_1$b.makeBorderConfig)(config.border), + columns: makeColumnsConfig$1(config.columnCount, config.columns, config.columnDefault), + }; +}; +makeStreamConfig$1.makeStreamConfig = makeStreamConfig; + +var mapDataUsingRowHeights = {}; + +(function (exports) { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.mapDataUsingRowHeights = exports.padCellVertically = void 0; + const utils_1 = utils$1; + const wrapCell_1 = wrapCell$1; + const createEmptyStrings = (length) => { + return new Array(length).fill(''); + }; + const padCellVertically = (lines, rowHeight, verticalAlignment) => { + const availableLines = rowHeight - lines.length; + if (verticalAlignment === 'top') { + return [...lines, ...createEmptyStrings(availableLines)]; + } + if (verticalAlignment === 'bottom') { + return [...createEmptyStrings(availableLines), ...lines]; + } + return [ + ...createEmptyStrings(Math.floor(availableLines / 2)), + ...lines, + ...createEmptyStrings(Math.ceil(availableLines / 2)), + ]; + }; + exports.padCellVertically = padCellVertically; + const mapDataUsingRowHeights = (unmappedRows, rowHeights, config) => { + const nColumns = unmappedRows[0].length; + const mappedRows = unmappedRows.map((unmappedRow, unmappedRowIndex) => { + const outputRowHeight = rowHeights[unmappedRowIndex]; + const outputRow = Array.from({ length: outputRowHeight }, () => { + return new Array(nColumns).fill(''); + }); + unmappedRow.forEach((cell, cellIndex) => { + var _a; + const containingRange = (_a = config.spanningCellManager) === null || _a === void 0 ? void 0 : _a.getContainingRange({ col: cellIndex, + row: unmappedRowIndex }); + if (containingRange) { + containingRange.extractCellContent(unmappedRowIndex).forEach((cellLine, cellLineIndex) => { + outputRow[cellLineIndex][cellIndex] = cellLine; + }); + return; + } + const cellLines = (0, wrapCell_1.wrapCell)(cell, config.columns[cellIndex].width, config.columns[cellIndex].wrapWord); + const paddedCellLines = (0, exports.padCellVertically)(cellLines, outputRowHeight, config.columns[cellIndex].verticalAlignment); + paddedCellLines.forEach((cellLine, cellLineIndex) => { + outputRow[cellLineIndex][cellIndex] = cellLine; + }); + }); + return outputRow; + }); + return (0, utils_1.flatten)(mappedRows); + }; + exports.mapDataUsingRowHeights = mapDataUsingRowHeights; + +} (mapDataUsingRowHeights)); + +var padTableData = {}; + +(function (exports) { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.padTableData = exports.padString = void 0; + const padString = (input, paddingLeft, paddingRight) => { + return ' '.repeat(paddingLeft) + input + ' '.repeat(paddingRight); + }; + exports.padString = padString; + const padTableData = (rows, config) => { + return rows.map((cells, rowIndex) => { + return cells.map((cell, cellIndex) => { + var _a; + const containingRange = (_a = config.spanningCellManager) === null || _a === void 0 ? void 0 : _a.getContainingRange({ col: cellIndex, + row: rowIndex }, { mapped: true }); + if (containingRange) { + return cell; + } + const { paddingLeft, paddingRight } = config.columns[cellIndex]; + return (0, exports.padString)(cell, paddingLeft, paddingRight); + }); + }); + }; + exports.padTableData = padTableData; + +} (padTableData)); + +var stringifyTableData$1 = {}; + +Object.defineProperty(stringifyTableData$1, "__esModule", { value: true }); +stringifyTableData$1.stringifyTableData = void 0; +const utils_1$a = utils$1; +const stringifyTableData = (rows) => { + return rows.map((cells) => { + return cells.map((cell) => { + return (0, utils_1$a.normalizeString)(String(cell)); + }); + }); +}; +stringifyTableData$1.stringifyTableData = stringifyTableData; + +var truncateTableData = {}; + +var lodash_truncate = {exports: {}}; + +/** + * lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright jQuery Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ +lodash_truncate.exports; + +(function (module, exports) { + /** Used as default options for `_.truncate`. */ + var DEFAULT_TRUNC_LENGTH = 30, + DEFAULT_TRUNC_OMISSION = '...'; + + /** Used as references for various `Number` constants. */ + var INFINITY = 1 / 0, + MAX_INTEGER = 1.7976931348623157e+308, + NAN = 0 / 0; + + /** `Object#toString` result references. */ + var regexpTag = '[object RegExp]', + symbolTag = '[object Symbol]'; + + /** Used to match leading and trailing whitespace. */ + var reTrim = /^\s+|\s+$/g; + + /** Used to match `RegExp` flags from their coerced string values. */ + var reFlags = /\w*$/; + + /** Used to detect bad signed hexadecimal string values. */ + var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; + + /** Used to detect binary string values. */ + var reIsBinary = /^0b[01]+$/i; + + /** Used to detect octal string values. */ + var reIsOctal = /^0o[0-7]+$/i; + + /** Used to compose unicode character classes. */ + var rsAstralRange = '\\ud800-\\udfff', + rsComboMarksRange = '\\u0300-\\u036f\\ufe20-\\ufe23', + rsComboSymbolsRange = '\\u20d0-\\u20f0', + rsVarRange = '\\ufe0e\\ufe0f'; + + /** Used to compose unicode capture groups. */ + var rsAstral = '[' + rsAstralRange + ']', + rsCombo = '[' + rsComboMarksRange + rsComboSymbolsRange + ']', + rsFitz = '\\ud83c[\\udffb-\\udfff]', + rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', + rsNonAstral = '[^' + rsAstralRange + ']', + rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', + rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', + rsZWJ = '\\u200d'; + + /** Used to compose unicode regexes. */ + var reOptMod = rsModifier + '?', + rsOptVar = '[' + rsVarRange + ']?', + rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', + rsSeq = rsOptVar + reOptMod + rsOptJoin, + rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; + + /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ + var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); + + /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ + var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboMarksRange + rsComboSymbolsRange + rsVarRange + ']'); + + /** Built-in method references without a dependency on `root`. */ + var freeParseInt = parseInt; + + /** Detect free variable `global` from Node.js. */ + var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal; + + /** Detect free variable `self`. */ + var freeSelf = typeof self == 'object' && self && self.Object === Object && self; + + /** Used as a reference to the global object. */ + var root = freeGlobal || freeSelf || Function('return this')(); + + /** Detect free variable `exports`. */ + var freeExports = exports && !exports.nodeType && exports; + + /** Detect free variable `module`. */ + var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module; + + /** Detect the popular CommonJS extension `module.exports`. */ + var moduleExports = freeModule && freeModule.exports === freeExports; + + /** Detect free variable `process` from Node.js. */ + var freeProcess = moduleExports && freeGlobal.process; + + /** Used to access faster Node.js helpers. */ + var nodeUtil = (function() { + try { + return freeProcess && freeProcess.binding('util'); + } catch (e) {} + }()); + + /* Node.js helper references. */ + var nodeIsRegExp = nodeUtil && nodeUtil.isRegExp; + + /** + * Gets the size of an ASCII `string`. + * + * @private + * @param {string} string The string inspect. + * @returns {number} Returns the string size. + */ + var asciiSize = baseProperty('length'); + + /** + * Converts an ASCII `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ + function asciiToArray(string) { + return string.split(''); + } + + /** + * The base implementation of `_.property` without support for deep paths. + * + * @private + * @param {string} key The key of the property to get. + * @returns {Function} Returns the new accessor function. + */ + function baseProperty(key) { + return function(object) { + return object == null ? undefined : object[key]; + }; + } + + /** + * The base implementation of `_.unary` without support for storing metadata. + * + * @private + * @param {Function} func The function to cap arguments for. + * @returns {Function} Returns the new capped function. + */ + function baseUnary(func) { + return function(value) { + return func(value); + }; + } + + /** + * Checks if `string` contains Unicode symbols. + * + * @private + * @param {string} string The string to inspect. + * @returns {boolean} Returns `true` if a symbol is found, else `false`. + */ + function hasUnicode(string) { + return reHasUnicode.test(string); + } + + /** + * Gets the number of symbols in `string`. + * + * @private + * @param {string} string The string to inspect. + * @returns {number} Returns the string size. + */ + function stringSize(string) { + return hasUnicode(string) + ? unicodeSize(string) + : asciiSize(string); + } + + /** + * Converts `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ + function stringToArray(string) { + return hasUnicode(string) + ? unicodeToArray(string) + : asciiToArray(string); + } + + /** + * Gets the size of a Unicode `string`. + * + * @private + * @param {string} string The string inspect. + * @returns {number} Returns the string size. + */ + function unicodeSize(string) { + var result = reUnicode.lastIndex = 0; + while (reUnicode.test(string)) { + result++; + } + return result; + } + + /** + * Converts a Unicode `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ + function unicodeToArray(string) { + return string.match(reUnicode) || []; + } + + /** Used for built-in method references. */ + var objectProto = Object.prototype; + + /** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ + var objectToString = objectProto.toString; + + /** Built-in value references. */ + var Symbol = root.Symbol; + + /** Used to convert symbols to primitives and strings. */ + var symbolProto = Symbol ? Symbol.prototype : undefined, + symbolToString = symbolProto ? symbolProto.toString : undefined; + + /** + * The base implementation of `_.isRegExp` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. + */ + function baseIsRegExp(value) { + return isObject(value) && objectToString.call(value) == regexpTag; + } + + /** + * The base implementation of `_.slice` without an iteratee call guard. + * + * @private + * @param {Array} array The array to slice. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the slice of `array`. + */ + function baseSlice(array, start, end) { + var index = -1, + length = array.length; + + if (start < 0) { + start = -start > length ? 0 : (length + start); + } + end = end > length ? length : end; + if (end < 0) { + end += length; + } + length = start > end ? 0 : ((end - start) >>> 0); + start >>>= 0; + + var result = Array(length); + while (++index < length) { + result[index] = array[index + start]; + } + return result; + } + + /** + * The base implementation of `_.toString` which doesn't convert nullish + * values to empty strings. + * + * @private + * @param {*} value The value to process. + * @returns {string} Returns the string. + */ + function baseToString(value) { + // Exit early for strings to avoid a performance hit in some environments. + if (typeof value == 'string') { + return value; + } + if (isSymbol(value)) { + return symbolToString ? symbolToString.call(value) : ''; + } + var result = (value + ''); + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; + } + + /** + * Casts `array` to a slice if it's needed. + * + * @private + * @param {Array} array The array to inspect. + * @param {number} start The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the cast slice. + */ + function castSlice(array, start, end) { + var length = array.length; + end = end === undefined ? length : end; + return (!start && end >= length) ? array : baseSlice(array, start, end); + } + + /** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ + function isObject(value) { + var type = typeof value; + return !!value && (type == 'object' || type == 'function'); + } + + /** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ + function isObjectLike(value) { + return !!value && typeof value == 'object'; + } + + /** + * Checks if `value` is classified as a `RegExp` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. + * @example + * + * _.isRegExp(/abc/); + * // => true + * + * _.isRegExp('/abc/'); + * // => false + */ + var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp; + + /** + * Checks if `value` is classified as a `Symbol` primitive or object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. + * @example + * + * _.isSymbol(Symbol.iterator); + * // => true + * + * _.isSymbol('abc'); + * // => false + */ + function isSymbol(value) { + return typeof value == 'symbol' || + (isObjectLike(value) && objectToString.call(value) == symbolTag); + } + + /** + * Converts `value` to a finite number. + * + * @static + * @memberOf _ + * @since 4.12.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted number. + * @example + * + * _.toFinite(3.2); + * // => 3.2 + * + * _.toFinite(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toFinite(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toFinite('3.2'); + * // => 3.2 + */ + function toFinite(value) { + if (!value) { + return value === 0 ? value : 0; + } + value = toNumber(value); + if (value === INFINITY || value === -INFINITY) { + var sign = (value < 0 ? -1 : 1); + return sign * MAX_INTEGER; + } + return value === value ? value : 0; + } + + /** + * Converts `value` to an integer. + * + * **Note:** This method is loosely based on + * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. + * @example + * + * _.toInteger(3.2); + * // => 3 + * + * _.toInteger(Number.MIN_VALUE); + * // => 0 + * + * _.toInteger(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toInteger('3.2'); + * // => 3 + */ + function toInteger(value) { + var result = toFinite(value), + remainder = result % 1; + + return result === result ? (remainder ? result - remainder : result) : 0; + } + + /** + * Converts `value` to a number. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to process. + * @returns {number} Returns the number. + * @example + * + * _.toNumber(3.2); + * // => 3.2 + * + * _.toNumber(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toNumber(Infinity); + * // => Infinity + * + * _.toNumber('3.2'); + * // => 3.2 + */ + function toNumber(value) { + if (typeof value == 'number') { + return value; + } + if (isSymbol(value)) { + return NAN; + } + if (isObject(value)) { + var other = typeof value.valueOf == 'function' ? value.valueOf() : value; + value = isObject(other) ? (other + '') : other; + } + if (typeof value != 'string') { + return value === 0 ? value : +value; + } + value = value.replace(reTrim, ''); + var isBinary = reIsBinary.test(value); + return (isBinary || reIsOctal.test(value)) + ? freeParseInt(value.slice(2), isBinary ? 2 : 8) + : (reIsBadHex.test(value) ? NAN : +value); + } + + /** + * Converts `value` to a string. An empty string is returned for `null` + * and `undefined` values. The sign of `-0` is preserved. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to process. + * @returns {string} Returns the string. + * @example + * + * _.toString(null); + * // => '' + * + * _.toString(-0); + * // => '-0' + * + * _.toString([1, 2, 3]); + * // => '1,2,3' + */ + function toString(value) { + return value == null ? '' : baseToString(value); + } + + /** + * Truncates `string` if it's longer than the given maximum string length. + * The last characters of the truncated string are replaced with the omission + * string which defaults to "...". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to truncate. + * @param {Object} [options={}] The options object. + * @param {number} [options.length=30] The maximum string length. + * @param {string} [options.omission='...'] The string to indicate text is omitted. + * @param {RegExp|string} [options.separator] The separator pattern to truncate to. + * @returns {string} Returns the truncated string. + * @example + * + * _.truncate('hi-diddly-ho there, neighborino'); + * // => 'hi-diddly-ho there, neighbo...' + * + * _.truncate('hi-diddly-ho there, neighborino', { + * 'length': 24, + * 'separator': ' ' + * }); + * // => 'hi-diddly-ho there,...' + * + * _.truncate('hi-diddly-ho there, neighborino', { + * 'length': 24, + * 'separator': /,? +/ + * }); + * // => 'hi-diddly-ho there...' + * + * _.truncate('hi-diddly-ho there, neighborino', { + * 'omission': ' [...]' + * }); + * // => 'hi-diddly-ho there, neig [...]' + */ + function truncate(string, options) { + var length = DEFAULT_TRUNC_LENGTH, + omission = DEFAULT_TRUNC_OMISSION; + + if (isObject(options)) { + var separator = 'separator' in options ? options.separator : separator; + length = 'length' in options ? toInteger(options.length) : length; + omission = 'omission' in options ? baseToString(options.omission) : omission; + } + string = toString(string); + + var strLength = string.length; + if (hasUnicode(string)) { + var strSymbols = stringToArray(string); + strLength = strSymbols.length; + } + if (length >= strLength) { + return string; + } + var end = length - stringSize(omission); + if (end < 1) { + return omission; + } + var result = strSymbols + ? castSlice(strSymbols, 0, end).join('') + : string.slice(0, end); + + if (separator === undefined) { + return result + omission; + } + if (strSymbols) { + end += (result.length - end); + } + if (isRegExp(separator)) { + if (string.slice(end).search(separator)) { + var match, + substring = result; + + if (!separator.global) { + separator = RegExp(separator.source, toString(reFlags.exec(separator)) + 'g'); + } + separator.lastIndex = 0; + while ((match = separator.exec(substring))) { + var newEnd = match.index; + } + result = result.slice(0, newEnd === undefined ? end : newEnd); + } + } else if (string.indexOf(baseToString(separator), end) != end) { + var index = result.lastIndexOf(separator); + if (index > -1) { + result = result.slice(0, index); + } + } + return result + omission; + } + + module.exports = truncate; +} (lodash_truncate, lodash_truncate.exports)); + +var lodash_truncateExports = lodash_truncate.exports; + +(function (exports) { + var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.truncateTableData = exports.truncateString = void 0; + const lodash_truncate_1 = __importDefault(lodash_truncateExports); + const truncateString = (input, length) => { + return (0, lodash_truncate_1.default)(input, { length, + omission: '…' }); + }; + exports.truncateString = truncateString; + /** + * @todo Make it work with ASCII content. + */ + const truncateTableData = (rows, truncates) => { + return rows.map((cells) => { + return cells.map((cell, cellIndex) => { + return (0, exports.truncateString)(cell, truncates[cellIndex]); + }); + }); + }; + exports.truncateTableData = truncateTableData; + +} (truncateTableData)); + +Object.defineProperty(createStream$1, "__esModule", { value: true }); +createStream$1.createStream = void 0; +const alignTableData_1$1 = alignTableData$1; +const calculateRowHeights_1$1 = calculateRowHeights$1; +const drawBorder_1$1 = drawBorder; +const drawRow_1$1 = drawRow$1; +const makeStreamConfig_1 = makeStreamConfig$1; +const mapDataUsingRowHeights_1$2 = mapDataUsingRowHeights; +const padTableData_1$2 = padTableData; +const stringifyTableData_1$1 = stringifyTableData$1; +const truncateTableData_1$2 = truncateTableData; +const utils_1$9 = utils$1; +const prepareData = (data, config) => { + let rows = (0, stringifyTableData_1$1.stringifyTableData)(data); + rows = (0, truncateTableData_1$2.truncateTableData)(rows, (0, utils_1$9.extractTruncates)(config)); + const rowHeights = (0, calculateRowHeights_1$1.calculateRowHeights)(rows, config); + rows = (0, mapDataUsingRowHeights_1$2.mapDataUsingRowHeights)(rows, rowHeights, config); + rows = (0, alignTableData_1$1.alignTableData)(rows, config); + rows = (0, padTableData_1$2.padTableData)(rows, config); + return rows; +}; +const create$2 = (row, columnWidths, config) => { + const rows = prepareData([row], config); + const body = rows.map((literalRow) => { + return (0, drawRow_1$1.drawRow)(literalRow, config); + }).join(''); + let output; + output = ''; + output += (0, drawBorder_1$1.drawBorderTop)(columnWidths, config); + output += body; + output += (0, drawBorder_1$1.drawBorderBottom)(columnWidths, config); + output = output.trimEnd(); + process.stdout.write(output); +}; +const append = (row, columnWidths, config) => { + const rows = prepareData([row], config); + const body = rows.map((literalRow) => { + return (0, drawRow_1$1.drawRow)(literalRow, config); + }).join(''); + let output = ''; + const bottom = (0, drawBorder_1$1.drawBorderBottom)(columnWidths, config); + if (bottom !== '\n') { + output = '\r\u001B[K'; + } + output += (0, drawBorder_1$1.drawBorderJoin)(columnWidths, config); + output += body; + output += bottom; + output = output.trimEnd(); + process.stdout.write(output); +}; +const createStream = (userConfig) => { + const config = (0, makeStreamConfig_1.makeStreamConfig)(userConfig); + const columnWidths = Object.values(config.columns).map((column) => { + return column.width + column.paddingLeft + column.paddingRight; + }); + let empty = true; + return { + write: (row) => { + if (row.length !== config.columnCount) { + throw new Error('Row cell count does not match the config.columnCount.'); + } + if (empty) { + empty = false; + create$2(row, columnWidths, config); + } + else { + append(row, columnWidths, config); + } + }, + }; +}; +createStream$1.createStream = createStream; + +var table$1 = {}; + +var calculateOutputColumnWidths$1 = {}; + +Object.defineProperty(calculateOutputColumnWidths$1, "__esModule", { value: true }); +calculateOutputColumnWidths$1.calculateOutputColumnWidths = void 0; +const calculateOutputColumnWidths = (config) => { + return config.columns.map((col) => { + return col.paddingLeft + col.width + col.paddingRight; + }); +}; +calculateOutputColumnWidths$1.calculateOutputColumnWidths = calculateOutputColumnWidths; + +var drawTable$1 = {}; + +Object.defineProperty(drawTable$1, "__esModule", { value: true }); +drawTable$1.drawTable = void 0; +const drawBorder_1 = drawBorder; +const drawContent_1 = drawContent$1; +const drawRow_1 = drawRow$1; +const utils_1$8 = utils$1; +const drawTable = (rows, outputColumnWidths, rowHeights, config) => { + const { drawHorizontalLine, singleLine, } = config; + const contents = (0, utils_1$8.groupBySizes)(rows, rowHeights).map((group, groupIndex) => { + return group.map((row) => { + return (0, drawRow_1.drawRow)(row, { ...config, + rowIndex: groupIndex }); + }).join(''); + }); + return (0, drawContent_1.drawContent)({ contents, + drawSeparator: (index, size) => { + // Top/bottom border + if (index === 0 || index === size) { + return drawHorizontalLine(index, size); + } + return !singleLine && drawHorizontalLine(index, size); + }, + elementType: 'row', + rowIndex: -1, + separatorGetter: (0, drawBorder_1.createTableBorderGetter)(outputColumnWidths, { ...config, + rowCount: contents.length }), + spanningCellManager: config.spanningCellManager }); +}; +drawTable$1.drawTable = drawTable; + +var injectHeaderConfig$1 = {}; + +Object.defineProperty(injectHeaderConfig$1, "__esModule", { value: true }); +injectHeaderConfig$1.injectHeaderConfig = void 0; +const injectHeaderConfig = (rows, config) => { + var _a; + let spanningCellConfig = (_a = config.spanningCells) !== null && _a !== void 0 ? _a : []; + const headerConfig = config.header; + const adjustedRows = [...rows]; + if (headerConfig) { + spanningCellConfig = spanningCellConfig.map(({ row, ...rest }) => { + return { ...rest, + row: row + 1 }; + }); + const { content, ...headerStyles } = headerConfig; + spanningCellConfig.unshift({ alignment: 'center', + col: 0, + colSpan: rows[0].length, + paddingLeft: 1, + paddingRight: 1, + row: 0, + wrapWord: false, + ...headerStyles }); + adjustedRows.unshift([content, ...Array.from({ length: rows[0].length - 1 }).fill('')]); + } + return [adjustedRows, + spanningCellConfig]; +}; +injectHeaderConfig$1.injectHeaderConfig = injectHeaderConfig; + +var makeTableConfig$1 = {}; + +var calculateMaximumColumnWidths = {}; + +(function (exports) { + var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.calculateMaximumColumnWidths = exports.calculateMaximumCellWidth = void 0; + const string_width_1 = __importDefault(stringWidthExports); + const utils_1 = utils$1; + const calculateMaximumCellWidth = (cell) => { + return Math.max(...cell.split('\n').map(string_width_1.default)); + }; + exports.calculateMaximumCellWidth = calculateMaximumCellWidth; + /** + * Produces an array of values that describe the largest value length (width) in every column. + */ + const calculateMaximumColumnWidths = (rows, spanningCellConfigs = []) => { + const columnWidths = new Array(rows[0].length).fill(0); + const rangeCoordinates = spanningCellConfigs.map(utils_1.calculateRangeCoordinate); + const isSpanningCell = (rowIndex, columnIndex) => { + return rangeCoordinates.some((rangeCoordinate) => { + return (0, utils_1.isCellInRange)({ col: columnIndex, + row: rowIndex }, rangeCoordinate); + }); + }; + rows.forEach((row, rowIndex) => { + row.forEach((cell, cellIndex) => { + if (isSpanningCell(rowIndex, cellIndex)) { + return; + } + columnWidths[cellIndex] = Math.max(columnWidths[cellIndex], (0, exports.calculateMaximumCellWidth)(cell)); + }); + }); + return columnWidths; + }; + exports.calculateMaximumColumnWidths = calculateMaximumColumnWidths; + +} (calculateMaximumColumnWidths)); + +var spanningCellManager = {}; + +var alignSpanningCell = {}; + +var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(alignSpanningCell, "__esModule", { value: true }); +alignSpanningCell.alignVerticalRangeContent = alignSpanningCell.wrapRangeContent = void 0; +const string_width_1 = __importDefault(stringWidthExports); +const alignString_1 = alignString$1; +const mapDataUsingRowHeights_1$1 = mapDataUsingRowHeights; +const padTableData_1$1 = padTableData; +const truncateTableData_1$1 = truncateTableData; +const utils_1$7 = utils$1; +const wrapCell_1 = wrapCell$1; +/** + * Fill content into all cells in range in order to calculate total height + */ +const wrapRangeContent = (rangeConfig, rangeWidth, context) => { + const { topLeft, paddingRight, paddingLeft, truncate, wrapWord, alignment } = rangeConfig; + const originalContent = context.rows[topLeft.row][topLeft.col]; + const contentWidth = rangeWidth - paddingLeft - paddingRight; + return (0, wrapCell_1.wrapCell)((0, truncateTableData_1$1.truncateString)(originalContent, truncate), contentWidth, wrapWord).map((line) => { + const alignedLine = (0, alignString_1.alignString)(line, contentWidth, alignment); + return (0, padTableData_1$1.padString)(alignedLine, paddingLeft, paddingRight); + }); +}; +alignSpanningCell.wrapRangeContent = wrapRangeContent; +const alignVerticalRangeContent = (range, content, context) => { + const { rows, drawHorizontalLine, rowHeights } = context; + const { topLeft, bottomRight, verticalAlignment } = range; + // They are empty before calculateRowHeights function run + if (rowHeights.length === 0) { + return []; + } + const totalCellHeight = (0, utils_1$7.sumArray)(rowHeights.slice(topLeft.row, bottomRight.row + 1)); + const totalBorderHeight = bottomRight.row - topLeft.row; + const hiddenHorizontalBorderCount = (0, utils_1$7.sequence)(topLeft.row + 1, bottomRight.row).filter((horizontalBorderIndex) => { + return !drawHorizontalLine(horizontalBorderIndex, rows.length); + }).length; + const availableRangeHeight = totalCellHeight + totalBorderHeight - hiddenHorizontalBorderCount; + return (0, mapDataUsingRowHeights_1$1.padCellVertically)(content, availableRangeHeight, verticalAlignment).map((line) => { + if (line.length === 0) { + return ' '.repeat((0, string_width_1.default)(content[0])); + } + return line; + }); +}; +alignSpanningCell.alignVerticalRangeContent = alignVerticalRangeContent; + +var calculateSpanningCellWidth$1 = {}; + +Object.defineProperty(calculateSpanningCellWidth$1, "__esModule", { value: true }); +calculateSpanningCellWidth$1.calculateSpanningCellWidth = void 0; +const utils_1$6 = utils$1; +const calculateSpanningCellWidth = (rangeConfig, dependencies) => { + const { columnsConfig, drawVerticalLine } = dependencies; + const { topLeft, bottomRight } = rangeConfig; + const totalWidth = (0, utils_1$6.sumArray)(columnsConfig.slice(topLeft.col, bottomRight.col + 1).map(({ width }) => { + return width; + })); + const totalPadding = topLeft.col === bottomRight.col ? + columnsConfig[topLeft.col].paddingRight + + columnsConfig[bottomRight.col].paddingLeft : + (0, utils_1$6.sumArray)(columnsConfig + .slice(topLeft.col, bottomRight.col + 1) + .map(({ paddingLeft, paddingRight }) => { + return paddingLeft + paddingRight; + })); + const totalBorderWidths = bottomRight.col - topLeft.col; + const totalHiddenVerticalBorders = (0, utils_1$6.sequence)(topLeft.col + 1, bottomRight.col).filter((verticalBorderIndex) => { + return !drawVerticalLine(verticalBorderIndex, columnsConfig.length); + }).length; + return totalWidth + totalPadding + totalBorderWidths - totalHiddenVerticalBorders; +}; +calculateSpanningCellWidth$1.calculateSpanningCellWidth = calculateSpanningCellWidth; + +var makeRangeConfig$1 = {}; + +Object.defineProperty(makeRangeConfig$1, "__esModule", { value: true }); +makeRangeConfig$1.makeRangeConfig = void 0; +const utils_1$5 = utils$1; +const makeRangeConfig = (spanningCellConfig, columnsConfig) => { + var _a; + const { topLeft, bottomRight } = (0, utils_1$5.calculateRangeCoordinate)(spanningCellConfig); + const cellConfig = { + ...columnsConfig[topLeft.col], + ...spanningCellConfig, + paddingRight: (_a = spanningCellConfig.paddingRight) !== null && _a !== void 0 ? _a : columnsConfig[bottomRight.col].paddingRight, + }; + return { ...cellConfig, + bottomRight, + topLeft }; +}; +makeRangeConfig$1.makeRangeConfig = makeRangeConfig; + +Object.defineProperty(spanningCellManager, "__esModule", { value: true }); +spanningCellManager.createSpanningCellManager = void 0; +const alignSpanningCell_1 = alignSpanningCell; +const calculateSpanningCellWidth_1 = calculateSpanningCellWidth$1; +const makeRangeConfig_1 = makeRangeConfig$1; +const utils_1$4 = utils$1; +const findRangeConfig = (cell, rangeConfigs) => { + return rangeConfigs.find((rangeCoordinate) => { + return (0, utils_1$4.isCellInRange)(cell, rangeCoordinate); + }); +}; +const getContainingRange = (rangeConfig, context) => { + const width = (0, calculateSpanningCellWidth_1.calculateSpanningCellWidth)(rangeConfig, context); + const wrappedContent = (0, alignSpanningCell_1.wrapRangeContent)(rangeConfig, width, context); + const alignedContent = (0, alignSpanningCell_1.alignVerticalRangeContent)(rangeConfig, wrappedContent, context); + const getCellContent = (rowIndex) => { + const { topLeft } = rangeConfig; + const { drawHorizontalLine, rowHeights } = context; + const totalWithinHorizontalBorderHeight = rowIndex - topLeft.row; + const totalHiddenHorizontalBorderHeight = (0, utils_1$4.sequence)(topLeft.row + 1, rowIndex).filter((index) => { + /* istanbul ignore next */ + return !(drawHorizontalLine === null || drawHorizontalLine === void 0 ? void 0 : drawHorizontalLine(index, rowHeights.length)); + }).length; + const offset = (0, utils_1$4.sumArray)(rowHeights.slice(topLeft.row, rowIndex)) + totalWithinHorizontalBorderHeight - totalHiddenHorizontalBorderHeight; + return alignedContent.slice(offset, offset + rowHeights[rowIndex]); + }; + const getBorderContent = (borderIndex) => { + const { topLeft } = rangeConfig; + const offset = (0, utils_1$4.sumArray)(context.rowHeights.slice(topLeft.row, borderIndex)) + (borderIndex - topLeft.row - 1); + return alignedContent[offset]; + }; + return { + ...rangeConfig, + extractBorderContent: getBorderContent, + extractCellContent: getCellContent, + height: wrappedContent.length, + width, + }; +}; +const inSameRange = (cell1, cell2, ranges) => { + const range1 = findRangeConfig(cell1, ranges); + const range2 = findRangeConfig(cell2, ranges); + if (range1 && range2) { + return (0, utils_1$4.areCellEqual)(range1.topLeft, range2.topLeft); + } + return false; +}; +const hashRange = (range) => { + const { row, col } = range.topLeft; + return `${row}/${col}`; +}; +const createSpanningCellManager = (parameters) => { + const { spanningCellConfigs, columnsConfig } = parameters; + const ranges = spanningCellConfigs.map((config) => { + return (0, makeRangeConfig_1.makeRangeConfig)(config, columnsConfig); + }); + const rangeCache = {}; + let rowHeights = []; + return { getContainingRange: (cell, options) => { + var _a; + const originalRow = (options === null || options === void 0 ? void 0 : options.mapped) ? (0, utils_1$4.findOriginalRowIndex)(rowHeights, cell.row) : cell.row; + const range = findRangeConfig({ ...cell, + row: originalRow }, ranges); + if (!range) { + return undefined; + } + if (rowHeights.length === 0) { + return getContainingRange(range, { ...parameters, + rowHeights }); + } + const hash = hashRange(range); + (_a = rangeCache[hash]) !== null && _a !== void 0 ? _a : (rangeCache[hash] = getContainingRange(range, { ...parameters, + rowHeights })); + return rangeCache[hash]; + }, + inSameRange: (cell1, cell2) => { + return inSameRange(cell1, cell2, ranges); + }, + rowHeights, + setRowHeights: (_rowHeights) => { + rowHeights = _rowHeights; + } }; +}; +spanningCellManager.createSpanningCellManager = createSpanningCellManager; + +var validateSpanningCellConfig$1 = {}; + +Object.defineProperty(validateSpanningCellConfig$1, "__esModule", { value: true }); +validateSpanningCellConfig$1.validateSpanningCellConfig = void 0; +const utils_1$3 = utils$1; +const inRange = (start, end, value) => { + return start <= value && value <= end; +}; +const validateSpanningCellConfig = (rows, configs) => { + const [nRow, nCol] = [rows.length, rows[0].length]; + configs.forEach((config, configIndex) => { + const { colSpan, rowSpan } = config; + if (colSpan === undefined && rowSpan === undefined) { + throw new Error(`Expect at least colSpan or rowSpan is provided in config.spanningCells[${configIndex}]`); + } + if (colSpan !== undefined && colSpan < 1) { + throw new Error(`Expect colSpan is not equal zero, instead got: ${colSpan} in config.spanningCells[${configIndex}]`); + } + if (rowSpan !== undefined && rowSpan < 1) { + throw new Error(`Expect rowSpan is not equal zero, instead got: ${rowSpan} in config.spanningCells[${configIndex}]`); + } + }); + const rangeCoordinates = configs.map(utils_1$3.calculateRangeCoordinate); + rangeCoordinates.forEach(({ topLeft, bottomRight }, rangeIndex) => { + if (!inRange(0, nCol - 1, topLeft.col) || + !inRange(0, nRow - 1, topLeft.row) || + !inRange(0, nCol - 1, bottomRight.col) || + !inRange(0, nRow - 1, bottomRight.row)) { + throw new Error(`Some cells in config.spanningCells[${rangeIndex}] are out of the table`); + } + }); + const configOccupy = Array.from({ length: nRow }, () => { + return Array.from({ length: nCol }); + }); + rangeCoordinates.forEach(({ topLeft, bottomRight }, rangeIndex) => { + (0, utils_1$3.sequence)(topLeft.row, bottomRight.row).forEach((row) => { + (0, utils_1$3.sequence)(topLeft.col, bottomRight.col).forEach((col) => { + if (configOccupy[row][col] !== undefined) { + throw new Error(`Spanning cells in config.spanningCells[${configOccupy[row][col]}] and config.spanningCells[${rangeIndex}] are overlap each other`); + } + configOccupy[row][col] = rangeIndex; + }); + }); + }); +}; +validateSpanningCellConfig$1.validateSpanningCellConfig = validateSpanningCellConfig; + +Object.defineProperty(makeTableConfig$1, "__esModule", { value: true }); +makeTableConfig$1.makeTableConfig = void 0; +const calculateMaximumColumnWidths_1 = calculateMaximumColumnWidths; +const spanningCellManager_1 = spanningCellManager; +const utils_1$2 = utils$1; +const validateConfig_1 = validateConfig$1; +const validateSpanningCellConfig_1 = validateSpanningCellConfig$1; +/** + * Creates a configuration for every column using default + * values for the missing configuration properties. + */ +const makeColumnsConfig = (rows, columns, columnDefault, spanningCellConfigs) => { + const columnWidths = (0, calculateMaximumColumnWidths_1.calculateMaximumColumnWidths)(rows, spanningCellConfigs); + return rows[0].map((_, columnIndex) => { + return { + alignment: 'left', + paddingLeft: 1, + paddingRight: 1, + truncate: Number.POSITIVE_INFINITY, + verticalAlignment: 'top', + width: columnWidths[columnIndex], + wrapWord: false, + ...columnDefault, + ...columns === null || columns === void 0 ? void 0 : columns[columnIndex], + }; + }); +}; +/** + * Makes a new configuration object out of the userConfig object + * using default values for the missing configuration properties. + */ +const makeTableConfig = (rows, config = {}, injectedSpanningCellConfig) => { + var _a, _b, _c, _d, _e; + (0, validateConfig_1.validateConfig)('config.json', config); + (0, validateSpanningCellConfig_1.validateSpanningCellConfig)(rows, (_a = config.spanningCells) !== null && _a !== void 0 ? _a : []); + const spanningCellConfigs = (_b = injectedSpanningCellConfig !== null && injectedSpanningCellConfig !== void 0 ? injectedSpanningCellConfig : config.spanningCells) !== null && _b !== void 0 ? _b : []; + const columnsConfig = makeColumnsConfig(rows, config.columns, config.columnDefault, spanningCellConfigs); + const drawVerticalLine = (_c = config.drawVerticalLine) !== null && _c !== void 0 ? _c : (() => { + return true; + }); + const drawHorizontalLine = (_d = config.drawHorizontalLine) !== null && _d !== void 0 ? _d : (() => { + return true; + }); + return { + ...config, + border: (0, utils_1$2.makeBorderConfig)(config.border), + columns: columnsConfig, + drawHorizontalLine, + drawVerticalLine, + singleLine: (_e = config.singleLine) !== null && _e !== void 0 ? _e : false, + spanningCellManager: (0, spanningCellManager_1.createSpanningCellManager)({ + columnsConfig, + drawHorizontalLine, + drawVerticalLine, + rows, + spanningCellConfigs, + }), + }; +}; +makeTableConfig$1.makeTableConfig = makeTableConfig; + +var validateTableData$1 = {}; + +Object.defineProperty(validateTableData$1, "__esModule", { value: true }); +validateTableData$1.validateTableData = void 0; +const utils_1$1 = utils$1; +const validateTableData = (rows) => { + if (!Array.isArray(rows)) { + throw new TypeError('Table data must be an array.'); + } + if (rows.length === 0) { + throw new Error('Table must define at least one row.'); + } + if (rows[0].length === 0) { + throw new Error('Table must define at least one column.'); + } + const columnNumber = rows[0].length; + for (const row of rows) { + if (!Array.isArray(row)) { + throw new TypeError('Table row data must be an array.'); + } + if (row.length !== columnNumber) { + throw new Error('Table must have a consistent number of cells.'); + } + for (const cell of row) { + // eslint-disable-next-line no-control-regex + if (/[\u0001-\u0006\u0008\u0009\u000B-\u001A]/.test((0, utils_1$1.normalizeString)(String(cell)))) { + throw new Error('Table data must not contain control characters.'); + } + } + } +}; +validateTableData$1.validateTableData = validateTableData; + +Object.defineProperty(table$1, "__esModule", { value: true }); +table$1.table = void 0; +const alignTableData_1 = alignTableData$1; +const calculateOutputColumnWidths_1 = calculateOutputColumnWidths$1; +const calculateRowHeights_1 = calculateRowHeights$1; +const drawTable_1 = drawTable$1; +const injectHeaderConfig_1 = injectHeaderConfig$1; +const makeTableConfig_1 = makeTableConfig$1; +const mapDataUsingRowHeights_1 = mapDataUsingRowHeights; +const padTableData_1 = padTableData; +const stringifyTableData_1 = stringifyTableData$1; +const truncateTableData_1 = truncateTableData; +const utils_1 = utils$1; +const validateTableData_1 = validateTableData$1; +const table = (data, userConfig = {}) => { + (0, validateTableData_1.validateTableData)(data); + let rows = (0, stringifyTableData_1.stringifyTableData)(data); + const [injectedRows, injectedSpanningCellConfig] = (0, injectHeaderConfig_1.injectHeaderConfig)(rows, userConfig); + const config = (0, makeTableConfig_1.makeTableConfig)(injectedRows, userConfig, injectedSpanningCellConfig); + rows = (0, truncateTableData_1.truncateTableData)(injectedRows, (0, utils_1.extractTruncates)(config)); + const rowHeights = (0, calculateRowHeights_1.calculateRowHeights)(rows, config); + config.spanningCellManager.setRowHeights(rowHeights); + rows = (0, mapDataUsingRowHeights_1.mapDataUsingRowHeights)(rows, rowHeights, config); + rows = (0, alignTableData_1.alignTableData)(rows, config); + rows = (0, padTableData_1.padTableData)(rows, config); + const outputColumnWidths = (0, calculateOutputColumnWidths_1.calculateOutputColumnWidths)(config); + return (0, drawTable_1.drawTable)(rows, outputColumnWidths, rowHeights, config); +}; +table$1.table = table; + +var api = {}; + +Object.defineProperty(api, "__esModule", { value: true }); + +(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 __exportStar = (commonjsGlobal && commonjsGlobal.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getBorderCharacters = exports.createStream = exports.table = void 0; + const createStream_1 = createStream$1; + Object.defineProperty(exports, "createStream", { enumerable: true, get: function () { return createStream_1.createStream; } }); + const getBorderCharacters_1 = getBorderCharacters$1; + Object.defineProperty(exports, "getBorderCharacters", { enumerable: true, get: function () { return getBorderCharacters_1.getBorderCharacters; } }); + const table_1 = table$1; + Object.defineProperty(exports, "table", { enumerable: true, get: function () { return table_1.table; } }); + __exportStar(api, exports); + +} (src$2)); + +const { + hasOwnProperty: hasOwnProp +} = Object.prototype; +/** + * @typedef {null|boolean|number|string|PlainObject|GenericArray} JSONObject + */ + +/** + * @typedef {any} AnyItem + */ + +/** + * @typedef {any} AnyResult + */ + +/** + * Copies array and then pushes item into it. + * @param {GenericArray} arr Array to copy and into which to push + * @param {AnyItem} item Array item to add (to end) + * @returns {GenericArray} Copy of the original array + */ + +function push(arr, item) { + arr = arr.slice(); + arr.push(item); + return arr; +} +/** + * Copies array and then unshifts item into it. + * @param {AnyItem} item Array item to add (to beginning) + * @param {GenericArray} arr Array to copy and into which to unshift + * @returns {GenericArray} Copy of the original array + */ + + +function unshift(item, arr) { + arr = arr.slice(); + arr.unshift(item); + return arr; +} +/** + * Caught when JSONPath is used without `new` but rethrown if with `new` + * @extends Error + */ + + +class NewError extends Error { + /** + * @param {AnyResult} value The evaluated scalar value + */ + constructor(value) { + super('JSONPath should not be called with "new" (it prevents return ' + 'of (unwrapped) scalar values)'); + this.avoidNew = true; + this.value = value; + this.name = 'NewError'; + } + +} +/** +* @typedef {PlainObject} ReturnObject +* @property {string} path +* @property {JSONObject} value +* @property {PlainObject|GenericArray} parent +* @property {string} parentProperty +*/ + +/** +* @callback JSONPathCallback +* @param {string|PlainObject} preferredOutput +* @param {"value"|"property"} type +* @param {ReturnObject} fullRetObj +* @returns {void} +*/ + +/** +* @callback OtherTypeCallback +* @param {JSONObject} val +* @param {string} path +* @param {PlainObject|GenericArray} parent +* @param {string} parentPropName +* @returns {boolean} +*/ + +/* eslint-disable max-len -- Can make multiline type after https://github.com/syavorsky/comment-parser/issues/109 */ + +/** + * @typedef {PlainObject} JSONPathOptions + * @property {JSON} json + * @property {string|string[]} path + * @property {"value"|"path"|"pointer"|"parent"|"parentProperty"|"all"} [resultType="value"] + * @property {boolean} [flatten=false] + * @property {boolean} [wrap=true] + * @property {PlainObject} [sandbox={}] + * @property {boolean} [preventEval=false] + * @property {PlainObject|GenericArray|null} [parent=null] + * @property {string|null} [parentProperty=null] + * @property {JSONPathCallback} [callback] + * @property {OtherTypeCallback} [otherTypeCallback] Defaults to + * function which throws on encountering `@other` + * @property {boolean} [autostart=true] + */ + +/* eslint-enable max-len -- Can make multiline type after https://github.com/syavorsky/comment-parser/issues/109 */ + +/** + * @param {string|JSONPathOptions} opts If a string, will be treated as `expr` + * @param {string} [expr] JSON path to evaluate + * @param {JSON} [obj] JSON object to evaluate against + * @param {JSONPathCallback} [callback] Passed 3 arguments: 1) desired payload + * per `resultType`, 2) `"value"|"property"`, 3) Full returned object with + * all payloads + * @param {OtherTypeCallback} [otherTypeCallback] If `@other()` is at the end + * of one's query, this will be invoked with the value of the item, its + * path, its parent, and its parent's property name, and it should return + * a boolean indicating whether the supplied value belongs to the "other" + * type or not (or it may handle transformations and return `false`). + * @returns {JSONPath} + * @class + */ + + +function JSONPath(opts, expr, obj, callback, otherTypeCallback) { + // eslint-disable-next-line no-restricted-syntax + if (!(this instanceof JSONPath)) { + try { + return new JSONPath(opts, expr, obj, callback, otherTypeCallback); + } catch (e) { + if (!e.avoidNew) { + throw e; + } + + return e.value; + } + } + + if (typeof opts === 'string') { + otherTypeCallback = callback; + callback = obj; + obj = expr; + expr = opts; + opts = null; + } + + const optObj = opts && typeof opts === 'object'; + opts = opts || {}; + this.json = opts.json || obj; + this.path = opts.path || expr; + this.resultType = opts.resultType || 'value'; + this.flatten = opts.flatten || false; + this.wrap = hasOwnProp.call(opts, 'wrap') ? opts.wrap : true; + this.sandbox = opts.sandbox || {}; + this.preventEval = opts.preventEval || false; + this.parent = opts.parent || null; + this.parentProperty = opts.parentProperty || null; + this.callback = opts.callback || callback || null; + + this.otherTypeCallback = opts.otherTypeCallback || otherTypeCallback || function () { + throw new TypeError('You must supply an otherTypeCallback callback option ' + 'with the @other() operator.'); + }; + + if (opts.autostart !== false) { + const args = { + path: optObj ? opts.path : expr + }; + + if (!optObj) { + args.json = obj; + } else if ('json' in opts) { + args.json = opts.json; + } + + const ret = this.evaluate(args); + + if (!ret || typeof ret !== 'object') { + throw new NewError(ret); + } + + return ret; + } +} // PUBLIC METHODS + + +JSONPath.prototype.evaluate = function (expr, json, callback, otherTypeCallback) { + let currParent = this.parent, + currParentProperty = this.parentProperty; + let { + flatten, + wrap + } = this; + this.currResultType = this.resultType; + this.currPreventEval = this.preventEval; + this.currSandbox = this.sandbox; + callback = callback || this.callback; + this.currOtherTypeCallback = otherTypeCallback || this.otherTypeCallback; + json = json || this.json; + expr = expr || this.path; + + if (expr && typeof expr === 'object' && !Array.isArray(expr)) { + if (!expr.path && expr.path !== '') { + throw new TypeError('You must supply a "path" property when providing an object ' + 'argument to JSONPath.evaluate().'); + } + + if (!hasOwnProp.call(expr, 'json')) { + throw new TypeError('You must supply a "json" property when providing an object ' + 'argument to JSONPath.evaluate().'); + } + + ({ + json + } = expr); + flatten = hasOwnProp.call(expr, 'flatten') ? expr.flatten : flatten; + this.currResultType = hasOwnProp.call(expr, 'resultType') ? expr.resultType : this.currResultType; + this.currSandbox = hasOwnProp.call(expr, 'sandbox') ? expr.sandbox : this.currSandbox; + wrap = hasOwnProp.call(expr, 'wrap') ? expr.wrap : wrap; + this.currPreventEval = hasOwnProp.call(expr, 'preventEval') ? expr.preventEval : this.currPreventEval; + callback = hasOwnProp.call(expr, 'callback') ? expr.callback : callback; + this.currOtherTypeCallback = hasOwnProp.call(expr, 'otherTypeCallback') ? expr.otherTypeCallback : this.currOtherTypeCallback; + currParent = hasOwnProp.call(expr, 'parent') ? expr.parent : currParent; + currParentProperty = hasOwnProp.call(expr, 'parentProperty') ? expr.parentProperty : currParentProperty; + expr = expr.path; + } + + currParent = currParent || null; + currParentProperty = currParentProperty || null; + + if (Array.isArray(expr)) { + expr = JSONPath.toPathString(expr); + } + + if (!expr && expr !== '' || !json) { + return undefined; + } + + const exprList = JSONPath.toPathArray(expr); + + if (exprList[0] === '$' && exprList.length > 1) { + exprList.shift(); + } + + this._hasParentSelector = null; + + const result = this._trace(exprList, json, ['$'], currParent, currParentProperty, callback).filter(function (ea) { + return ea && !ea.isParentSelector; + }); + + if (!result.length) { + return wrap ? [] : undefined; + } + + if (!wrap && result.length === 1 && !result[0].hasArrExpr) { + return this._getPreferredOutput(result[0]); + } + + return result.reduce((rslt, ea) => { + const valOrPath = this._getPreferredOutput(ea); + + if (flatten && Array.isArray(valOrPath)) { + rslt = rslt.concat(valOrPath); + } else { + rslt.push(valOrPath); + } + + return rslt; + }, []); +}; // PRIVATE METHODS + + +JSONPath.prototype._getPreferredOutput = function (ea) { + const resultType = this.currResultType; + + switch (resultType) { + case 'all': + { + const path = Array.isArray(ea.path) ? ea.path : JSONPath.toPathArray(ea.path); + ea.pointer = JSONPath.toPointer(path); + ea.path = typeof ea.path === 'string' ? ea.path : JSONPath.toPathString(ea.path); + return ea; + } + + case 'value': + case 'parent': + case 'parentProperty': + return ea[resultType]; + + case 'path': + return JSONPath.toPathString(ea[resultType]); + + case 'pointer': + return JSONPath.toPointer(ea.path); + + default: + throw new TypeError('Unknown result type'); + } +}; + +JSONPath.prototype._handleCallback = function (fullRetObj, callback, type) { + if (callback) { + const preferredOutput = this._getPreferredOutput(fullRetObj); + + fullRetObj.path = typeof fullRetObj.path === 'string' ? fullRetObj.path : JSONPath.toPathString(fullRetObj.path); // eslint-disable-next-line n/callback-return + + callback(preferredOutput, type, fullRetObj); + } +}; +/** + * + * @param {string} expr + * @param {JSONObject} val + * @param {string} path + * @param {PlainObject|GenericArray} parent + * @param {string} parentPropName + * @param {JSONPathCallback} callback + * @param {boolean} hasArrExpr + * @param {boolean} literalPriority + * @returns {ReturnObject|ReturnObject[]} + */ + + +JSONPath.prototype._trace = function (expr, val, path, parent, parentPropName, callback, hasArrExpr, literalPriority) { + // No expr to follow? return path and value as the result of + // this trace branch + let retObj; + + if (!expr.length) { + retObj = { + path, + value: val, + parent, + parentProperty: parentPropName, + hasArrExpr + }; + + this._handleCallback(retObj, callback, 'value'); + + return retObj; + } + + const loc = expr[0], + x = expr.slice(1); // We need to gather the return value of recursive trace calls in order to + // do the parent sel computation. + + const ret = []; + /** + * + * @param {ReturnObject|ReturnObject[]} elems + * @returns {void} + */ + + function addRet(elems) { + if (Array.isArray(elems)) { + // This was causing excessive stack size in Node (with or + // without Babel) against our performance test: + // `ret.push(...elems);` + elems.forEach(t => { + ret.push(t); + }); + } else { + ret.push(elems); + } + } + + if ((typeof loc !== 'string' || literalPriority) && val && hasOwnProp.call(val, loc)) { + // simple case--directly follow property + addRet(this._trace(x, val[loc], push(path, loc), val, loc, callback, hasArrExpr)); // eslint-disable-next-line unicorn/prefer-switch -- Part of larger `if` + } else if (loc === '*') { + // all child properties + this._walk(val, m => { + addRet(this._trace(x, val[m], push(path, m), val, m, callback, true, true)); + }); + } else if (loc === '..') { + // all descendent parent properties + // Check remaining expression with val's immediate children + addRet(this._trace(x, val, path, parent, parentPropName, callback, hasArrExpr)); + + this._walk(val, m => { + // We don't join m and x here because we only want parents, + // not scalar values + if (typeof val[m] === 'object') { + // Keep going with recursive descent on val's + // object children + addRet(this._trace(expr.slice(), val[m], push(path, m), val, m, callback, true)); + } + }); // The parent sel computation is handled in the frame above using the + // ancestor object of val + + } else if (loc === '^') { + // This is not a final endpoint, so we do not invoke the callback here + this._hasParentSelector = true; + return { + path: path.slice(0, -1), + expr: x, + isParentSelector: true + }; + } else if (loc === '~') { + // property name + retObj = { + path: push(path, loc), + value: parentPropName, + parent, + parentProperty: null + }; + + this._handleCallback(retObj, callback, 'property'); + + return retObj; + } else if (loc === '$') { + // root only + addRet(this._trace(x, val, path, null, null, callback, hasArrExpr)); + } else if (/^(-?\d*):(-?\d*):?(\d*)$/u.test(loc)) { + // [start:end:step] Python slice syntax + addRet(this._slice(loc, x, val, path, parent, parentPropName, callback)); + } else if (loc.indexOf('?(') === 0) { + // [?(expr)] (filtering) + if (this.currPreventEval) { + throw new Error('Eval [?(expr)] prevented in JSONPath expression.'); + } + + const safeLoc = loc.replace(/^\?\((.*?)\)$/u, '$1'); + + this._walk(val, m => { + if (this._eval(safeLoc, val[m], m, path, parent, parentPropName)) { + addRet(this._trace(x, val[m], push(path, m), val, m, callback, true)); + } + }); + } else if (loc[0] === '(') { + // [(expr)] (dynamic property/index) + if (this.currPreventEval) { + throw new Error('Eval [(expr)] prevented in JSONPath expression.'); + } // As this will resolve to a property name (but we don't know it + // yet), property and parent information is relative to the + // parent of the property to which this expression will resolve + + + addRet(this._trace(unshift(this._eval(loc, val, path[path.length - 1], path.slice(0, -1), parent, parentPropName), x), val, path, parent, parentPropName, callback, hasArrExpr)); + } else if (loc[0] === '@') { + // value type: @boolean(), etc. + let addType = false; + const valueType = loc.slice(1, -2); + + switch (valueType) { + case 'scalar': + if (!val || !['object', 'function'].includes(typeof val)) { + addType = true; + } + + break; + + case 'boolean': + case 'string': + case 'undefined': + case 'function': + // eslint-disable-next-line valid-typeof + if (typeof val === valueType) { + addType = true; + } + + break; + + case 'integer': + if (Number.isFinite(val) && !(val % 1)) { + addType = true; + } + + break; + + case 'number': + if (Number.isFinite(val)) { + addType = true; + } + + break; + + case 'nonFinite': + if (typeof val === 'number' && !Number.isFinite(val)) { + addType = true; + } + + break; + + case 'object': + // eslint-disable-next-line valid-typeof + if (val && typeof val === valueType) { + addType = true; + } + + break; + + case 'array': + if (Array.isArray(val)) { + addType = true; + } + + break; + + case 'other': + addType = this.currOtherTypeCallback(val, path, parent, parentPropName); + break; + + case 'null': + if (val === null) { + addType = true; + } + + break; + + /* c8 ignore next 2 */ + + default: + throw new TypeError('Unknown value type ' + valueType); + } + + if (addType) { + retObj = { + path, + value: val, + parent, + parentProperty: parentPropName + }; + + this._handleCallback(retObj, callback, 'value'); + + return retObj; + } // `-escaped property + + } else if (loc[0] === '`' && val && hasOwnProp.call(val, loc.slice(1))) { + const locProp = loc.slice(1); + addRet(this._trace(x, val[locProp], push(path, locProp), val, locProp, callback, hasArrExpr, true)); + } else if (loc.includes(',')) { + // [name1,name2,...] + const parts = loc.split(','); + + for (const part of parts) { + addRet(this._trace(unshift(part, x), val, path, parent, parentPropName, callback, true)); + } // simple case--directly follow property + + } else if (!literalPriority && val && hasOwnProp.call(val, loc)) { + addRet(this._trace(x, val[loc], push(path, loc), val, loc, callback, hasArrExpr, true)); + } // We check the resulting values for parent selections. For parent + // selections we discard the value object and continue the trace with the + // current val object + + + if (this._hasParentSelector) { + for (let t = 0; t < ret.length; t++) { + const rett = ret[t]; + + if (rett && rett.isParentSelector) { + const tmp = this._trace(rett.expr, val, rett.path, parent, parentPropName, callback, hasArrExpr); + + if (Array.isArray(tmp)) { + ret[t] = tmp[0]; + const tl = tmp.length; + + for (let tt = 1; tt < tl; tt++) { + t++; + ret.splice(t, 0, tmp[tt]); + } + } else { + ret[t] = tmp; + } + } + } + } + + return ret; +}; + +JSONPath.prototype._walk = function (val, f) { + if (Array.isArray(val)) { + const n = val.length; + + for (let i = 0; i < n; i++) { + f(i); + } + } else if (val && typeof val === 'object') { + Object.keys(val).forEach(m => { + f(m); + }); + } +}; + +JSONPath.prototype._slice = function (loc, expr, val, path, parent, parentPropName, callback) { + if (!Array.isArray(val)) { + return undefined; + } + + const len = val.length, + parts = loc.split(':'), + step = parts[2] && Number.parseInt(parts[2]) || 1; + let start = parts[0] && Number.parseInt(parts[0]) || 0, + end = parts[1] && Number.parseInt(parts[1]) || len; + start = start < 0 ? Math.max(0, start + len) : Math.min(len, start); + end = end < 0 ? Math.max(0, end + len) : Math.min(len, end); + const ret = []; + + for (let i = start; i < end; i += step) { + const tmp = this._trace(unshift(i, expr), val, path, parent, parentPropName, callback, true); // Should only be possible to be an array here since first part of + // ``unshift(i, expr)` passed in above would not be empty, nor `~`, + // nor begin with `@` (as could return objects) + // This was causing excessive stack size in Node (with or + // without Babel) against our performance test: `ret.push(...tmp);` + + + tmp.forEach(t => { + ret.push(t); + }); + } + + return ret; +}; + +JSONPath.prototype._eval = function (code, _v, _vname, path, parent, parentPropName) { + this.currSandbox._$_parentProperty = parentPropName; + this.currSandbox._$_parent = parent; + this.currSandbox._$_property = _vname; + this.currSandbox._$_root = this.json; + this.currSandbox._$_v = _v; + const containsPath = code.includes('@path'); + + if (containsPath) { + this.currSandbox._$_path = JSONPath.toPathString(path.concat([_vname])); + } + + const scriptCacheKey = 'script:' + code; + + if (!JSONPath.cache[scriptCacheKey]) { + let script = code.replace(/@parentProperty/gu, '_$_parentProperty').replace(/@parent/gu, '_$_parent').replace(/@property/gu, '_$_property').replace(/@root/gu, '_$_root').replace(/@([.\s)[])/gu, '_$_v$1'); + + if (containsPath) { + script = script.replace(/@path/gu, '_$_path'); + } + + JSONPath.cache[scriptCacheKey] = new this.vm.Script(script); + } + + try { + return JSONPath.cache[scriptCacheKey].runInNewContext(this.currSandbox); + } catch (e) { + throw new Error('jsonPath: ' + e.message + ': ' + code); + } +}; // PUBLIC CLASS PROPERTIES AND METHODS +// Could store the cache object itself + + +JSONPath.cache = {}; +/** + * @param {string[]} pathArr Array to convert + * @returns {string} The path string + */ + +JSONPath.toPathString = function (pathArr) { + const x = pathArr, + n = x.length; + let p = '$'; + + for (let i = 1; i < n; i++) { + if (!/^(~|\^|@.*?\(\))$/u.test(x[i])) { + p += /^[0-9*]+$/u.test(x[i]) ? '[' + x[i] + ']' : "['" + x[i] + "']"; + } + } + + return p; +}; +/** + * @param {string} pointer JSON Path + * @returns {string} JSON Pointer + */ + + +JSONPath.toPointer = function (pointer) { + const x = pointer, + n = x.length; + let p = ''; + + for (let i = 1; i < n; i++) { + if (!/^(~|\^|@.*?\(\))$/u.test(x[i])) { + p += '/' + x[i].toString().replace(/~/gu, '~0').replace(/\//gu, '~1'); + } + } + + return p; +}; +/** + * @param {string} expr Expression to convert + * @returns {string[]} + */ + + +JSONPath.toPathArray = function (expr) { + const { + cache + } = JSONPath; + + if (cache[expr]) { + return cache[expr].concat(); + } + + const subx = []; + const normalized = expr // Properties + .replace(/@(?:null|boolean|number|string|integer|undefined|nonFinite|scalar|array|object|function|other)\(\)/gu, ';$&;') // Parenthetical evaluations (filtering and otherwise), directly + // within brackets or single quotes + .replace(/[['](\??\(.*?\))[\]']/gu, function ($0, $1) { + return '[#' + (subx.push($1) - 1) + ']'; + }) // Escape periods and tildes within properties + .replace(/\[['"]([^'\]]*)['"]\]/gu, function ($0, prop) { + return "['" + prop.replace(/\./gu, '%@%').replace(/~/gu, '%%@@%%') + "']"; + }) // Properties operator + .replace(/~/gu, ';~;') // Split by property boundaries + .replace(/['"]?\.['"]?(?![^[]*\])|\[['"]?/gu, ';') // Reinsert periods within properties + .replace(/%@%/gu, '.') // Reinsert tildes within properties + .replace(/%%@@%%/gu, '~') // Parent + .replace(/(?:;)?(\^+)(?:;)?/gu, function ($0, ups) { + return ';' + ups.split('').join(';') + ';'; + }) // Descendents + .replace(/;;;|;;/gu, ';..;') // Remove trailing + .replace(/;$|'?\]|'$/gu, ''); + const exprList = normalized.split(';').map(function (exp) { + const match = exp.match(/#(\d+)/u); + return !match || !match[1] ? exp : subx[match[1]]; + }); + cache[expr] = exprList; + return cache[expr].concat(); +}; + +JSONPath.prototype.vm = vm; + +// src/analyzer/util.ts +function query(queries, definition) { + const results = queries.map((q) => JSONPath({ path: q, json: definition, resultType: "all" })).filter((res) => res.length ? res : false).reduce((prev, next) => prev.concat(next), []); + results.sort((a, b) => { + if (a.pointer < b.pointer) { + return -1; + } else if (a.pointer > b.pointer) { + return 1; + } + return 0; + }); + return results; +} +function refizePointer(pointer) { + return `#${pointer}`; +} + +// src/rmoas.types.ts +function isRef(check) { + return check.$ref !== void 0; +} +function isOAS31(check) { + return check.openapi === "3.1.0"; +} +function isSchema$4(check, isPolymorphicAllOfChild = false) { + return check.type !== void 0 || check.allOf !== void 0 || check.anyOf !== void 0 || check.oneOf !== void 0 || isPolymorphicAllOfChild; +} + +/** + * Removes all key-value entries from the list cache. + * + * @private + * @name clear + * @memberOf ListCache + */ + +function listCacheClear$1() { + this.__data__ = []; + this.size = 0; +} + +var _listCacheClear = listCacheClear$1; + +/** + * Performs a + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * comparison between two values to determine if they are equivalent. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.eq(object, object); + * // => true + * + * _.eq(object, other); + * // => false + * + * _.eq('a', 'a'); + * // => true + * + * _.eq('a', Object('a')); + * // => false + * + * _.eq(NaN, NaN); + * // => true + */ + +function eq$7(value, other) { + return value === other || (value !== value && other !== other); +} + +var eq_1 = eq$7; + +var eq$6 = eq_1; + +/** + * Gets the index at which the `key` is found in `array` of key-value pairs. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} key The key to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function assocIndexOf$4(array, key) { + var length = array.length; + while (length--) { + if (eq$6(array[length][0], key)) { + return length; + } + } + return -1; +} + +var _assocIndexOf = assocIndexOf$4; + +var assocIndexOf$3 = _assocIndexOf; + +/** Used for built-in method references. */ +var arrayProto$1 = Array.prototype; + +/** Built-in value references. */ +var splice$1 = arrayProto$1.splice; + +/** + * Removes `key` and its value from the list cache. + * + * @private + * @name delete + * @memberOf ListCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function listCacheDelete$1(key) { + var data = this.__data__, + index = assocIndexOf$3(data, key); + + if (index < 0) { + return false; + } + var lastIndex = data.length - 1; + if (index == lastIndex) { + data.pop(); + } else { + splice$1.call(data, index, 1); + } + --this.size; + return true; +} + +var _listCacheDelete = listCacheDelete$1; + +var assocIndexOf$2 = _assocIndexOf; + +/** + * Gets the list cache value for `key`. + * + * @private + * @name get + * @memberOf ListCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function listCacheGet$1(key) { + var data = this.__data__, + index = assocIndexOf$2(data, key); + + return index < 0 ? undefined : data[index][1]; +} + +var _listCacheGet = listCacheGet$1; + +var assocIndexOf$1 = _assocIndexOf; + +/** + * Checks if a list cache value for `key` exists. + * + * @private + * @name has + * @memberOf ListCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function listCacheHas$1(key) { + return assocIndexOf$1(this.__data__, key) > -1; +} + +var _listCacheHas = listCacheHas$1; + +var assocIndexOf = _assocIndexOf; + +/** + * Sets the list cache `key` to `value`. + * + * @private + * @name set + * @memberOf ListCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the list cache instance. + */ +function listCacheSet$1(key, value) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + ++this.size; + data.push([key, value]); + } else { + data[index][1] = value; + } + return this; +} + +var _listCacheSet = listCacheSet$1; + +var listCacheClear = _listCacheClear, + listCacheDelete = _listCacheDelete, + listCacheGet = _listCacheGet, + listCacheHas = _listCacheHas, + listCacheSet = _listCacheSet; + +/** + * Creates an list cache object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function ListCache$4(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } +} + +// Add methods to `ListCache`. +ListCache$4.prototype.clear = listCacheClear; +ListCache$4.prototype['delete'] = listCacheDelete; +ListCache$4.prototype.get = listCacheGet; +ListCache$4.prototype.has = listCacheHas; +ListCache$4.prototype.set = listCacheSet; + +var _ListCache = ListCache$4; + +var ListCache$3 = _ListCache; + +/** + * Removes all key-value entries from the stack. + * + * @private + * @name clear + * @memberOf Stack + */ +function stackClear$1() { + this.__data__ = new ListCache$3; + this.size = 0; +} + +var _stackClear = stackClear$1; + +/** + * Removes `key` and its value from the stack. + * + * @private + * @name delete + * @memberOf Stack + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + +function stackDelete$1(key) { + var data = this.__data__, + result = data['delete'](key); + + this.size = data.size; + return result; +} + +var _stackDelete = stackDelete$1; + +/** + * Gets the stack value for `key`. + * + * @private + * @name get + * @memberOf Stack + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + +function stackGet$1(key) { + return this.__data__.get(key); +} + +var _stackGet = stackGet$1; + +/** + * Checks if a stack value for `key` exists. + * + * @private + * @name has + * @memberOf Stack + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + +function stackHas$1(key) { + return this.__data__.has(key); +} + +var _stackHas = stackHas$1; + +/** Detect free variable `global` from Node.js. */ + +var freeGlobal$1 = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal; + +var _freeGlobal = freeGlobal$1; + +var freeGlobal = _freeGlobal; + +/** Detect free variable `self`. */ +var freeSelf = typeof self == 'object' && self && self.Object === Object && self; + +/** Used as a reference to the global object. */ +var root$8 = freeGlobal || freeSelf || Function('return this')(); + +var _root = root$8; + +var root$7 = _root; + +/** Built-in value references. */ +var Symbol$7 = root$7.Symbol; + +var _Symbol = Symbol$7; + +var Symbol$6 = _Symbol; + +/** Used for built-in method references. */ +var objectProto$h = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty$f = objectProto$h.hasOwnProperty; + +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var nativeObjectToString$1 = objectProto$h.toString; + +/** Built-in value references. */ +var symToStringTag$1 = Symbol$6 ? Symbol$6.toStringTag : undefined; + +/** + * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the raw `toStringTag`. + */ +function getRawTag$1(value) { + var isOwn = hasOwnProperty$f.call(value, symToStringTag$1), + tag = value[symToStringTag$1]; + + try { + value[symToStringTag$1] = undefined; + var unmasked = true; + } catch (e) {} + + var result = nativeObjectToString$1.call(value); + if (unmasked) { + if (isOwn) { + value[symToStringTag$1] = tag; + } else { + delete value[symToStringTag$1]; + } + } + return result; +} + +var _getRawTag = getRawTag$1; + +/** Used for built-in method references. */ + +var objectProto$g = Object.prototype; + +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var nativeObjectToString = objectProto$g.toString; + +/** + * Converts `value` to a string using `Object.prototype.toString`. + * + * @private + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. + */ +function objectToString$2(value) { + return nativeObjectToString.call(value); +} + +var _objectToString = objectToString$2; + +var Symbol$5 = _Symbol, + getRawTag = _getRawTag, + objectToString$1 = _objectToString; + +/** `Object#toString` result references. */ +var nullTag = '[object Null]', + undefinedTag = '[object Undefined]'; + +/** Built-in value references. */ +var symToStringTag = Symbol$5 ? Symbol$5.toStringTag : undefined; + +/** + * The base implementation of `getTag` without fallbacks for buggy environments. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ +function baseGetTag$7(value) { + if (value == null) { + return value === undefined ? undefinedTag : nullTag; + } + return (symToStringTag && symToStringTag in Object(value)) + ? getRawTag(value) + : objectToString$1(value); +} + +var _baseGetTag = baseGetTag$7; + +/** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ + +function isObject$i(value) { + var type = typeof value; + return value != null && (type == 'object' || type == 'function'); +} + +var isObject_1 = isObject$i; + +var baseGetTag$6 = _baseGetTag, + isObject$h = isObject_1; + +/** `Object#toString` result references. */ +var asyncTag = '[object AsyncFunction]', + funcTag$3 = '[object Function]', + genTag$2 = '[object GeneratorFunction]', + proxyTag = '[object Proxy]'; + +/** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ +function isFunction$a(value) { + if (!isObject$h(value)) { + return false; + } + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 9 which returns 'object' for typed arrays and other constructors. + var tag = baseGetTag$6(value); + return tag == funcTag$3 || tag == genTag$2 || tag == asyncTag || tag == proxyTag; +} + +var isFunction_1 = isFunction$a; + +var root$6 = _root; + +/** Used to detect overreaching core-js shims. */ +var coreJsData$1 = root$6['__core-js_shared__']; + +var _coreJsData = coreJsData$1; + +var coreJsData = _coreJsData; + +/** Used to detect methods masquerading as native. */ +var maskSrcKey = (function() { + var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); + return uid ? ('Symbol(src)_1.' + uid) : ''; +}()); + +/** + * Checks if `func` has its source masked. + * + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` is masked, else `false`. + */ +function isMasked$1(func) { + return !!maskSrcKey && (maskSrcKey in func); +} + +var _isMasked = isMasked$1; + +/** Used for built-in method references. */ + +var funcProto$2 = Function.prototype; + +/** Used to resolve the decompiled source of functions. */ +var funcToString$2 = funcProto$2.toString; + +/** + * Converts `func` to its source code. + * + * @private + * @param {Function} func The function to convert. + * @returns {string} Returns the source code. + */ +function toSource$2(func) { + if (func != null) { + try { + return funcToString$2.call(func); + } catch (e) {} + try { + return (func + ''); + } catch (e) {} + } + return ''; +} + +var _toSource = toSource$2; + +var isFunction$9 = isFunction_1, + isMasked = _isMasked, + isObject$g = isObject_1, + toSource$1 = _toSource; + +/** + * Used to match `RegExp` + * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). + */ +var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; + +/** Used to detect host constructors (Safari). */ +var reIsHostCtor = /^\[object .+?Constructor\]$/; + +/** Used for built-in method references. */ +var funcProto$1 = Function.prototype, + objectProto$f = Object.prototype; + +/** Used to resolve the decompiled source of functions. */ +var funcToString$1 = funcProto$1.toString; + +/** Used to check objects for own properties. */ +var hasOwnProperty$e = objectProto$f.hasOwnProperty; + +/** Used to detect if a method is native. */ +var reIsNative = RegExp('^' + + funcToString$1.call(hasOwnProperty$e).replace(reRegExpChar, '\\$&') + .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' +); + +/** + * The base implementation of `_.isNative` without bad shim checks. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, + * else `false`. + */ +function baseIsNative$1(value) { + if (!isObject$g(value) || isMasked(value)) { + return false; + } + var pattern = isFunction$9(value) ? reIsNative : reIsHostCtor; + return pattern.test(toSource$1(value)); +} + +var _baseIsNative = baseIsNative$1; + +/** + * Gets the value at `key` of `object`. + * + * @private + * @param {Object} [object] The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. + */ + +function getValue$1(object, key) { + return object == null ? undefined : object[key]; +} + +var _getValue = getValue$1; + +var baseIsNative = _baseIsNative, + getValue = _getValue; + +/** + * Gets the native function at `key` of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the method to get. + * @returns {*} Returns the function if it's native, else `undefined`. + */ +function getNative$7(object, key) { + var value = getValue(object, key); + return baseIsNative(value) ? value : undefined; +} + +var _getNative = getNative$7; + +var getNative$6 = _getNative, + root$5 = _root; + +/* Built-in method references that are verified to be native. */ +var Map$4 = getNative$6(root$5, 'Map'); + +var _Map = Map$4; + +var getNative$5 = _getNative; + +/* Built-in method references that are verified to be native. */ +var nativeCreate$4 = getNative$5(Object, 'create'); + +var _nativeCreate = nativeCreate$4; + +var nativeCreate$3 = _nativeCreate; + +/** + * Removes all key-value entries from the hash. + * + * @private + * @name clear + * @memberOf Hash + */ +function hashClear$1() { + this.__data__ = nativeCreate$3 ? nativeCreate$3(null) : {}; + this.size = 0; +} + +var _hashClear = hashClear$1; + +/** + * Removes `key` and its value from the hash. + * + * @private + * @name delete + * @memberOf Hash + * @param {Object} hash The hash to modify. + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + +function hashDelete$1(key) { + var result = this.has(key) && delete this.__data__[key]; + this.size -= result ? 1 : 0; + return result; +} + +var _hashDelete = hashDelete$1; + +var nativeCreate$2 = _nativeCreate; + +/** Used to stand-in for `undefined` hash values. */ +var HASH_UNDEFINED$2 = '__lodash_hash_undefined__'; + +/** Used for built-in method references. */ +var objectProto$e = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty$d = objectProto$e.hasOwnProperty; + +/** + * Gets the hash value for `key`. + * + * @private + * @name get + * @memberOf Hash + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function hashGet$1(key) { + var data = this.__data__; + if (nativeCreate$2) { + var result = data[key]; + return result === HASH_UNDEFINED$2 ? undefined : result; + } + return hasOwnProperty$d.call(data, key) ? data[key] : undefined; +} + +var _hashGet = hashGet$1; + +var nativeCreate$1 = _nativeCreate; + +/** Used for built-in method references. */ +var objectProto$d = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty$c = objectProto$d.hasOwnProperty; + +/** + * Checks if a hash value for `key` exists. + * + * @private + * @name has + * @memberOf Hash + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function hashHas$1(key) { + var data = this.__data__; + return nativeCreate$1 ? (data[key] !== undefined) : hasOwnProperty$c.call(data, key); +} + +var _hashHas = hashHas$1; + +var nativeCreate = _nativeCreate; + +/** Used to stand-in for `undefined` hash values. */ +var HASH_UNDEFINED$1 = '__lodash_hash_undefined__'; + +/** + * Sets the hash `key` to `value`. + * + * @private + * @name set + * @memberOf Hash + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the hash instance. + */ +function hashSet$1(key, value) { + var data = this.__data__; + this.size += this.has(key) ? 0 : 1; + data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED$1 : value; + return this; +} + +var _hashSet = hashSet$1; + +var hashClear = _hashClear, + hashDelete = _hashDelete, + hashGet = _hashGet, + hashHas = _hashHas, + hashSet = _hashSet; + +/** + * Creates a hash object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function Hash$1(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } +} + +// Add methods to `Hash`. +Hash$1.prototype.clear = hashClear; +Hash$1.prototype['delete'] = hashDelete; +Hash$1.prototype.get = hashGet; +Hash$1.prototype.has = hashHas; +Hash$1.prototype.set = hashSet; + +var _Hash = Hash$1; + +var Hash = _Hash, + ListCache$2 = _ListCache, + Map$3 = _Map; + +/** + * Removes all key-value entries from the map. + * + * @private + * @name clear + * @memberOf MapCache + */ +function mapCacheClear$1() { + this.size = 0; + this.__data__ = { + 'hash': new Hash, + 'map': new (Map$3 || ListCache$2), + 'string': new Hash + }; +} + +var _mapCacheClear = mapCacheClear$1; + +/** + * Checks if `value` is suitable for use as unique object key. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is suitable, else `false`. + */ + +function isKeyable$1(value) { + var type = typeof value; + return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') + ? (value !== '__proto__') + : (value === null); +} + +var _isKeyable = isKeyable$1; + +var isKeyable = _isKeyable; + +/** + * Gets the data for `map`. + * + * @private + * @param {Object} map The map to query. + * @param {string} key The reference key. + * @returns {*} Returns the map data. + */ +function getMapData$4(map, key) { + var data = map.__data__; + return isKeyable(key) + ? data[typeof key == 'string' ? 'string' : 'hash'] + : data.map; +} + +var _getMapData = getMapData$4; + +var getMapData$3 = _getMapData; + +/** + * Removes `key` and its value from the map. + * + * @private + * @name delete + * @memberOf MapCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function mapCacheDelete$1(key) { + var result = getMapData$3(this, key)['delete'](key); + this.size -= result ? 1 : 0; + return result; +} + +var _mapCacheDelete = mapCacheDelete$1; + +var getMapData$2 = _getMapData; + +/** + * Gets the map value for `key`. + * + * @private + * @name get + * @memberOf MapCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function mapCacheGet$1(key) { + return getMapData$2(this, key).get(key); +} + +var _mapCacheGet = mapCacheGet$1; + +var getMapData$1 = _getMapData; + +/** + * Checks if a map value for `key` exists. + * + * @private + * @name has + * @memberOf MapCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function mapCacheHas$1(key) { + return getMapData$1(this, key).has(key); +} + +var _mapCacheHas = mapCacheHas$1; + +var getMapData = _getMapData; + +/** + * Sets the map `key` to `value`. + * + * @private + * @name set + * @memberOf MapCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the map cache instance. + */ +function mapCacheSet$1(key, value) { + var data = getMapData(this, key), + size = data.size; + + data.set(key, value); + this.size += data.size == size ? 0 : 1; + return this; +} + +var _mapCacheSet = mapCacheSet$1; + +var mapCacheClear = _mapCacheClear, + mapCacheDelete = _mapCacheDelete, + mapCacheGet = _mapCacheGet, + mapCacheHas = _mapCacheHas, + mapCacheSet = _mapCacheSet; + +/** + * Creates a map cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function MapCache$3(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } +} + +// Add methods to `MapCache`. +MapCache$3.prototype.clear = mapCacheClear; +MapCache$3.prototype['delete'] = mapCacheDelete; +MapCache$3.prototype.get = mapCacheGet; +MapCache$3.prototype.has = mapCacheHas; +MapCache$3.prototype.set = mapCacheSet; + +var _MapCache = MapCache$3; + +var ListCache$1 = _ListCache, + Map$2 = _Map, + MapCache$2 = _MapCache; + +/** Used as the size to enable large array optimizations. */ +var LARGE_ARRAY_SIZE$2 = 200; + +/** + * Sets the stack `key` to `value`. + * + * @private + * @name set + * @memberOf Stack + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the stack cache instance. + */ +function stackSet$1(key, value) { + var data = this.__data__; + if (data instanceof ListCache$1) { + var pairs = data.__data__; + if (!Map$2 || (pairs.length < LARGE_ARRAY_SIZE$2 - 1)) { + pairs.push([key, value]); + this.size = ++data.size; + return this; + } + data = this.__data__ = new MapCache$2(pairs); + } + data.set(key, value); + this.size = data.size; + return this; +} + +var _stackSet = stackSet$1; + +var ListCache = _ListCache, + stackClear = _stackClear, + stackDelete = _stackDelete, + stackGet = _stackGet, + stackHas = _stackHas, + stackSet = _stackSet; + +/** + * Creates a stack cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function Stack$4(entries) { + var data = this.__data__ = new ListCache(entries); + this.size = data.size; +} + +// Add methods to `Stack`. +Stack$4.prototype.clear = stackClear; +Stack$4.prototype['delete'] = stackDelete; +Stack$4.prototype.get = stackGet; +Stack$4.prototype.has = stackHas; +Stack$4.prototype.set = stackSet; + +var _Stack = Stack$4; + +/** + * A specialized version of `_.forEach` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns `array`. + */ + +function arrayEach$2(array, iteratee) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + if (iteratee(array[index], index, array) === false) { + break; + } + } + return array; +} + +var _arrayEach = arrayEach$2; + +var getNative$4 = _getNative; + +var defineProperty$2 = (function() { + try { + var func = getNative$4(Object, 'defineProperty'); + func({}, '', {}); + return func; + } catch (e) {} +}()); + +var _defineProperty = defineProperty$2; + +var defineProperty$1 = _defineProperty; + +/** + * The base implementation of `assignValue` and `assignMergeValue` without + * value checks. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ +function baseAssignValue$3(object, key, value) { + if (key == '__proto__' && defineProperty$1) { + defineProperty$1(object, key, { + 'configurable': true, + 'enumerable': true, + 'value': value, + 'writable': true + }); + } else { + object[key] = value; + } +} + +var _baseAssignValue = baseAssignValue$3; + +var baseAssignValue$2 = _baseAssignValue, + eq$5 = eq_1; + +/** Used for built-in method references. */ +var objectProto$c = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty$b = objectProto$c.hasOwnProperty; + +/** + * Assigns `value` to `key` of `object` if the existing value is not equivalent + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ +function assignValue$3(object, key, value) { + var objValue = object[key]; + if (!(hasOwnProperty$b.call(object, key) && eq$5(objValue, value)) || + (value === undefined && !(key in object))) { + baseAssignValue$2(object, key, value); + } +} + +var _assignValue = assignValue$3; + +var assignValue$2 = _assignValue, + baseAssignValue$1 = _baseAssignValue; + +/** + * Copies properties of `source` to `object`. + * + * @private + * @param {Object} source The object to copy properties from. + * @param {Array} props The property identifiers to copy. + * @param {Object} [object={}] The object to copy properties to. + * @param {Function} [customizer] The function to customize copied values. + * @returns {Object} Returns `object`. + */ +function copyObject$6(source, props, object, customizer) { + var isNew = !object; + object || (object = {}); + + var index = -1, + length = props.length; + + while (++index < length) { + var key = props[index]; + + var newValue = customizer + ? customizer(object[key], source[key], key, object, source) + : undefined; + + if (newValue === undefined) { + newValue = source[key]; + } + if (isNew) { + baseAssignValue$1(object, key, newValue); + } else { + assignValue$2(object, key, newValue); + } + } + return object; +} + +var _copyObject = copyObject$6; + +/** + * The base implementation of `_.times` without support for iteratee shorthands + * or max array length checks. + * + * @private + * @param {number} n The number of times to invoke `iteratee`. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the array of results. + */ + +function baseTimes$2(n, iteratee) { + var index = -1, + result = Array(n); + + while (++index < n) { + result[index] = iteratee(index); + } + return result; +} + +var _baseTimes = baseTimes$2; + +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ + +function isObjectLike$b(value) { + return value != null && typeof value == 'object'; +} + +var isObjectLike_1 = isObjectLike$b; + +var baseGetTag$5 = _baseGetTag, + isObjectLike$a = isObjectLike_1; + +/** `Object#toString` result references. */ +var argsTag$4 = '[object Arguments]'; + +/** + * The base implementation of `_.isArguments`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + */ +function baseIsArguments$1(value) { + return isObjectLike$a(value) && baseGetTag$5(value) == argsTag$4; +} + +var _baseIsArguments = baseIsArguments$1; + +var baseIsArguments = _baseIsArguments, + isObjectLike$9 = isObjectLike_1; + +/** Used for built-in method references. */ +var objectProto$b = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty$a = objectProto$b.hasOwnProperty; + +/** Built-in value references. */ +var propertyIsEnumerable$2 = objectProto$b.propertyIsEnumerable; + +/** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ +var isArguments$6 = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { + return isObjectLike$9(value) && hasOwnProperty$a.call(value, 'callee') && + !propertyIsEnumerable$2.call(value, 'callee'); +}; + +var isArguments_1 = isArguments$6; + +/** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ + +var isArray$k = Array.isArray; + +var isArray_1 = isArray$k; + +var isBuffer$4 = {exports: {}}; + +/** + * This method returns `false`. + * + * @static + * @memberOf _ + * @since 4.13.0 + * @category Util + * @returns {boolean} Returns `false`. + * @example + * + * _.times(2, _.stubFalse); + * // => [false, false] + */ + +function stubFalse() { + return false; +} + +var stubFalse_1 = stubFalse; + +isBuffer$4.exports; + +(function (module, exports) { + var root = _root, + stubFalse = stubFalse_1; + + /** Detect free variable `exports`. */ + var freeExports = exports && !exports.nodeType && exports; + + /** Detect free variable `module`. */ + var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module; + + /** Detect the popular CommonJS extension `module.exports`. */ + var moduleExports = freeModule && freeModule.exports === freeExports; + + /** Built-in value references. */ + var Buffer = moduleExports ? root.Buffer : undefined; + + /* Built-in method references for those with the same name as other `lodash` methods. */ + var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined; + + /** + * Checks if `value` is a buffer. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. + * @example + * + * _.isBuffer(new Buffer(2)); + * // => true + * + * _.isBuffer(new Uint8Array(2)); + * // => false + */ + var isBuffer = nativeIsBuffer || stubFalse; + + module.exports = isBuffer; +} (isBuffer$4, isBuffer$4.exports)); + +var isBufferExports = isBuffer$4.exports; + +/** Used as references for various `Number` constants. */ + +var MAX_SAFE_INTEGER$2 = 9007199254740991; + +/** Used to detect unsigned integer values. */ +var reIsUint$1 = /^(?:0|[1-9]\d*)$/; + +/** + * Checks if `value` is a valid array-like index. + * + * @private + * @param {*} value The value to check. + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + */ +function isIndex$4(value, length) { + var type = typeof value; + length = length == null ? MAX_SAFE_INTEGER$2 : length; + + return !!length && + (type == 'number' || + (type != 'symbol' && reIsUint$1.test(value))) && + (value > -1 && value % 1 == 0 && value < length); +} + +var _isIndex = isIndex$4; + +/** Used as references for various `Number` constants. */ + +var MAX_SAFE_INTEGER$1 = 9007199254740991; + +/** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ +function isLength$4(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER$1; +} + +var isLength_1 = isLength$4; + +var baseGetTag$4 = _baseGetTag, + isLength$3 = isLength_1, + isObjectLike$8 = isObjectLike_1; + +/** `Object#toString` result references. */ +var argsTag$3 = '[object Arguments]', + arrayTag$2 = '[object Array]', + boolTag$4 = '[object Boolean]', + dateTag$3 = '[object Date]', + errorTag$2 = '[object Error]', + funcTag$2 = '[object Function]', + mapTag$5 = '[object Map]', + numberTag$3 = '[object Number]', + objectTag$4 = '[object Object]', + regexpTag$3 = '[object RegExp]', + setTag$5 = '[object Set]', + stringTag$3 = '[object String]', + weakMapTag$2 = '[object WeakMap]'; + +var arrayBufferTag$3 = '[object ArrayBuffer]', + dataViewTag$4 = '[object DataView]', + float32Tag$2 = '[object Float32Array]', + float64Tag$2 = '[object Float64Array]', + int8Tag$2 = '[object Int8Array]', + int16Tag$2 = '[object Int16Array]', + int32Tag$2 = '[object Int32Array]', + uint8Tag$2 = '[object Uint8Array]', + uint8ClampedTag$2 = '[object Uint8ClampedArray]', + uint16Tag$2 = '[object Uint16Array]', + uint32Tag$2 = '[object Uint32Array]'; + +/** Used to identify `toStringTag` values of typed arrays. */ +var typedArrayTags = {}; +typedArrayTags[float32Tag$2] = typedArrayTags[float64Tag$2] = +typedArrayTags[int8Tag$2] = typedArrayTags[int16Tag$2] = +typedArrayTags[int32Tag$2] = typedArrayTags[uint8Tag$2] = +typedArrayTags[uint8ClampedTag$2] = typedArrayTags[uint16Tag$2] = +typedArrayTags[uint32Tag$2] = true; +typedArrayTags[argsTag$3] = typedArrayTags[arrayTag$2] = +typedArrayTags[arrayBufferTag$3] = typedArrayTags[boolTag$4] = +typedArrayTags[dataViewTag$4] = typedArrayTags[dateTag$3] = +typedArrayTags[errorTag$2] = typedArrayTags[funcTag$2] = +typedArrayTags[mapTag$5] = typedArrayTags[numberTag$3] = +typedArrayTags[objectTag$4] = typedArrayTags[regexpTag$3] = +typedArrayTags[setTag$5] = typedArrayTags[stringTag$3] = +typedArrayTags[weakMapTag$2] = false; + +/** + * The base implementation of `_.isTypedArray` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + */ +function baseIsTypedArray$1(value) { + return isObjectLike$8(value) && + isLength$3(value.length) && !!typedArrayTags[baseGetTag$4(value)]; +} + +var _baseIsTypedArray = baseIsTypedArray$1; + +/** + * The base implementation of `_.unary` without support for storing metadata. + * + * @private + * @param {Function} func The function to cap arguments for. + * @returns {Function} Returns the new capped function. + */ + +function baseUnary$7(func) { + return function(value) { + return func(value); + }; +} + +var _baseUnary = baseUnary$7; + +var _nodeUtil = {exports: {}}; + +_nodeUtil.exports; + +(function (module, exports) { + var freeGlobal = _freeGlobal; + + /** Detect free variable `exports`. */ + var freeExports = exports && !exports.nodeType && exports; + + /** Detect free variable `module`. */ + var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module; + + /** Detect the popular CommonJS extension `module.exports`. */ + var moduleExports = freeModule && freeModule.exports === freeExports; + + /** Detect free variable `process` from Node.js. */ + var freeProcess = moduleExports && freeGlobal.process; + + /** Used to access faster Node.js helpers. */ + var nodeUtil = (function() { + try { + // Use `util.types` for Node.js 10+. + var types = freeModule && freeModule.require && freeModule.require('util').types; + + if (types) { + return types; + } + + // Legacy `process.binding('util')` for Node.js < 10. + return freeProcess && freeProcess.binding && freeProcess.binding('util'); + } catch (e) {} + }()); + + module.exports = nodeUtil; +} (_nodeUtil, _nodeUtil.exports)); + +var _nodeUtilExports = _nodeUtil.exports; + +var baseIsTypedArray = _baseIsTypedArray, + baseUnary$6 = _baseUnary, + nodeUtil$2 = _nodeUtilExports; + +/* Node.js helper references. */ +var nodeIsTypedArray = nodeUtil$2 && nodeUtil$2.isTypedArray; + +/** + * Checks if `value` is classified as a typed array. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + * @example + * + * _.isTypedArray(new Uint8Array); + * // => true + * + * _.isTypedArray([]); + * // => false + */ +var isTypedArray$3 = nodeIsTypedArray ? baseUnary$6(nodeIsTypedArray) : baseIsTypedArray; + +var isTypedArray_1 = isTypedArray$3; + +var baseTimes$1 = _baseTimes, + isArguments$5 = isArguments_1, + isArray$j = isArray_1, + isBuffer$3 = isBufferExports, + isIndex$3 = _isIndex, + isTypedArray$2 = isTypedArray_1; + +/** Used for built-in method references. */ +var objectProto$a = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty$9 = objectProto$a.hasOwnProperty; + +/** + * Creates an array of the enumerable property names of the array-like `value`. + * + * @private + * @param {*} value The value to query. + * @param {boolean} inherited Specify returning inherited property names. + * @returns {Array} Returns the array of property names. + */ +function arrayLikeKeys$3(value, inherited) { + var isArr = isArray$j(value), + isArg = !isArr && isArguments$5(value), + isBuff = !isArr && !isArg && isBuffer$3(value), + isType = !isArr && !isArg && !isBuff && isTypedArray$2(value), + skipIndexes = isArr || isArg || isBuff || isType, + result = skipIndexes ? baseTimes$1(value.length, String) : [], + length = result.length; + + for (var key in value) { + if ((inherited || hasOwnProperty$9.call(value, key)) && + !(skipIndexes && ( + // Safari 9 has enumerable `arguments.length` in strict mode. + key == 'length' || + // Node.js 0.10 has enumerable non-index properties on buffers. + (isBuff && (key == 'offset' || key == 'parent')) || + // PhantomJS 2 has enumerable non-index properties on typed arrays. + (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || + // Skip index properties. + isIndex$3(key, length) + ))) { + result.push(key); + } + } + return result; +} + +var _arrayLikeKeys = arrayLikeKeys$3; + +/** Used for built-in method references. */ + +var objectProto$9 = Object.prototype; + +/** + * Checks if `value` is likely a prototype object. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. + */ +function isPrototype$4(value) { + var Ctor = value && value.constructor, + proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto$9; + + return value === proto; +} + +var _isPrototype = isPrototype$4; + +/** + * Creates a unary function that invokes `func` with its argument transformed. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ + +function overArg$3(func, transform) { + return function(arg) { + return func(transform(arg)); + }; +} + +var _overArg = overArg$3; + +var overArg$2 = _overArg; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeKeys$2 = overArg$2(Object.keys, Object); + +var _nativeKeys = nativeKeys$2; + +var isPrototype$3 = _isPrototype, + nativeKeys$1 = _nativeKeys; + +/** Used for built-in method references. */ +var objectProto$8 = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty$8 = objectProto$8.hasOwnProperty; + +/** + * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ +function baseKeys$2(object) { + if (!isPrototype$3(object)) { + return nativeKeys$1(object); + } + var result = []; + for (var key in Object(object)) { + if (hasOwnProperty$8.call(object, key) && key != 'constructor') { + result.push(key); + } + } + return result; +} + +var _baseKeys = baseKeys$2; + +var isFunction$8 = isFunction_1, + isLength$2 = isLength_1; + +/** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ +function isArrayLike$b(value) { + return value != null && isLength$2(value.length) && !isFunction$8(value); +} + +var isArrayLike_1 = isArrayLike$b; + +var arrayLikeKeys$2 = _arrayLikeKeys, + baseKeys$1 = _baseKeys, + isArrayLike$a = isArrayLike_1; + +/** + * Creates an array of the own enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. See the + * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * for more details. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keys(new Foo); + * // => ['a', 'b'] (iteration order is not guaranteed) + * + * _.keys('hi'); + * // => ['0', '1'] + */ +function keys$c(object) { + return isArrayLike$a(object) ? arrayLikeKeys$2(object) : baseKeys$1(object); +} + +var keys_1 = keys$c; + +var copyObject$5 = _copyObject, + keys$b = keys_1; + +/** + * The base implementation of `_.assign` without support for multiple sources + * or `customizer` functions. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @returns {Object} Returns `object`. + */ +function baseAssign$1(object, source) { + return object && copyObject$5(source, keys$b(source), object); +} + +var _baseAssign = baseAssign$1; + +/** + * This function is like + * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * except that it includes inherited enumerable properties. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ + +function nativeKeysIn$1(object) { + var result = []; + if (object != null) { + for (var key in Object(object)) { + result.push(key); + } + } + return result; +} + +var _nativeKeysIn = nativeKeysIn$1; + +var isObject$f = isObject_1, + isPrototype$2 = _isPrototype, + nativeKeysIn = _nativeKeysIn; + +/** Used for built-in method references. */ +var objectProto$7 = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty$7 = objectProto$7.hasOwnProperty; + +/** + * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ +function baseKeysIn$1(object) { + if (!isObject$f(object)) { + return nativeKeysIn(object); + } + var isProto = isPrototype$2(object), + result = []; + + for (var key in object) { + if (!(key == 'constructor' && (isProto || !hasOwnProperty$7.call(object, key)))) { + result.push(key); + } + } + return result; +} + +var _baseKeysIn = baseKeysIn$1; + +var arrayLikeKeys$1 = _arrayLikeKeys, + baseKeysIn = _baseKeysIn, + isArrayLike$9 = isArrayLike_1; + +/** + * Creates an array of the own and inherited enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keysIn(new Foo); + * // => ['a', 'b', 'c'] (iteration order is not guaranteed) + */ +function keysIn$6(object) { + return isArrayLike$9(object) ? arrayLikeKeys$1(object, true) : baseKeysIn(object); +} + +var keysIn_1 = keysIn$6; + +var copyObject$4 = _copyObject, + keysIn$5 = keysIn_1; + +/** + * The base implementation of `_.assignIn` without support for multiple sources + * or `customizer` functions. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @returns {Object} Returns `object`. + */ +function baseAssignIn$1(object, source) { + return object && copyObject$4(source, keysIn$5(source), object); +} + +var _baseAssignIn = baseAssignIn$1; + +var _cloneBuffer = {exports: {}}; + +_cloneBuffer.exports; + +(function (module, exports) { + var root = _root; + + /** Detect free variable `exports`. */ + var freeExports = exports && !exports.nodeType && exports; + + /** Detect free variable `module`. */ + var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module; + + /** Detect the popular CommonJS extension `module.exports`. */ + var moduleExports = freeModule && freeModule.exports === freeExports; + + /** Built-in value references. */ + var Buffer = moduleExports ? root.Buffer : undefined, + allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined; + + /** + * Creates a clone of `buffer`. + * + * @private + * @param {Buffer} buffer The buffer to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Buffer} Returns the cloned buffer. + */ + function cloneBuffer(buffer, isDeep) { + if (isDeep) { + return buffer.slice(); + } + var length = buffer.length, + result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); + + buffer.copy(result); + return result; + } + + module.exports = cloneBuffer; +} (_cloneBuffer, _cloneBuffer.exports)); + +var _cloneBufferExports = _cloneBuffer.exports; + +/** + * Copies the values of `source` to `array`. + * + * @private + * @param {Array} source The array to copy values from. + * @param {Array} [array=[]] The array to copy values to. + * @returns {Array} Returns `array`. + */ + +function copyArray$3(source, array) { + var index = -1, + length = source.length; + + array || (array = Array(length)); + while (++index < length) { + array[index] = source[index]; + } + return array; +} + +var _copyArray = copyArray$3; + +/** + * A specialized version of `_.filter` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + */ + +function arrayFilter$1(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index]; + if (predicate(value, index, array)) { + result[resIndex++] = value; + } + } + return result; +} + +var _arrayFilter = arrayFilter$1; + +/** + * This method returns a new empty array. + * + * @static + * @memberOf _ + * @since 4.13.0 + * @category Util + * @returns {Array} Returns the new empty array. + * @example + * + * var arrays = _.times(2, _.stubArray); + * + * console.log(arrays); + * // => [[], []] + * + * console.log(arrays[0] === arrays[1]); + * // => false + */ + +function stubArray$2() { + return []; +} + +var stubArray_1 = stubArray$2; + +var arrayFilter = _arrayFilter, + stubArray$1 = stubArray_1; + +/** Used for built-in method references. */ +var objectProto$6 = Object.prototype; + +/** Built-in value references. */ +var propertyIsEnumerable$1 = objectProto$6.propertyIsEnumerable; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeGetSymbols$1 = Object.getOwnPropertySymbols; + +/** + * Creates an array of the own enumerable symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of symbols. + */ +var getSymbols$3 = !nativeGetSymbols$1 ? stubArray$1 : function(object) { + if (object == null) { + return []; + } + object = Object(object); + return arrayFilter(nativeGetSymbols$1(object), function(symbol) { + return propertyIsEnumerable$1.call(object, symbol); + }); +}; + +var _getSymbols = getSymbols$3; + +var copyObject$3 = _copyObject, + getSymbols$2 = _getSymbols; + +/** + * Copies own symbols of `source` to `object`. + * + * @private + * @param {Object} source The object to copy symbols from. + * @param {Object} [object={}] The object to copy symbols to. + * @returns {Object} Returns `object`. + */ +function copySymbols$1(source, object) { + return copyObject$3(source, getSymbols$2(source), object); +} + +var _copySymbols = copySymbols$1; + +/** + * Appends the elements of `values` to `array`. + * + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to append. + * @returns {Array} Returns `array`. + */ + +function arrayPush$3(array, values) { + var index = -1, + length = values.length, + offset = array.length; + + while (++index < length) { + array[offset + index] = values[index]; + } + return array; +} + +var _arrayPush = arrayPush$3; + +var overArg$1 = _overArg; + +/** Built-in value references. */ +var getPrototype$3 = overArg$1(Object.getPrototypeOf, Object); + +var _getPrototype = getPrototype$3; + +var arrayPush$2 = _arrayPush, + getPrototype$2 = _getPrototype, + getSymbols$1 = _getSymbols, + stubArray = stubArray_1; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeGetSymbols = Object.getOwnPropertySymbols; + +/** + * Creates an array of the own and inherited enumerable symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of symbols. + */ +var getSymbolsIn$2 = !nativeGetSymbols ? stubArray : function(object) { + var result = []; + while (object) { + arrayPush$2(result, getSymbols$1(object)); + object = getPrototype$2(object); + } + return result; +}; + +var _getSymbolsIn = getSymbolsIn$2; + +var copyObject$2 = _copyObject, + getSymbolsIn$1 = _getSymbolsIn; + +/** + * Copies own and inherited symbols of `source` to `object`. + * + * @private + * @param {Object} source The object to copy symbols from. + * @param {Object} [object={}] The object to copy symbols to. + * @returns {Object} Returns `object`. + */ +function copySymbolsIn$1(source, object) { + return copyObject$2(source, getSymbolsIn$1(source), object); +} + +var _copySymbolsIn = copySymbolsIn$1; + +var arrayPush$1 = _arrayPush, + isArray$i = isArray_1; + +/** + * The base implementation of `getAllKeys` and `getAllKeysIn` which uses + * `keysFunc` and `symbolsFunc` to get the enumerable property names and + * symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Function} keysFunc The function to get the keys of `object`. + * @param {Function} symbolsFunc The function to get the symbols of `object`. + * @returns {Array} Returns the array of property names and symbols. + */ +function baseGetAllKeys$2(object, keysFunc, symbolsFunc) { + var result = keysFunc(object); + return isArray$i(object) ? result : arrayPush$1(result, symbolsFunc(object)); +} + +var _baseGetAllKeys = baseGetAllKeys$2; + +var baseGetAllKeys$1 = _baseGetAllKeys, + getSymbols = _getSymbols, + keys$a = keys_1; + +/** + * Creates an array of own enumerable property names and symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names and symbols. + */ +function getAllKeys$2(object) { + return baseGetAllKeys$1(object, keys$a, getSymbols); +} + +var _getAllKeys = getAllKeys$2; + +var baseGetAllKeys = _baseGetAllKeys, + getSymbolsIn = _getSymbolsIn, + keysIn$4 = keysIn_1; + +/** + * Creates an array of own and inherited enumerable property names and + * symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names and symbols. + */ +function getAllKeysIn$1(object) { + return baseGetAllKeys(object, keysIn$4, getSymbolsIn); +} + +var _getAllKeysIn = getAllKeysIn$1; + +var getNative$3 = _getNative, + root$4 = _root; + +/* Built-in method references that are verified to be native. */ +var DataView$2 = getNative$3(root$4, 'DataView'); + +var _DataView = DataView$2; + +var getNative$2 = _getNative, + root$3 = _root; + +/* Built-in method references that are verified to be native. */ +var Promise$2 = getNative$2(root$3, 'Promise'); + +var _Promise = Promise$2; + +var getNative$1 = _getNative, + root$2 = _root; + +/* Built-in method references that are verified to be native. */ +var Set$3 = getNative$1(root$2, 'Set'); + +var _Set = Set$3; + +var getNative = _getNative, + root$1 = _root; + +/* Built-in method references that are verified to be native. */ +var WeakMap$2 = getNative(root$1, 'WeakMap'); + +var _WeakMap = WeakMap$2; + +var DataView$1 = _DataView, + Map$1 = _Map, + Promise$1 = _Promise, + Set$2 = _Set, + WeakMap$1 = _WeakMap, + baseGetTag$3 = _baseGetTag, + toSource = _toSource; + +/** `Object#toString` result references. */ +var mapTag$4 = '[object Map]', + objectTag$3 = '[object Object]', + promiseTag = '[object Promise]', + setTag$4 = '[object Set]', + weakMapTag$1 = '[object WeakMap]'; + +var dataViewTag$3 = '[object DataView]'; + +/** Used to detect maps, sets, and weakmaps. */ +var dataViewCtorString = toSource(DataView$1), + mapCtorString = toSource(Map$1), + promiseCtorString = toSource(Promise$1), + setCtorString = toSource(Set$2), + weakMapCtorString = toSource(WeakMap$1); + +/** + * Gets the `toStringTag` of `value`. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ +var getTag$4 = baseGetTag$3; + +// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. +if ((DataView$1 && getTag$4(new DataView$1(new ArrayBuffer(1))) != dataViewTag$3) || + (Map$1 && getTag$4(new Map$1) != mapTag$4) || + (Promise$1 && getTag$4(Promise$1.resolve()) != promiseTag) || + (Set$2 && getTag$4(new Set$2) != setTag$4) || + (WeakMap$1 && getTag$4(new WeakMap$1) != weakMapTag$1)) { + getTag$4 = function(value) { + var result = baseGetTag$3(value), + Ctor = result == objectTag$3 ? value.constructor : undefined, + ctorString = Ctor ? toSource(Ctor) : ''; + + if (ctorString) { + switch (ctorString) { + case dataViewCtorString: return dataViewTag$3; + case mapCtorString: return mapTag$4; + case promiseCtorString: return promiseTag; + case setCtorString: return setTag$4; + case weakMapCtorString: return weakMapTag$1; + } + } + return result; + }; +} + +var _getTag = getTag$4; + +/** Used for built-in method references. */ + +var objectProto$5 = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty$6 = objectProto$5.hasOwnProperty; + +/** + * Initializes an array clone. + * + * @private + * @param {Array} array The array to clone. + * @returns {Array} Returns the initialized clone. + */ +function initCloneArray$1(array) { + var length = array.length, + result = new array.constructor(length); + + // Add properties assigned by `RegExp#exec`. + if (length && typeof array[0] == 'string' && hasOwnProperty$6.call(array, 'index')) { + result.index = array.index; + result.input = array.input; + } + return result; +} + +var _initCloneArray = initCloneArray$1; + +var root = _root; + +/** Built-in value references. */ +var Uint8Array$3 = root.Uint8Array; + +var _Uint8Array = Uint8Array$3; + +var Uint8Array$2 = _Uint8Array; + +/** + * Creates a clone of `arrayBuffer`. + * + * @private + * @param {ArrayBuffer} arrayBuffer The array buffer to clone. + * @returns {ArrayBuffer} Returns the cloned array buffer. + */ +function cloneArrayBuffer$3(arrayBuffer) { + var result = new arrayBuffer.constructor(arrayBuffer.byteLength); + new Uint8Array$2(result).set(new Uint8Array$2(arrayBuffer)); + return result; +} + +var _cloneArrayBuffer = cloneArrayBuffer$3; + +var cloneArrayBuffer$2 = _cloneArrayBuffer; + +/** + * Creates a clone of `dataView`. + * + * @private + * @param {Object} dataView The data view to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned data view. + */ +function cloneDataView$1(dataView, isDeep) { + var buffer = isDeep ? cloneArrayBuffer$2(dataView.buffer) : dataView.buffer; + return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); +} + +var _cloneDataView = cloneDataView$1; + +/** Used to match `RegExp` flags from their coerced string values. */ + +var reFlags = /\w*$/; + +/** + * Creates a clone of `regexp`. + * + * @private + * @param {Object} regexp The regexp to clone. + * @returns {Object} Returns the cloned regexp. + */ +function cloneRegExp$1(regexp) { + var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); + result.lastIndex = regexp.lastIndex; + return result; +} + +var _cloneRegExp = cloneRegExp$1; + +var Symbol$4 = _Symbol; + +/** Used to convert symbols to primitives and strings. */ +var symbolProto$2 = Symbol$4 ? Symbol$4.prototype : undefined, + symbolValueOf$1 = symbolProto$2 ? symbolProto$2.valueOf : undefined; + +/** + * Creates a clone of the `symbol` object. + * + * @private + * @param {Object} symbol The symbol object to clone. + * @returns {Object} Returns the cloned symbol object. + */ +function cloneSymbol$1(symbol) { + return symbolValueOf$1 ? Object(symbolValueOf$1.call(symbol)) : {}; +} + +var _cloneSymbol = cloneSymbol$1; + +var cloneArrayBuffer$1 = _cloneArrayBuffer; + +/** + * Creates a clone of `typedArray`. + * + * @private + * @param {Object} typedArray The typed array to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned typed array. + */ +function cloneTypedArray$2(typedArray, isDeep) { + var buffer = isDeep ? cloneArrayBuffer$1(typedArray.buffer) : typedArray.buffer; + return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); +} + +var _cloneTypedArray = cloneTypedArray$2; + +var cloneArrayBuffer = _cloneArrayBuffer, + cloneDataView = _cloneDataView, + cloneRegExp = _cloneRegExp, + cloneSymbol = _cloneSymbol, + cloneTypedArray$1 = _cloneTypedArray; + +/** `Object#toString` result references. */ +var boolTag$3 = '[object Boolean]', + dateTag$2 = '[object Date]', + mapTag$3 = '[object Map]', + numberTag$2 = '[object Number]', + regexpTag$2 = '[object RegExp]', + setTag$3 = '[object Set]', + stringTag$2 = '[object String]', + symbolTag$3 = '[object Symbol]'; + +var arrayBufferTag$2 = '[object ArrayBuffer]', + dataViewTag$2 = '[object DataView]', + float32Tag$1 = '[object Float32Array]', + float64Tag$1 = '[object Float64Array]', + int8Tag$1 = '[object Int8Array]', + int16Tag$1 = '[object Int16Array]', + int32Tag$1 = '[object Int32Array]', + uint8Tag$1 = '[object Uint8Array]', + uint8ClampedTag$1 = '[object Uint8ClampedArray]', + uint16Tag$1 = '[object Uint16Array]', + uint32Tag$1 = '[object Uint32Array]'; + +/** + * Initializes an object clone based on its `toStringTag`. + * + * **Note:** This function only supports cloning values with tags of + * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`. + * + * @private + * @param {Object} object The object to clone. + * @param {string} tag The `toStringTag` of the object to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the initialized clone. + */ +function initCloneByTag$1(object, tag, isDeep) { + var Ctor = object.constructor; + switch (tag) { + case arrayBufferTag$2: + return cloneArrayBuffer(object); + + case boolTag$3: + case dateTag$2: + return new Ctor(+object); + + case dataViewTag$2: + return cloneDataView(object, isDeep); + + case float32Tag$1: case float64Tag$1: + case int8Tag$1: case int16Tag$1: case int32Tag$1: + case uint8Tag$1: case uint8ClampedTag$1: case uint16Tag$1: case uint32Tag$1: + return cloneTypedArray$1(object, isDeep); + + case mapTag$3: + return new Ctor; + + case numberTag$2: + case stringTag$2: + return new Ctor(object); + + case regexpTag$2: + return cloneRegExp(object); + + case setTag$3: + return new Ctor; + + case symbolTag$3: + return cloneSymbol(object); + } +} + +var _initCloneByTag = initCloneByTag$1; + +var isObject$e = isObject_1; + +/** Built-in value references. */ +var objectCreate = Object.create; + +/** + * The base implementation of `_.create` without support for assigning + * properties to the created object. + * + * @private + * @param {Object} proto The object to inherit from. + * @returns {Object} Returns the new object. + */ +var baseCreate$1 = (function() { + function object() {} + return function(proto) { + if (!isObject$e(proto)) { + return {}; + } + if (objectCreate) { + return objectCreate(proto); + } + object.prototype = proto; + var result = new object; + object.prototype = undefined; + return result; + }; +}()); + +var _baseCreate = baseCreate$1; + +var baseCreate = _baseCreate, + getPrototype$1 = _getPrototype, + isPrototype$1 = _isPrototype; + +/** + * Initializes an object clone. + * + * @private + * @param {Object} object The object to clone. + * @returns {Object} Returns the initialized clone. + */ +function initCloneObject$2(object) { + return (typeof object.constructor == 'function' && !isPrototype$1(object)) + ? baseCreate(getPrototype$1(object)) + : {}; +} + +var _initCloneObject = initCloneObject$2; + +var getTag$3 = _getTag, + isObjectLike$7 = isObjectLike_1; + +/** `Object#toString` result references. */ +var mapTag$2 = '[object Map]'; + +/** + * The base implementation of `_.isMap` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a map, else `false`. + */ +function baseIsMap$1(value) { + return isObjectLike$7(value) && getTag$3(value) == mapTag$2; +} + +var _baseIsMap = baseIsMap$1; + +var baseIsMap = _baseIsMap, + baseUnary$5 = _baseUnary, + nodeUtil$1 = _nodeUtilExports; + +/* Node.js helper references. */ +var nodeIsMap = nodeUtil$1 && nodeUtil$1.isMap; + +/** + * Checks if `value` is classified as a `Map` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a map, else `false`. + * @example + * + * _.isMap(new Map); + * // => true + * + * _.isMap(new WeakMap); + * // => false + */ +var isMap$1 = nodeIsMap ? baseUnary$5(nodeIsMap) : baseIsMap; + +var isMap_1 = isMap$1; + +var getTag$2 = _getTag, + isObjectLike$6 = isObjectLike_1; + +/** `Object#toString` result references. */ +var setTag$2 = '[object Set]'; + +/** + * The base implementation of `_.isSet` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a set, else `false`. + */ +function baseIsSet$1(value) { + return isObjectLike$6(value) && getTag$2(value) == setTag$2; +} + +var _baseIsSet = baseIsSet$1; + +var baseIsSet = _baseIsSet, + baseUnary$4 = _baseUnary, + nodeUtil = _nodeUtilExports; + +/* Node.js helper references. */ +var nodeIsSet = nodeUtil && nodeUtil.isSet; + +/** + * Checks if `value` is classified as a `Set` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a set, else `false`. + * @example + * + * _.isSet(new Set); + * // => true + * + * _.isSet(new WeakSet); + * // => false + */ +var isSet$1 = nodeIsSet ? baseUnary$4(nodeIsSet) : baseIsSet; + +var isSet_1 = isSet$1; + +var Stack$3 = _Stack, + arrayEach$1 = _arrayEach, + assignValue$1 = _assignValue, + baseAssign = _baseAssign, + baseAssignIn = _baseAssignIn, + cloneBuffer$1 = _cloneBufferExports, + copyArray$2 = _copyArray, + copySymbols = _copySymbols, + copySymbolsIn = _copySymbolsIn, + getAllKeys$1 = _getAllKeys, + getAllKeysIn = _getAllKeysIn, + getTag$1 = _getTag, + initCloneArray = _initCloneArray, + initCloneByTag = _initCloneByTag, + initCloneObject$1 = _initCloneObject, + isArray$h = isArray_1, + isBuffer$2 = isBufferExports, + isMap = isMap_1, + isObject$d = isObject_1, + isSet = isSet_1, + keys$9 = keys_1, + keysIn$3 = keysIn_1; + +/** Used to compose bitmasks for cloning. */ +var CLONE_DEEP_FLAG$1 = 1, + CLONE_FLAT_FLAG = 2, + CLONE_SYMBOLS_FLAG$1 = 4; + +/** `Object#toString` result references. */ +var argsTag$2 = '[object Arguments]', + arrayTag$1 = '[object Array]', + boolTag$2 = '[object Boolean]', + dateTag$1 = '[object Date]', + errorTag$1 = '[object Error]', + funcTag$1 = '[object Function]', + genTag$1 = '[object GeneratorFunction]', + mapTag$1 = '[object Map]', + numberTag$1 = '[object Number]', + objectTag$2 = '[object Object]', + regexpTag$1 = '[object RegExp]', + setTag$1 = '[object Set]', + stringTag$1 = '[object String]', + symbolTag$2 = '[object Symbol]', + weakMapTag = '[object WeakMap]'; + +var arrayBufferTag$1 = '[object ArrayBuffer]', + dataViewTag$1 = '[object DataView]', + float32Tag = '[object Float32Array]', + float64Tag = '[object Float64Array]', + int8Tag = '[object Int8Array]', + int16Tag = '[object Int16Array]', + int32Tag = '[object Int32Array]', + uint8Tag = '[object Uint8Array]', + uint8ClampedTag = '[object Uint8ClampedArray]', + uint16Tag = '[object Uint16Array]', + uint32Tag = '[object Uint32Array]'; + +/** Used to identify `toStringTag` values supported by `_.clone`. */ +var cloneableTags = {}; +cloneableTags[argsTag$2] = cloneableTags[arrayTag$1] = +cloneableTags[arrayBufferTag$1] = cloneableTags[dataViewTag$1] = +cloneableTags[boolTag$2] = cloneableTags[dateTag$1] = +cloneableTags[float32Tag] = cloneableTags[float64Tag] = +cloneableTags[int8Tag] = cloneableTags[int16Tag] = +cloneableTags[int32Tag] = cloneableTags[mapTag$1] = +cloneableTags[numberTag$1] = cloneableTags[objectTag$2] = +cloneableTags[regexpTag$1] = cloneableTags[setTag$1] = +cloneableTags[stringTag$1] = cloneableTags[symbolTag$2] = +cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = +cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; +cloneableTags[errorTag$1] = cloneableTags[funcTag$1] = +cloneableTags[weakMapTag] = false; + +/** + * The base implementation of `_.clone` and `_.cloneDeep` which tracks + * traversed objects. + * + * @private + * @param {*} value The value to clone. + * @param {boolean} bitmask The bitmask flags. + * 1 - Deep clone + * 2 - Flatten inherited properties + * 4 - Clone symbols + * @param {Function} [customizer] The function to customize cloning. + * @param {string} [key] The key of `value`. + * @param {Object} [object] The parent object of `value`. + * @param {Object} [stack] Tracks traversed objects and their clone counterparts. + * @returns {*} Returns the cloned value. + */ +function baseClone$1(value, bitmask, customizer, key, object, stack) { + var result, + isDeep = bitmask & CLONE_DEEP_FLAG$1, + isFlat = bitmask & CLONE_FLAT_FLAG, + isFull = bitmask & CLONE_SYMBOLS_FLAG$1; + + if (customizer) { + result = object ? customizer(value, key, object, stack) : customizer(value); + } + if (result !== undefined) { + return result; + } + if (!isObject$d(value)) { + return value; + } + var isArr = isArray$h(value); + if (isArr) { + result = initCloneArray(value); + if (!isDeep) { + return copyArray$2(value, result); + } + } else { + var tag = getTag$1(value), + isFunc = tag == funcTag$1 || tag == genTag$1; + + if (isBuffer$2(value)) { + return cloneBuffer$1(value, isDeep); + } + if (tag == objectTag$2 || tag == argsTag$2 || (isFunc && !object)) { + result = (isFlat || isFunc) ? {} : initCloneObject$1(value); + if (!isDeep) { + return isFlat + ? copySymbolsIn(value, baseAssignIn(result, value)) + : copySymbols(value, baseAssign(result, value)); + } + } else { + if (!cloneableTags[tag]) { + return object ? value : {}; + } + result = initCloneByTag(value, tag, isDeep); + } + } + // Check for circular references and return its corresponding clone. + stack || (stack = new Stack$3); + var stacked = stack.get(value); + if (stacked) { + return stacked; + } + stack.set(value, result); + + if (isSet(value)) { + value.forEach(function(subValue) { + result.add(baseClone$1(subValue, bitmask, customizer, subValue, value, stack)); + }); + } else if (isMap(value)) { + value.forEach(function(subValue, key) { + result.set(key, baseClone$1(subValue, bitmask, customizer, key, value, stack)); + }); + } + + var keysFunc = isFull + ? (isFlat ? getAllKeysIn : getAllKeys$1) + : (isFlat ? keysIn$3 : keys$9); + + var props = isArr ? undefined : keysFunc(value); + arrayEach$1(props || value, function(subValue, key) { + if (props) { + key = subValue; + subValue = value[key]; + } + // Recursively populate clone (susceptible to call stack limits). + assignValue$1(result, key, baseClone$1(subValue, bitmask, customizer, key, value, stack)); + }); + return result; +} + +var _baseClone = baseClone$1; + +var baseClone = _baseClone; + +/** Used to compose bitmasks for cloning. */ +var CLONE_DEEP_FLAG = 1, + CLONE_SYMBOLS_FLAG = 4; + +/** + * This method is like `_.clone` except that it recursively clones `value`. + * + * @static + * @memberOf _ + * @since 1.0.0 + * @category Lang + * @param {*} value The value to recursively clone. + * @returns {*} Returns the deep cloned value. + * @see _.clone + * @example + * + * var objects = [{ 'a': 1 }, { 'b': 2 }]; + * + * var deep = _.cloneDeep(objects); + * console.log(deep[0] === objects[0]); + * // => false + */ +function cloneDeep$1(value) { + return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG); +} + +var cloneDeep_1 = cloneDeep$1; + +/** Used to stand-in for `undefined` hash values. */ + +var HASH_UNDEFINED = '__lodash_hash_undefined__'; + +/** + * Adds `value` to the array cache. + * + * @private + * @name add + * @memberOf SetCache + * @alias push + * @param {*} value The value to cache. + * @returns {Object} Returns the cache instance. + */ +function setCacheAdd$1(value) { + this.__data__.set(value, HASH_UNDEFINED); + return this; +} + +var _setCacheAdd = setCacheAdd$1; + +/** + * Checks if `value` is in the array cache. + * + * @private + * @name has + * @memberOf SetCache + * @param {*} value The value to search for. + * @returns {number} Returns `true` if `value` is found, else `false`. + */ + +function setCacheHas$1(value) { + return this.__data__.has(value); +} + +var _setCacheHas = setCacheHas$1; + +var MapCache$1 = _MapCache, + setCacheAdd = _setCacheAdd, + setCacheHas = _setCacheHas; + +/** + * + * Creates an array cache object to store unique values. + * + * @private + * @constructor + * @param {Array} [values] The values to cache. + */ +function SetCache$4(values) { + var index = -1, + length = values == null ? 0 : values.length; + + this.__data__ = new MapCache$1; + while (++index < length) { + this.add(values[index]); + } +} + +// Add methods to `SetCache`. +SetCache$4.prototype.add = SetCache$4.prototype.push = setCacheAdd; +SetCache$4.prototype.has = setCacheHas; + +var _SetCache = SetCache$4; + +/** + * A specialized version of `_.some` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + */ + +function arraySome$1(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + if (predicate(array[index], index, array)) { + return true; + } + } + return false; +} + +var _arraySome = arraySome$1; + +/** + * Checks if a `cache` value for `key` exists. + * + * @private + * @param {Object} cache The cache to query. + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + +function cacheHas$4(cache, key) { + return cache.has(key); +} + +var _cacheHas = cacheHas$4; + +var SetCache$3 = _SetCache, + arraySome = _arraySome, + cacheHas$3 = _cacheHas; + +/** Used to compose bitmasks for value comparisons. */ +var COMPARE_PARTIAL_FLAG$5 = 1, + COMPARE_UNORDERED_FLAG$3 = 2; + +/** + * A specialized version of `baseIsEqualDeep` for arrays with support for + * partial deep comparisons. + * + * @private + * @param {Array} array The array to compare. + * @param {Array} other The other array to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `array` and `other` objects. + * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. + */ +function equalArrays$2(array, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG$5, + arrLength = array.length, + othLength = other.length; + + if (arrLength != othLength && !(isPartial && othLength > arrLength)) { + return false; + } + // Check that cyclic values are equal. + var arrStacked = stack.get(array); + var othStacked = stack.get(other); + if (arrStacked && othStacked) { + return arrStacked == other && othStacked == array; + } + var index = -1, + result = true, + seen = (bitmask & COMPARE_UNORDERED_FLAG$3) ? new SetCache$3 : undefined; + + stack.set(array, other); + stack.set(other, array); + + // Ignore non-index properties. + while (++index < arrLength) { + var arrValue = array[index], + othValue = other[index]; + + if (customizer) { + var compared = isPartial + ? customizer(othValue, arrValue, index, other, array, stack) + : customizer(arrValue, othValue, index, array, other, stack); + } + if (compared !== undefined) { + if (compared) { + continue; + } + result = false; + break; + } + // Recursively compare arrays (susceptible to call stack limits). + if (seen) { + if (!arraySome(other, function(othValue, othIndex) { + if (!cacheHas$3(seen, othIndex) && + (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { + return seen.push(othIndex); + } + })) { + result = false; + break; + } + } else if (!( + arrValue === othValue || + equalFunc(arrValue, othValue, bitmask, customizer, stack) + )) { + result = false; + break; + } + } + stack['delete'](array); + stack['delete'](other); + return result; +} + +var _equalArrays = equalArrays$2; + +/** + * Converts `map` to its key-value pairs. + * + * @private + * @param {Object} map The map to convert. + * @returns {Array} Returns the key-value pairs. + */ + +function mapToArray$1(map) { + var index = -1, + result = Array(map.size); + + map.forEach(function(value, key) { + result[++index] = [key, value]; + }); + return result; +} + +var _mapToArray = mapToArray$1; + +/** + * Converts `set` to an array of its values. + * + * @private + * @param {Object} set The set to convert. + * @returns {Array} Returns the values. + */ + +function setToArray$3(set) { + var index = -1, + result = Array(set.size); + + set.forEach(function(value) { + result[++index] = value; + }); + return result; +} + +var _setToArray = setToArray$3; + +var Symbol$3 = _Symbol, + Uint8Array$1 = _Uint8Array, + eq$4 = eq_1, + equalArrays$1 = _equalArrays, + mapToArray = _mapToArray, + setToArray$2 = _setToArray; + +/** Used to compose bitmasks for value comparisons. */ +var COMPARE_PARTIAL_FLAG$4 = 1, + COMPARE_UNORDERED_FLAG$2 = 2; + +/** `Object#toString` result references. */ +var boolTag$1 = '[object Boolean]', + dateTag = '[object Date]', + errorTag = '[object Error]', + mapTag = '[object Map]', + numberTag = '[object Number]', + regexpTag = '[object RegExp]', + setTag = '[object Set]', + stringTag = '[object String]', + symbolTag$1 = '[object Symbol]'; + +var arrayBufferTag = '[object ArrayBuffer]', + dataViewTag = '[object DataView]'; + +/** Used to convert symbols to primitives and strings. */ +var symbolProto$1 = Symbol$3 ? Symbol$3.prototype : undefined, + symbolValueOf = symbolProto$1 ? symbolProto$1.valueOf : undefined; + +/** + * A specialized version of `baseIsEqualDeep` for comparing objects of + * the same `toStringTag`. + * + * **Note:** This function only supports comparing values with tags of + * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {string} tag The `toStringTag` of the objects to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ +function equalByTag$1(object, other, tag, bitmask, customizer, equalFunc, stack) { + switch (tag) { + case dataViewTag: + if ((object.byteLength != other.byteLength) || + (object.byteOffset != other.byteOffset)) { + return false; + } + object = object.buffer; + other = other.buffer; + + case arrayBufferTag: + if ((object.byteLength != other.byteLength) || + !equalFunc(new Uint8Array$1(object), new Uint8Array$1(other))) { + return false; + } + return true; + + case boolTag$1: + case dateTag: + case numberTag: + // Coerce booleans to `1` or `0` and dates to milliseconds. + // Invalid dates are coerced to `NaN`. + return eq$4(+object, +other); + + case errorTag: + return object.name == other.name && object.message == other.message; + + case regexpTag: + case stringTag: + // Coerce regexes to strings and treat strings, primitives and objects, + // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring + // for more details. + return object == (other + ''); + + case mapTag: + var convert = mapToArray; + + case setTag: + var isPartial = bitmask & COMPARE_PARTIAL_FLAG$4; + convert || (convert = setToArray$2); + + if (object.size != other.size && !isPartial) { + return false; + } + // Assume cyclic values are equal. + var stacked = stack.get(object); + if (stacked) { + return stacked == other; + } + bitmask |= COMPARE_UNORDERED_FLAG$2; + + // Recursively compare objects (susceptible to call stack limits). + stack.set(object, other); + var result = equalArrays$1(convert(object), convert(other), bitmask, customizer, equalFunc, stack); + stack['delete'](object); + return result; + + case symbolTag$1: + if (symbolValueOf) { + return symbolValueOf.call(object) == symbolValueOf.call(other); + } + } + return false; +} + +var _equalByTag = equalByTag$1; + +var getAllKeys = _getAllKeys; + +/** Used to compose bitmasks for value comparisons. */ +var COMPARE_PARTIAL_FLAG$3 = 1; + +/** Used for built-in method references. */ +var objectProto$4 = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty$5 = objectProto$4.hasOwnProperty; + +/** + * A specialized version of `baseIsEqualDeep` for objects with support for + * partial deep comparisons. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ +function equalObjects$1(object, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG$3, + objProps = getAllKeys(object), + objLength = objProps.length, + othProps = getAllKeys(other), + othLength = othProps.length; + + if (objLength != othLength && !isPartial) { + return false; + } + var index = objLength; + while (index--) { + var key = objProps[index]; + if (!(isPartial ? key in other : hasOwnProperty$5.call(other, key))) { + return false; + } + } + // Check that cyclic values are equal. + var objStacked = stack.get(object); + var othStacked = stack.get(other); + if (objStacked && othStacked) { + return objStacked == other && othStacked == object; + } + var result = true; + stack.set(object, other); + stack.set(other, object); + + var skipCtor = isPartial; + while (++index < objLength) { + key = objProps[index]; + var objValue = object[key], + othValue = other[key]; + + if (customizer) { + var compared = isPartial + ? customizer(othValue, objValue, key, other, object, stack) + : customizer(objValue, othValue, key, object, other, stack); + } + // Recursively compare objects (susceptible to call stack limits). + if (!(compared === undefined + ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) + : compared + )) { + result = false; + break; + } + skipCtor || (skipCtor = key == 'constructor'); + } + if (result && !skipCtor) { + var objCtor = object.constructor, + othCtor = other.constructor; + + // Non `Object` object instances with different constructors are not equal. + if (objCtor != othCtor && + ('constructor' in object && 'constructor' in other) && + !(typeof objCtor == 'function' && objCtor instanceof objCtor && + typeof othCtor == 'function' && othCtor instanceof othCtor)) { + result = false; + } + } + stack['delete'](object); + stack['delete'](other); + return result; +} + +var _equalObjects = equalObjects$1; + +var Stack$2 = _Stack, + equalArrays = _equalArrays, + equalByTag = _equalByTag, + equalObjects = _equalObjects, + getTag = _getTag, + isArray$g = isArray_1, + isBuffer$1 = isBufferExports, + isTypedArray$1 = isTypedArray_1; + +/** Used to compose bitmasks for value comparisons. */ +var COMPARE_PARTIAL_FLAG$2 = 1; + +/** `Object#toString` result references. */ +var argsTag$1 = '[object Arguments]', + arrayTag = '[object Array]', + objectTag$1 = '[object Object]'; + +/** Used for built-in method references. */ +var objectProto$3 = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty$4 = objectProto$3.hasOwnProperty; + +/** + * A specialized version of `baseIsEqual` for arrays and objects which performs + * deep comparisons and tracks traversed objects enabling objects with circular + * references to be compared. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} [stack] Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ +function baseIsEqualDeep$1(object, other, bitmask, customizer, equalFunc, stack) { + var objIsArr = isArray$g(object), + othIsArr = isArray$g(other), + objTag = objIsArr ? arrayTag : getTag(object), + othTag = othIsArr ? arrayTag : getTag(other); + + objTag = objTag == argsTag$1 ? objectTag$1 : objTag; + othTag = othTag == argsTag$1 ? objectTag$1 : othTag; + + var objIsObj = objTag == objectTag$1, + othIsObj = othTag == objectTag$1, + isSameTag = objTag == othTag; + + if (isSameTag && isBuffer$1(object)) { + if (!isBuffer$1(other)) { + return false; + } + objIsArr = true; + objIsObj = false; + } + if (isSameTag && !objIsObj) { + stack || (stack = new Stack$2); + return (objIsArr || isTypedArray$1(object)) + ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) + : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); + } + if (!(bitmask & COMPARE_PARTIAL_FLAG$2)) { + var objIsWrapped = objIsObj && hasOwnProperty$4.call(object, '__wrapped__'), + othIsWrapped = othIsObj && hasOwnProperty$4.call(other, '__wrapped__'); + + if (objIsWrapped || othIsWrapped) { + var objUnwrapped = objIsWrapped ? object.value() : object, + othUnwrapped = othIsWrapped ? other.value() : other; + + stack || (stack = new Stack$2); + return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); + } + } + if (!isSameTag) { + return false; + } + stack || (stack = new Stack$2); + return equalObjects(object, other, bitmask, customizer, equalFunc, stack); +} + +var _baseIsEqualDeep = baseIsEqualDeep$1; + +var baseIsEqualDeep = _baseIsEqualDeep, + isObjectLike$5 = isObjectLike_1; + +/** + * The base implementation of `_.isEqual` which supports partial comparisons + * and tracks traversed objects. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @param {boolean} bitmask The bitmask flags. + * 1 - Unordered comparison + * 2 - Partial comparison + * @param {Function} [customizer] The function to customize comparisons. + * @param {Object} [stack] Tracks traversed `value` and `other` objects. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + */ +function baseIsEqual$3(value, other, bitmask, customizer, stack) { + if (value === other) { + return true; + } + if (value == null || other == null || (!isObjectLike$5(value) && !isObjectLike$5(other))) { + return value !== value && other !== other; + } + return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual$3, stack); +} + +var _baseIsEqual = baseIsEqual$3; + +var baseIsEqual$2 = _baseIsEqual; + +/** + * Performs a deep comparison between two values to determine if they are + * equivalent. + * + * **Note:** This method supports comparing arrays, array buffers, booleans, + * date objects, error objects, maps, numbers, `Object` objects, regexes, + * sets, strings, symbols, and typed arrays. `Object` objects are compared + * by their own, not inherited, enumerable properties. Functions and DOM + * nodes are compared by strict equality, i.e. `===`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.isEqual(object, other); + * // => true + * + * object === other; + * // => false + */ +function isEqual$2(value, other) { + return baseIsEqual$2(value, other); +} + +var isEqual_1 = isEqual$2; + +var Symbol$2 = _Symbol, + isArguments$4 = isArguments_1, + isArray$f = isArray_1; + +/** Built-in value references. */ +var spreadableSymbol = Symbol$2 ? Symbol$2.isConcatSpreadable : undefined; + +/** + * Checks if `value` is a flattenable `arguments` object or array. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. + */ +function isFlattenable$1(value) { + return isArray$f(value) || isArguments$4(value) || + !!(spreadableSymbol && value && value[spreadableSymbol]); +} + +var _isFlattenable = isFlattenable$1; + +var arrayPush = _arrayPush, + isFlattenable = _isFlattenable; + +/** + * The base implementation of `_.flatten` with support for restricting flattening. + * + * @private + * @param {Array} array The array to flatten. + * @param {number} depth The maximum recursion depth. + * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. + * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. + * @param {Array} [result=[]] The initial result value. + * @returns {Array} Returns the new flattened array. + */ +function baseFlatten$3(array, depth, predicate, isStrict, result) { + var index = -1, + length = array.length; + + predicate || (predicate = isFlattenable); + result || (result = []); + + while (++index < length) { + var value = array[index]; + if (depth > 0 && predicate(value)) { + if (depth > 1) { + // Recursively flatten arrays (susceptible to call stack limits). + baseFlatten$3(value, depth - 1, predicate, isStrict, result); + } else { + arrayPush(result, value); + } + } else if (!isStrict) { + result[result.length] = value; + } + } + return result; +} + +var _baseFlatten = baseFlatten$3; + +/** + * A specialized version of `_.map` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + */ + +function arrayMap$7(array, iteratee) { + var index = -1, + length = array == null ? 0 : array.length, + result = Array(length); + + while (++index < length) { + result[index] = iteratee(array[index], index, array); + } + return result; +} + +var _arrayMap = arrayMap$7; + +var baseGetTag$2 = _baseGetTag, + isObjectLike$4 = isObjectLike_1; + +/** `Object#toString` result references. */ +var symbolTag = '[object Symbol]'; + +/** + * Checks if `value` is classified as a `Symbol` primitive or object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. + * @example + * + * _.isSymbol(Symbol.iterator); + * // => true + * + * _.isSymbol('abc'); + * // => false + */ +function isSymbol$5(value) { + return typeof value == 'symbol' || + (isObjectLike$4(value) && baseGetTag$2(value) == symbolTag); +} + +var isSymbol_1 = isSymbol$5; + +var isArray$e = isArray_1, + isSymbol$4 = isSymbol_1; + +/** Used to match property names within property paths. */ +var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, + reIsPlainProp = /^\w*$/; + +/** + * Checks if `value` is a property name and not a property path. + * + * @private + * @param {*} value The value to check. + * @param {Object} [object] The object to query keys on. + * @returns {boolean} Returns `true` if `value` is a property name, else `false`. + */ +function isKey$3(value, object) { + if (isArray$e(value)) { + return false; + } + var type = typeof value; + if (type == 'number' || type == 'symbol' || type == 'boolean' || + value == null || isSymbol$4(value)) { + return true; + } + return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || + (object != null && value in Object(object)); +} + +var _isKey = isKey$3; + +var MapCache = _MapCache; + +/** Error message constants. */ +var FUNC_ERROR_TEXT = 'Expected a function'; + +/** + * Creates a function that memoizes the result of `func`. If `resolver` is + * provided, it determines the cache key for storing the result based on the + * arguments provided to the memoized function. By default, the first argument + * provided to the memoized function is used as the map cache key. The `func` + * is invoked with the `this` binding of the memoized function. + * + * **Note:** The cache is exposed as the `cache` property on the memoized + * function. Its creation may be customized by replacing the `_.memoize.Cache` + * constructor with one whose instances implement the + * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) + * method interface of `clear`, `delete`, `get`, `has`, and `set`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to have its output memoized. + * @param {Function} [resolver] The function to resolve the cache key. + * @returns {Function} Returns the new memoized function. + * @example + * + * var object = { 'a': 1, 'b': 2 }; + * var other = { 'c': 3, 'd': 4 }; + * + * var values = _.memoize(_.values); + * values(object); + * // => [1, 2] + * + * values(other); + * // => [3, 4] + * + * object.a = 2; + * values(object); + * // => [1, 2] + * + * // Modify the result cache. + * values.cache.set(object, ['a', 'b']); + * values(object); + * // => ['a', 'b'] + * + * // Replace `_.memoize.Cache`. + * _.memoize.Cache = WeakMap; + */ +function memoize$2(func, resolver) { + if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { + throw new TypeError(FUNC_ERROR_TEXT); + } + var memoized = function() { + var args = arguments, + key = resolver ? resolver.apply(this, args) : args[0], + cache = memoized.cache; + + if (cache.has(key)) { + return cache.get(key); + } + var result = func.apply(this, args); + memoized.cache = cache.set(key, result) || cache; + return result; + }; + memoized.cache = new (memoize$2.Cache || MapCache); + return memoized; +} + +// Expose `MapCache`. +memoize$2.Cache = MapCache; + +var memoize_1 = memoize$2; + +var memoize$1 = memoize_1; + +/** Used as the maximum memoize cache size. */ +var MAX_MEMOIZE_SIZE = 500; + +/** + * A specialized version of `_.memoize` which clears the memoized function's + * cache when it exceeds `MAX_MEMOIZE_SIZE`. + * + * @private + * @param {Function} func The function to have its output memoized. + * @returns {Function} Returns the new memoized function. + */ +function memoizeCapped$1(func) { + var result = memoize$1(func, function(key) { + if (cache.size === MAX_MEMOIZE_SIZE) { + cache.clear(); + } + return key; + }); + + var cache = result.cache; + return result; +} + +var _memoizeCapped = memoizeCapped$1; + +var memoizeCapped = _memoizeCapped; + +/** Used to match property names within property paths. */ +var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; + +/** Used to match backslashes in property paths. */ +var reEscapeChar = /\\(\\)?/g; + +/** + * Converts `string` to a property path array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the property path array. + */ +var stringToPath$1 = memoizeCapped(function(string) { + var result = []; + if (string.charCodeAt(0) === 46 /* . */) { + result.push(''); + } + string.replace(rePropName, function(match, number, quote, subString) { + result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match)); + }); + return result; +}); + +var _stringToPath = stringToPath$1; + +var Symbol$1 = _Symbol, + arrayMap$6 = _arrayMap, + isArray$d = isArray_1, + isSymbol$3 = isSymbol_1; + +/** Used as references for various `Number` constants. */ +var INFINITY$3 = 1 / 0; + +/** Used to convert symbols to primitives and strings. */ +var symbolProto = Symbol$1 ? Symbol$1.prototype : undefined, + symbolToString = symbolProto ? symbolProto.toString : undefined; + +/** + * The base implementation of `_.toString` which doesn't convert nullish + * values to empty strings. + * + * @private + * @param {*} value The value to process. + * @returns {string} Returns the string. + */ +function baseToString$1(value) { + // Exit early for strings to avoid a performance hit in some environments. + if (typeof value == 'string') { + return value; + } + if (isArray$d(value)) { + // Recursively convert values (susceptible to call stack limits). + return arrayMap$6(value, baseToString$1) + ''; + } + if (isSymbol$3(value)) { + return symbolToString ? symbolToString.call(value) : ''; + } + var result = (value + ''); + return (result == '0' && (1 / value) == -INFINITY$3) ? '-0' : result; +} + +var _baseToString = baseToString$1; + +var baseToString = _baseToString; + +/** + * Converts `value` to a string. An empty string is returned for `null` + * and `undefined` values. The sign of `-0` is preserved. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. + * @example + * + * _.toString(null); + * // => '' + * + * _.toString(-0); + * // => '-0' + * + * _.toString([1, 2, 3]); + * // => '1,2,3' + */ +function toString$1(value) { + return value == null ? '' : baseToString(value); +} + +var toString_1 = toString$1; + +var isArray$c = isArray_1, + isKey$2 = _isKey, + stringToPath = _stringToPath, + toString = toString_1; + +/** + * Casts `value` to a path array if it's not one. + * + * @private + * @param {*} value The value to inspect. + * @param {Object} [object] The object to query keys on. + * @returns {Array} Returns the cast property path array. + */ +function castPath$2(value, object) { + if (isArray$c(value)) { + return value; + } + return isKey$2(value, object) ? [value] : stringToPath(toString(value)); +} + +var _castPath = castPath$2; + +var isSymbol$2 = isSymbol_1; + +/** Used as references for various `Number` constants. */ +var INFINITY$2 = 1 / 0; + +/** + * Converts `value` to a string key if it's not a string or symbol. + * + * @private + * @param {*} value The value to inspect. + * @returns {string|symbol} Returns the key. + */ +function toKey$4(value) { + if (typeof value == 'string' || isSymbol$2(value)) { + return value; + } + var result = (value + ''); + return (result == '0' && (1 / value) == -INFINITY$2) ? '-0' : result; +} + +var _toKey = toKey$4; + +var castPath$1 = _castPath, + toKey$3 = _toKey; + +/** + * The base implementation of `_.get` without support for default values. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @returns {*} Returns the resolved value. + */ +function baseGet$3(object, path) { + path = castPath$1(path, object); + + var index = 0, + length = path.length; + + while (object != null && index < length) { + object = object[toKey$3(path[index++])]; + } + return (index && index == length) ? object : undefined; +} + +var _baseGet = baseGet$3; + +var Stack$1 = _Stack, + baseIsEqual$1 = _baseIsEqual; + +/** Used to compose bitmasks for value comparisons. */ +var COMPARE_PARTIAL_FLAG$1 = 1, + COMPARE_UNORDERED_FLAG$1 = 2; + +/** + * The base implementation of `_.isMatch` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to inspect. + * @param {Object} source The object of property values to match. + * @param {Array} matchData The property names, values, and compare flags to match. + * @param {Function} [customizer] The function to customize comparisons. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. + */ +function baseIsMatch$1(object, source, matchData, customizer) { + var index = matchData.length, + length = index, + noCustomizer = !customizer; + + if (object == null) { + return !length; + } + object = Object(object); + while (index--) { + var data = matchData[index]; + if ((noCustomizer && data[2]) + ? data[1] !== object[data[0]] + : !(data[0] in object) + ) { + return false; + } + } + while (++index < length) { + data = matchData[index]; + var key = data[0], + objValue = object[key], + srcValue = data[1]; + + if (noCustomizer && data[2]) { + if (objValue === undefined && !(key in object)) { + return false; + } + } else { + var stack = new Stack$1; + if (customizer) { + var result = customizer(objValue, srcValue, key, object, source, stack); + } + if (!(result === undefined + ? baseIsEqual$1(srcValue, objValue, COMPARE_PARTIAL_FLAG$1 | COMPARE_UNORDERED_FLAG$1, customizer, stack) + : result + )) { + return false; + } + } + } + return true; +} + +var _baseIsMatch = baseIsMatch$1; + +var isObject$c = isObject_1; + +/** + * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` if suitable for strict + * equality comparisons, else `false`. + */ +function isStrictComparable$2(value) { + return value === value && !isObject$c(value); +} + +var _isStrictComparable = isStrictComparable$2; + +var isStrictComparable$1 = _isStrictComparable, + keys$8 = keys_1; + +/** + * Gets the property names, values, and compare flags of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the match data of `object`. + */ +function getMatchData$1(object) { + var result = keys$8(object), + length = result.length; + + while (length--) { + var key = result[length], + value = object[key]; + + result[length] = [key, value, isStrictComparable$1(value)]; + } + return result; +} + +var _getMatchData = getMatchData$1; + +/** + * A specialized version of `matchesProperty` for source values suitable + * for strict equality comparisons, i.e. `===`. + * + * @private + * @param {string} key The key of the property to get. + * @param {*} srcValue The value to match. + * @returns {Function} Returns the new spec function. + */ + +function matchesStrictComparable$2(key, srcValue) { + return function(object) { + if (object == null) { + return false; + } + return object[key] === srcValue && + (srcValue !== undefined || (key in Object(object))); + }; +} + +var _matchesStrictComparable = matchesStrictComparable$2; + +var baseIsMatch = _baseIsMatch, + getMatchData = _getMatchData, + matchesStrictComparable$1 = _matchesStrictComparable; + +/** + * The base implementation of `_.matches` which doesn't clone `source`. + * + * @private + * @param {Object} source The object of property values to match. + * @returns {Function} Returns the new spec function. + */ +function baseMatches$1(source) { + var matchData = getMatchData(source); + if (matchData.length == 1 && matchData[0][2]) { + return matchesStrictComparable$1(matchData[0][0], matchData[0][1]); + } + return function(object) { + return object === source || baseIsMatch(object, source, matchData); + }; +} + +var _baseMatches = baseMatches$1; + +var baseGet$2 = _baseGet; + +/** + * Gets the value at `path` of `object`. If the resolved value is + * `undefined`, the `defaultValue` is returned in its place. + * + * @static + * @memberOf _ + * @since 3.7.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @param {*} [defaultValue] The value returned for `undefined` resolved values. + * @returns {*} Returns the resolved value. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; + * + * _.get(object, 'a[0].b.c'); + * // => 3 + * + * _.get(object, ['a', '0', 'b', 'c']); + * // => 3 + * + * _.get(object, 'a.b.c', 'default'); + * // => 'default' + */ +function get$2(object, path, defaultValue) { + var result = object == null ? undefined : baseGet$2(object, path); + return result === undefined ? defaultValue : result; +} + +var get_1 = get$2; + +/** + * The base implementation of `_.hasIn` without support for deep paths. + * + * @private + * @param {Object} [object] The object to query. + * @param {Array|string} key The key to check. + * @returns {boolean} Returns `true` if `key` exists, else `false`. + */ + +function baseHasIn$1(object, key) { + return object != null && key in Object(object); +} + +var _baseHasIn = baseHasIn$1; + +var castPath = _castPath, + isArguments$3 = isArguments_1, + isArray$b = isArray_1, + isIndex$2 = _isIndex, + isLength$1 = isLength_1, + toKey$2 = _toKey; + +/** + * Checks if `path` exists on `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @param {Function} hasFunc The function to check properties. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + */ +function hasPath$1(object, path, hasFunc) { + path = castPath(path, object); + + var index = -1, + length = path.length, + result = false; + + while (++index < length) { + var key = toKey$2(path[index]); + if (!(result = object != null && hasFunc(object, key))) { + break; + } + object = object[key]; + } + if (result || ++index != length) { + return result; + } + length = object == null ? 0 : object.length; + return !!length && isLength$1(length) && isIndex$2(key, length) && + (isArray$b(object) || isArguments$3(object)); +} + +var _hasPath = hasPath$1; + +var baseHasIn = _baseHasIn, + hasPath = _hasPath; + +/** + * Checks if `path` is a direct or inherited property of `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + * @example + * + * var object = _.create({ 'a': _.create({ 'b': 2 }) }); + * + * _.hasIn(object, 'a'); + * // => true + * + * _.hasIn(object, 'a.b'); + * // => true + * + * _.hasIn(object, ['a', 'b']); + * // => true + * + * _.hasIn(object, 'b'); + * // => false + */ +function hasIn$1(object, path) { + return object != null && hasPath(object, path, baseHasIn); +} + +var hasIn_1 = hasIn$1; + +var baseIsEqual = _baseIsEqual, + get$1 = get_1, + hasIn = hasIn_1, + isKey$1 = _isKey, + isStrictComparable = _isStrictComparable, + matchesStrictComparable = _matchesStrictComparable, + toKey$1 = _toKey; + +/** Used to compose bitmasks for value comparisons. */ +var COMPARE_PARTIAL_FLAG = 1, + COMPARE_UNORDERED_FLAG = 2; + +/** + * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. + * + * @private + * @param {string} path The path of the property to get. + * @param {*} srcValue The value to match. + * @returns {Function} Returns the new spec function. + */ +function baseMatchesProperty$1(path, srcValue) { + if (isKey$1(path) && isStrictComparable(srcValue)) { + return matchesStrictComparable(toKey$1(path), srcValue); + } + return function(object) { + var objValue = get$1(object, path); + return (objValue === undefined && objValue === srcValue) + ? hasIn(object, path) + : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG); + }; +} + +var _baseMatchesProperty = baseMatchesProperty$1; + +/** + * This method returns the first argument it receives. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Util + * @param {*} value Any value. + * @returns {*} Returns `value`. + * @example + * + * var object = { 'a': 1 }; + * + * console.log(_.identity(object) === object); + * // => true + */ + +function identity$5(value) { + return value; +} + +var identity_1 = identity$5; + +/** + * The base implementation of `_.property` without support for deep paths. + * + * @private + * @param {string} key The key of the property to get. + * @returns {Function} Returns the new accessor function. + */ + +function baseProperty$1(key) { + return function(object) { + return object == null ? undefined : object[key]; + }; +} + +var _baseProperty = baseProperty$1; + +var baseGet$1 = _baseGet; + +/** + * A specialized version of `baseProperty` which supports deep paths. + * + * @private + * @param {Array|string} path The path of the property to get. + * @returns {Function} Returns the new accessor function. + */ +function basePropertyDeep$1(path) { + return function(object) { + return baseGet$1(object, path); + }; +} + +var _basePropertyDeep = basePropertyDeep$1; + +var baseProperty = _baseProperty, + basePropertyDeep = _basePropertyDeep, + isKey = _isKey, + toKey = _toKey; + +/** + * Creates a function that returns the value at `path` of a given object. + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Util + * @param {Array|string} path The path of the property to get. + * @returns {Function} Returns the new accessor function. + * @example + * + * var objects = [ + * { 'a': { 'b': 2 } }, + * { 'a': { 'b': 1 } } + * ]; + * + * _.map(objects, _.property('a.b')); + * // => [2, 1] + * + * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b'); + * // => [1, 2] + */ +function property$1(path) { + return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path); +} + +var property_1 = property$1; + +var baseMatches = _baseMatches, + baseMatchesProperty = _baseMatchesProperty, + identity$4 = identity_1, + isArray$a = isArray_1, + property = property_1; + +/** + * The base implementation of `_.iteratee`. + * + * @private + * @param {*} [value=_.identity] The value to convert to an iteratee. + * @returns {Function} Returns the iteratee. + */ +function baseIteratee$1(value) { + // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. + // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. + if (typeof value == 'function') { + return value; + } + if (value == null) { + return identity$4; + } + if (typeof value == 'object') { + return isArray$a(value) + ? baseMatchesProperty(value[0], value[1]) + : baseMatches(value); + } + return property(value); +} + +var _baseIteratee = baseIteratee$1; + +/** + * Creates a base function for methods like `_.forIn` and `_.forOwn`. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. + */ + +function createBaseFor$1(fromRight) { + return function(object, iteratee, keysFunc) { + var index = -1, + iterable = Object(object), + props = keysFunc(object), + length = props.length; + + while (length--) { + var key = props[fromRight ? length : ++index]; + if (iteratee(iterable[key], key, iterable) === false) { + break; + } + } + return object; + }; +} + +var _createBaseFor = createBaseFor$1; + +var createBaseFor = _createBaseFor; + +/** + * The base implementation of `baseForOwn` which iterates over `object` + * properties returned by `keysFunc` and invokes `iteratee` for each property. + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {Function} keysFunc The function to get the keys of `object`. + * @returns {Object} Returns `object`. + */ +var baseFor$2 = createBaseFor(); + +var _baseFor = baseFor$2; + +var baseFor$1 = _baseFor, + keys$7 = keys_1; + +/** + * The base implementation of `_.forOwn` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Object} Returns `object`. + */ +function baseForOwn$1(object, iteratee) { + return object && baseFor$1(object, iteratee, keys$7); +} + +var _baseForOwn = baseForOwn$1; + +var isArrayLike$8 = isArrayLike_1; + +/** + * Creates a `baseEach` or `baseEachRight` function. + * + * @private + * @param {Function} eachFunc The function to iterate over a collection. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. + */ +function createBaseEach$1(eachFunc, fromRight) { + return function(collection, iteratee) { + if (collection == null) { + return collection; + } + if (!isArrayLike$8(collection)) { + return eachFunc(collection, iteratee); + } + var length = collection.length, + index = fromRight ? length : -1, + iterable = Object(collection); + + while ((fromRight ? index-- : ++index < length)) { + if (iteratee(iterable[index], index, iterable) === false) { + break; + } + } + return collection; + }; +} + +var _createBaseEach = createBaseEach$1; + +var baseForOwn = _baseForOwn, + createBaseEach = _createBaseEach; + +/** + * The base implementation of `_.forEach` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + */ +var baseEach$2 = createBaseEach(baseForOwn); + +var _baseEach = baseEach$2; + +var baseEach$1 = _baseEach, + isArrayLike$7 = isArrayLike_1; + +/** + * The base implementation of `_.map` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + */ +function baseMap$1(collection, iteratee) { + var index = -1, + result = isArrayLike$7(collection) ? Array(collection.length) : []; + + baseEach$1(collection, function(value, key, collection) { + result[++index] = iteratee(value, key, collection); + }); + return result; +} + +var _baseMap = baseMap$1; + +/** + * The base implementation of `_.sortBy` which uses `comparer` to define the + * sort order of `array` and replaces criteria objects with their corresponding + * values. + * + * @private + * @param {Array} array The array to sort. + * @param {Function} comparer The function to define sort order. + * @returns {Array} Returns `array`. + */ + +function baseSortBy$1(array, comparer) { + var length = array.length; + + array.sort(comparer); + while (length--) { + array[length] = array[length].value; + } + return array; +} + +var _baseSortBy = baseSortBy$1; + +var isSymbol$1 = isSymbol_1; + +/** + * Compares values to sort them in ascending order. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {number} Returns the sort order indicator for `value`. + */ +function compareAscending$1(value, other) { + if (value !== other) { + var valIsDefined = value !== undefined, + valIsNull = value === null, + valIsReflexive = value === value, + valIsSymbol = isSymbol$1(value); + + var othIsDefined = other !== undefined, + othIsNull = other === null, + othIsReflexive = other === other, + othIsSymbol = isSymbol$1(other); + + if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) || + (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) || + (valIsNull && othIsDefined && othIsReflexive) || + (!valIsDefined && othIsReflexive) || + !valIsReflexive) { + return 1; + } + if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) || + (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) || + (othIsNull && valIsDefined && valIsReflexive) || + (!othIsDefined && valIsReflexive) || + !othIsReflexive) { + return -1; + } + } + return 0; +} + +var _compareAscending = compareAscending$1; + +var compareAscending = _compareAscending; + +/** + * Used by `_.orderBy` to compare multiple properties of a value to another + * and stable sort them. + * + * If `orders` is unspecified, all values are sorted in ascending order. Otherwise, + * specify an order of "desc" for descending or "asc" for ascending sort order + * of corresponding values. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {boolean[]|string[]} orders The order to sort by for each property. + * @returns {number} Returns the sort order indicator for `object`. + */ +function compareMultiple$1(object, other, orders) { + var index = -1, + objCriteria = object.criteria, + othCriteria = other.criteria, + length = objCriteria.length, + ordersLength = orders.length; + + while (++index < length) { + var result = compareAscending(objCriteria[index], othCriteria[index]); + if (result) { + if (index >= ordersLength) { + return result; + } + var order = orders[index]; + return result * (order == 'desc' ? -1 : 1); + } + } + // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications + // that causes it, under certain circumstances, to provide the same value for + // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247 + // for more details. + // + // This also ensures a stable sort in V8 and other engines. + // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details. + return object.index - other.index; +} + +var _compareMultiple = compareMultiple$1; + +var arrayMap$5 = _arrayMap, + baseGet = _baseGet, + baseIteratee = _baseIteratee, + baseMap = _baseMap, + baseSortBy = _baseSortBy, + baseUnary$3 = _baseUnary, + compareMultiple = _compareMultiple, + identity$3 = identity_1, + isArray$9 = isArray_1; + +/** + * The base implementation of `_.orderBy` without param guards. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by. + * @param {string[]} orders The sort orders of `iteratees`. + * @returns {Array} Returns the new sorted array. + */ +function baseOrderBy$1(collection, iteratees, orders) { + if (iteratees.length) { + iteratees = arrayMap$5(iteratees, function(iteratee) { + if (isArray$9(iteratee)) { + return function(value) { + return baseGet(value, iteratee.length === 1 ? iteratee[0] : iteratee); + } + } + return iteratee; + }); + } else { + iteratees = [identity$3]; + } + + var index = -1; + iteratees = arrayMap$5(iteratees, baseUnary$3(baseIteratee)); + + var result = baseMap(collection, function(value, key, collection) { + var criteria = arrayMap$5(iteratees, function(iteratee) { + return iteratee(value); + }); + return { 'criteria': criteria, 'index': ++index, 'value': value }; + }); + + return baseSortBy(result, function(object, other) { + return compareMultiple(object, other, orders); + }); +} + +var _baseOrderBy = baseOrderBy$1; + +/** + * A faster alternative to `Function#apply`, this function invokes `func` + * with the `this` binding of `thisArg` and the arguments of `args`. + * + * @private + * @param {Function} func The function to invoke. + * @param {*} thisArg The `this` binding of `func`. + * @param {Array} args The arguments to invoke `func` with. + * @returns {*} Returns the result of `func`. + */ + +function apply$4(func, thisArg, args) { + switch (args.length) { + case 0: return func.call(thisArg); + case 1: return func.call(thisArg, args[0]); + case 2: return func.call(thisArg, args[0], args[1]); + case 3: return func.call(thisArg, args[0], args[1], args[2]); + } + return func.apply(thisArg, args); +} + +var _apply = apply$4; + +var apply$3 = _apply; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax$1 = Math.max; + +/** + * A specialized version of `baseRest` which transforms the rest array. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @param {Function} transform The rest array transform. + * @returns {Function} Returns the new function. + */ +function overRest$1(func, start, transform) { + start = nativeMax$1(start === undefined ? (func.length - 1) : start, 0); + return function() { + var args = arguments, + index = -1, + length = nativeMax$1(args.length - start, 0), + array = Array(length); + + while (++index < length) { + array[index] = args[start + index]; + } + index = -1; + var otherArgs = Array(start + 1); + while (++index < start) { + otherArgs[index] = args[index]; + } + otherArgs[start] = transform(array); + return apply$3(func, this, otherArgs); + }; +} + +var _overRest = overRest$1; + +/** + * Creates a function that returns `value`. + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Util + * @param {*} value The value to return from the new function. + * @returns {Function} Returns the new constant function. + * @example + * + * var objects = _.times(2, _.constant({ 'a': 1 })); + * + * console.log(objects); + * // => [{ 'a': 1 }, { 'a': 1 }] + * + * console.log(objects[0] === objects[1]); + * // => true + */ + +function constant$1(value) { + return function() { + return value; + }; +} + +var constant_1 = constant$1; + +var constant = constant_1, + defineProperty = _defineProperty, + identity$2 = identity_1; + +/** + * The base implementation of `setToString` without support for hot loop shorting. + * + * @private + * @param {Function} func The function to modify. + * @param {Function} string The `toString` result. + * @returns {Function} Returns `func`. + */ +var baseSetToString$1 = !defineProperty ? identity$2 : function(func, string) { + return defineProperty(func, 'toString', { + 'configurable': true, + 'enumerable': false, + 'value': constant(string), + 'writable': true + }); +}; + +var _baseSetToString = baseSetToString$1; + +/** Used to detect hot functions by number of calls within a span of milliseconds. */ + +var HOT_COUNT = 800, + HOT_SPAN = 16; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeNow = Date.now; + +/** + * Creates a function that'll short out and invoke `identity` instead + * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` + * milliseconds. + * + * @private + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new shortable function. + */ +function shortOut$1(func) { + var count = 0, + lastCalled = 0; + + return function() { + var stamp = nativeNow(), + remaining = HOT_SPAN - (stamp - lastCalled); + + lastCalled = stamp; + if (remaining > 0) { + if (++count >= HOT_COUNT) { + return arguments[0]; + } + } else { + count = 0; + } + return func.apply(undefined, arguments); + }; +} + +var _shortOut = shortOut$1; + +var baseSetToString = _baseSetToString, + shortOut = _shortOut; + +/** + * Sets the `toString` method of `func` to return `string`. + * + * @private + * @param {Function} func The function to modify. + * @param {Function} string The `toString` result. + * @returns {Function} Returns `func`. + */ +var setToString$1 = shortOut(baseSetToString); + +var _setToString = setToString$1; + +var identity$1 = identity_1, + overRest = _overRest, + setToString = _setToString; + +/** + * The base implementation of `_.rest` which doesn't validate or coerce arguments. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. + */ +function baseRest$8(func, start) { + return setToString(overRest(func, start, identity$1), func + ''); +} + +var _baseRest = baseRest$8; + +var eq$3 = eq_1, + isArrayLike$6 = isArrayLike_1, + isIndex$1 = _isIndex, + isObject$b = isObject_1; + +/** + * Checks if the given arguments are from an iteratee call. + * + * @private + * @param {*} value The potential iteratee value argument. + * @param {*} index The potential iteratee index or key argument. + * @param {*} object The potential iteratee object argument. + * @returns {boolean} Returns `true` if the arguments are from an iteratee call, + * else `false`. + */ +function isIterateeCall$4(value, index, object) { + if (!isObject$b(object)) { + return false; + } + var type = typeof index; + if (type == 'number' + ? (isArrayLike$6(object) && isIndex$1(index, object.length)) + : (type == 'string' && index in object) + ) { + return eq$3(object[index], value); + } + return false; +} + +var _isIterateeCall = isIterateeCall$4; + +var baseFlatten$2 = _baseFlatten, + baseOrderBy = _baseOrderBy, + baseRest$7 = _baseRest, + isIterateeCall$3 = _isIterateeCall; + +/** + * Creates an array of elements, sorted in ascending order by the results of + * running each element in a collection thru each iteratee. This method + * performs a stable sort, that is, it preserves the original sort order of + * equal elements. The iteratees are invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {...(Function|Function[])} [iteratees=[_.identity]] + * The iteratees to sort by. + * @returns {Array} Returns the new sorted array. + * @example + * + * var users = [ + * { 'user': 'fred', 'age': 48 }, + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 30 }, + * { 'user': 'barney', 'age': 34 } + * ]; + * + * _.sortBy(users, [function(o) { return o.user; }]); + * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 30]] + * + * _.sortBy(users, ['user', 'age']); + * // => objects for [['barney', 34], ['barney', 36], ['fred', 30], ['fred', 48]] + */ +var sortBy$2 = baseRest$7(function(collection, iteratees) { + if (collection == null) { + return []; + } + var length = iteratees.length; + if (length > 1 && isIterateeCall$3(collection, iteratees[0], iteratees[1])) { + iteratees = []; + } else if (length > 2 && isIterateeCall$3(iteratees[0], iteratees[1], iteratees[2])) { + iteratees = [iteratees[0]]; + } + return baseOrderBy(collection, baseFlatten$2(iteratees, 1), []); +}); + +var sortBy_1 = sortBy$2; + +/** + * The base implementation of `_.findIndex` and `_.findLastIndex` without + * support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} predicate The function invoked per iteration. + * @param {number} fromIndex The index to search from. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + +function baseFindIndex$1(array, predicate, fromIndex, fromRight) { + var length = array.length, + index = fromIndex + (fromRight ? 1 : -1); + + while ((fromRight ? index-- : ++index < length)) { + if (predicate(array[index], index, array)) { + return index; + } + } + return -1; +} + +var _baseFindIndex = baseFindIndex$1; + +/** + * The base implementation of `_.isNaN` without support for number objects. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. + */ + +function baseIsNaN$1(value) { + return value !== value; +} + +var _baseIsNaN = baseIsNaN$1; + +/** + * A specialized version of `_.indexOf` which performs strict equality + * comparisons of values, i.e. `===`. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + +function strictIndexOf$1(array, value, fromIndex) { + var index = fromIndex - 1, + length = array.length; + + while (++index < length) { + if (array[index] === value) { + return index; + } + } + return -1; +} + +var _strictIndexOf = strictIndexOf$1; + +var baseFindIndex = _baseFindIndex, + baseIsNaN = _baseIsNaN, + strictIndexOf = _strictIndexOf; + +/** + * The base implementation of `_.indexOf` without `fromIndex` bounds checks. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function baseIndexOf$2(array, value, fromIndex) { + return value === value + ? strictIndexOf(array, value, fromIndex) + : baseFindIndex(array, baseIsNaN, fromIndex); +} + +var _baseIndexOf = baseIndexOf$2; + +var baseIndexOf$1 = _baseIndexOf; + +/** + * A specialized version of `_.includes` for arrays without support for + * specifying an index to search from. + * + * @private + * @param {Array} [array] The array to inspect. + * @param {*} target The value to search for. + * @returns {boolean} Returns `true` if `target` is found, else `false`. + */ +function arrayIncludes$3(array, value) { + var length = array == null ? 0 : array.length; + return !!length && baseIndexOf$1(array, value, 0) > -1; +} + +var _arrayIncludes = arrayIncludes$3; + +/** + * This function is like `arrayIncludes` except that it accepts a comparator. + * + * @private + * @param {Array} [array] The array to inspect. + * @param {*} target The value to search for. + * @param {Function} comparator The comparator invoked per element. + * @returns {boolean} Returns `true` if `target` is found, else `false`. + */ + +function arrayIncludesWith$3(array, value, comparator) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + if (comparator(value, array[index])) { + return true; + } + } + return false; +} + +var _arrayIncludesWith = arrayIncludesWith$3; + +/** + * This method returns `undefined`. + * + * @static + * @memberOf _ + * @since 2.3.0 + * @category Util + * @example + * + * _.times(2, _.noop); + * // => [undefined, undefined] + */ + +function noop$3() { + // No operation performed. +} + +var noop_1 = noop$3; + +var Set$1 = _Set, + noop$2 = noop_1, + setToArray$1 = _setToArray; + +/** Used as references for various `Number` constants. */ +var INFINITY$1 = 1 / 0; + +/** + * Creates a set object of `values`. + * + * @private + * @param {Array} values The values to add to the set. + * @returns {Object} Returns the new set. + */ +var createSet$1 = !(Set$1 && (1 / setToArray$1(new Set$1([,-0]))[1]) == INFINITY$1) ? noop$2 : function(values) { + return new Set$1(values); +}; + +var _createSet = createSet$1; + +var SetCache$2 = _SetCache, + arrayIncludes$2 = _arrayIncludes, + arrayIncludesWith$2 = _arrayIncludesWith, + cacheHas$2 = _cacheHas, + createSet = _createSet, + setToArray = _setToArray; + +/** Used as the size to enable large array optimizations. */ +var LARGE_ARRAY_SIZE$1 = 200; + +/** + * The base implementation of `_.uniqBy` without support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new duplicate free array. + */ +function baseUniq$2(array, iteratee, comparator) { + var index = -1, + includes = arrayIncludes$2, + length = array.length, + isCommon = true, + result = [], + seen = result; + + if (comparator) { + isCommon = false; + includes = arrayIncludesWith$2; + } + else if (length >= LARGE_ARRAY_SIZE$1) { + var set = iteratee ? null : createSet(array); + if (set) { + return setToArray(set); + } + isCommon = false; + includes = cacheHas$2; + seen = new SetCache$2; + } + else { + seen = iteratee ? [] : result; + } + outer: + while (++index < length) { + var value = array[index], + computed = iteratee ? iteratee(value) : value; + + value = (comparator || value !== 0) ? value : 0; + if (isCommon && computed === computed) { + var seenIndex = seen.length; + while (seenIndex--) { + if (seen[seenIndex] === computed) { + continue outer; + } + } + if (iteratee) { + seen.push(computed); + } + result.push(value); + } + else if (!includes(seen, computed, comparator)) { + if (seen !== result) { + seen.push(computed); + } + result.push(value); + } + } + return result; +} + +var _baseUniq = baseUniq$2; + +var baseUniq$1 = _baseUniq; + +/** + * Creates a duplicate-free version of an array, using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons, in which only the first occurrence of each element + * is kept. The order of result values is determined by the order they occur + * in the array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @returns {Array} Returns the new duplicate free array. + * @example + * + * _.uniq([2, 1, 2]); + * // => [2, 1] + */ +function uniq$3(array) { + return (array && array.length) ? baseUniq$1(array) : []; +} + +var uniq_1 = uniq$3; + +var baseUniq = _baseUniq; + +/** + * This method is like `_.uniq` except that it accepts `comparator` which + * is invoked to compare elements of `array`. The order of result values is + * determined by the order they occur in the array.The comparator is invoked + * with two arguments: (arrVal, othVal). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new duplicate free array. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * + * _.uniqWith(objects, _.isEqual); + * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }] + */ +function uniqWith$5(array, comparator) { + comparator = typeof comparator == 'function' ? comparator : undefined; + return (array && array.length) ? baseUniq(array, undefined, comparator) : []; +} + +var uniqWith_1 = uniqWith$5; + +var baseRest$6 = _baseRest, + eq$2 = eq_1, + isIterateeCall$2 = _isIterateeCall, + keysIn$2 = keysIn_1; + +/** Used for built-in method references. */ +var objectProto$2 = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty$3 = objectProto$2.hasOwnProperty; + +/** + * Assigns own and inherited enumerable string keyed properties of source + * objects to the destination object for all destination properties that + * resolve to `undefined`. Source objects are applied from left to right. + * Once a property is set, additional values of the same property are ignored. + * + * **Note:** This method mutates `object`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.defaultsDeep + * @example + * + * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); + * // => { 'a': 1, 'b': 2 } + */ +var defaults$1 = baseRest$6(function(object, sources) { + object = Object(object); + + var index = -1; + var length = sources.length; + var guard = length > 2 ? sources[2] : undefined; + + if (guard && isIterateeCall$2(sources[0], sources[1], guard)) { + length = 1; + } + + while (++index < length) { + var source = sources[index]; + var props = keysIn$2(source); + var propsIndex = -1; + var propsLength = props.length; + + while (++propsIndex < propsLength) { + var key = props[propsIndex]; + var value = object[key]; + + if (value === undefined || + (eq$2(value, objectProto$2[key]) && !hasOwnProperty$3.call(object, key))) { + object[key] = source[key]; + } + } + } + + return object; +}); + +var defaults_1 = defaults$1; + +var SetCache$1 = _SetCache, + arrayIncludes$1 = _arrayIncludes, + arrayIncludesWith$1 = _arrayIncludesWith, + arrayMap$4 = _arrayMap, + baseUnary$2 = _baseUnary, + cacheHas$1 = _cacheHas; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMin = Math.min; + +/** + * The base implementation of methods like `_.intersection`, without support + * for iteratee shorthands, that accepts an array of arrays to inspect. + * + * @private + * @param {Array} arrays The arrays to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of shared values. + */ +function baseIntersection$2(arrays, iteratee, comparator) { + var includes = comparator ? arrayIncludesWith$1 : arrayIncludes$1, + length = arrays[0].length, + othLength = arrays.length, + othIndex = othLength, + caches = Array(othLength), + maxLength = Infinity, + result = []; + + while (othIndex--) { + var array = arrays[othIndex]; + if (othIndex && iteratee) { + array = arrayMap$4(array, baseUnary$2(iteratee)); + } + maxLength = nativeMin(array.length, maxLength); + caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120)) + ? new SetCache$1(othIndex && array) + : undefined; + } + array = arrays[0]; + + var index = -1, + seen = caches[0]; + + outer: + while (++index < length && result.length < maxLength) { + var value = array[index], + computed = iteratee ? iteratee(value) : value; + + value = (comparator || value !== 0) ? value : 0; + if (!(seen + ? cacheHas$1(seen, computed) + : includes(result, computed, comparator) + )) { + othIndex = othLength; + while (--othIndex) { + var cache = caches[othIndex]; + if (!(cache + ? cacheHas$1(cache, computed) + : includes(arrays[othIndex], computed, comparator)) + ) { + continue outer; + } + } + if (seen) { + seen.push(computed); + } + result.push(value); + } + } + return result; +} + +var _baseIntersection = baseIntersection$2; + +var isArrayLike$5 = isArrayLike_1, + isObjectLike$3 = isObjectLike_1; + +/** + * This method is like `_.isArrayLike` except that it also checks if `value` + * is an object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array-like object, + * else `false`. + * @example + * + * _.isArrayLikeObject([1, 2, 3]); + * // => true + * + * _.isArrayLikeObject(document.body.children); + * // => true + * + * _.isArrayLikeObject('abc'); + * // => false + * + * _.isArrayLikeObject(_.noop); + * // => false + */ +function isArrayLikeObject$4(value) { + return isObjectLike$3(value) && isArrayLike$5(value); +} + +var isArrayLikeObject_1 = isArrayLikeObject$4; + +var isArrayLikeObject$3 = isArrayLikeObject_1; + +/** + * Casts `value` to an empty array if it's not an array like object. + * + * @private + * @param {*} value The value to inspect. + * @returns {Array|Object} Returns the cast array-like object. + */ +function castArrayLikeObject$2(value) { + return isArrayLikeObject$3(value) ? value : []; +} + +var _castArrayLikeObject = castArrayLikeObject$2; + +/** + * Gets the last element of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to query. + * @returns {*} Returns the last element of `array`. + * @example + * + * _.last([1, 2, 3]); + * // => 3 + */ + +function last$1(array) { + var length = array == null ? 0 : array.length; + return length ? array[length - 1] : undefined; +} + +var last_1 = last$1; + +var arrayMap$3 = _arrayMap, + baseIntersection$1 = _baseIntersection, + baseRest$5 = _baseRest, + castArrayLikeObject$1 = _castArrayLikeObject, + last = last_1; + +/** + * This method is like `_.intersection` except that it accepts `comparator` + * which is invoked to compare elements of `arrays`. The order and references + * of result values are determined by the first array. The comparator is + * invoked with two arguments: (arrVal, othVal). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of intersecting values. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * + * _.intersectionWith(objects, others, _.isEqual); + * // => [{ 'x': 1, 'y': 2 }] + */ +var intersectionWith$2 = baseRest$5(function(arrays) { + var comparator = last(arrays), + mapped = arrayMap$3(arrays, castArrayLikeObject$1); + + comparator = typeof comparator == 'function' ? comparator : undefined; + if (comparator) { + mapped.pop(); + } + return (mapped.length && mapped[0] === arrays[0]) + ? baseIntersection$1(mapped, undefined, comparator) + : []; +}); + +var intersectionWith_1 = intersectionWith$2; + +var baseGetTag$1 = _baseGetTag, + getPrototype = _getPrototype, + isObjectLike$2 = isObjectLike_1; + +/** `Object#toString` result references. */ +var objectTag = '[object Object]'; + +/** Used for built-in method references. */ +var funcProto = Function.prototype, + objectProto$1 = Object.prototype; + +/** Used to resolve the decompiled source of functions. */ +var funcToString = funcProto.toString; + +/** Used to check objects for own properties. */ +var hasOwnProperty$2 = objectProto$1.hasOwnProperty; + +/** Used to infer the `Object` constructor. */ +var objectCtorString = funcToString.call(Object); + +/** + * Checks if `value` is a plain object, that is, an object created by the + * `Object` constructor or one with a `[[Prototype]]` of `null`. + * + * @static + * @memberOf _ + * @since 0.8.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * _.isPlainObject(new Foo); + * // => false + * + * _.isPlainObject([1, 2, 3]); + * // => false + * + * _.isPlainObject({ 'x': 0, 'y': 0 }); + * // => true + * + * _.isPlainObject(Object.create(null)); + * // => true + */ +function isPlainObject$7(value) { + if (!isObjectLike$2(value) || baseGetTag$1(value) != objectTag) { + return false; + } + var proto = getPrototype(value); + if (proto === null) { + return true; + } + var Ctor = hasOwnProperty$2.call(proto, 'constructor') && proto.constructor; + return typeof Ctor == 'function' && Ctor instanceof Ctor && + funcToString.call(Ctor) == objectCtorString; +} + +var isPlainObject_1 = isPlainObject$7; + +var baseGetTag = _baseGetTag, + isObjectLike$1 = isObjectLike_1; + +/** `Object#toString` result references. */ +var boolTag = '[object Boolean]'; + +/** + * Checks if `value` is classified as a boolean primitive or object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a boolean, else `false`. + * @example + * + * _.isBoolean(false); + * // => true + * + * _.isBoolean(null); + * // => false + */ +function isBoolean$1(value) { + return value === true || value === false || + (isObjectLike$1(value) && baseGetTag(value) == boolTag); +} + +var isBoolean_1 = isBoolean$1; + +var isEqual$1 = isEqual_1; +var sortBy$1 = sortBy_1; +var uniq$2 = uniq_1; +var uniqWith$4 = uniqWith_1; +var defaults = defaults_1; +var intersectionWith$1 = intersectionWith_1; +var isPlainObject$6 = isPlainObject_1; +var isBoolean = isBoolean_1; + +var normalizeArray$1 = val => Array.isArray(val) + ? val : [val]; +var undef = val => val === undefined; +var keys$6 = obj => isPlainObject$6(obj) || Array.isArray(obj) ? Object.keys(obj) : []; +var has$3 = (obj, key) => obj.hasOwnProperty(key); +var stringArray$1 = arr => sortBy$1(uniq$2(arr)); +var undefEmpty = val => undef(val) || (Array.isArray(val) && val.length === 0); +var keyValEqual = (a, b, key, compare) => b && has$3(b, key) && a && has$3(a, key) && compare(a[key], b[key]); +var undefAndZero = (a, b) => (undef(a) && b === 0) || (undef(b) && a === 0) || isEqual$1(a, b); +var falseUndefined = (a, b) => (undef(a) && b === false) || (undef(b) && a === false) || isEqual$1(a, b); +var emptySchema = schema => undef(schema) || isEqual$1(schema, {}) || schema === true; +var emptyObjUndef = schema => undef(schema) || isEqual$1(schema, {}); +var isSchema$3 = val => undef(val) || isPlainObject$6(val) || val === true || val === false; + +function undefArrayEqual(a, b) { + if (undefEmpty(a) && undefEmpty(b)) { + return true + } else { + return isEqual$1(stringArray$1(a), stringArray$1(b)) + } +} + +function unsortedNormalizedArray(a, b) { + a = normalizeArray$1(a); + b = normalizeArray$1(b); + return isEqual$1(stringArray$1(a), stringArray$1(b)) +} + +function schemaGroup(a, b, key, compare) { + var allProps = uniq$2(keys$6(a).concat(keys$6(b))); + if (emptyObjUndef(a) && emptyObjUndef(b)) { + return true + } else if (emptyObjUndef(a) && keys$6(b).length) { + return false + } else if (emptyObjUndef(b) && keys$6(a).length) { + return false + } + + return allProps.every(function(key) { + var aVal = a[key]; + var bVal = b[key]; + if (Array.isArray(aVal) && Array.isArray(bVal)) { + return isEqual$1(stringArray$1(a), stringArray$1(b)) + } else if (Array.isArray(aVal) && !Array.isArray(bVal)) { + return false + } else if (Array.isArray(bVal) && !Array.isArray(aVal)) { + return false + } + return keyValEqual(a, b, key, compare) + }) +} + +function items$1(a, b, key, compare) { + if (isPlainObject$6(a) && isPlainObject$6(b)) { + return compare(a, b) + } else if (Array.isArray(a) && Array.isArray(b)) { + return schemaGroup(a, b, key, compare) + } else { + return isEqual$1(a, b) + } +} + +function unsortedArray(a, b, key, compare) { + var uniqueA = uniqWith$4(a, compare); + var uniqueB = uniqWith$4(b, compare); + var inter = intersectionWith$1(uniqueA, uniqueB, compare); + return inter.length === Math.max(uniqueA.length, uniqueB.length) +} + +var comparers = { + title: isEqual$1, + uniqueItems: falseUndefined, + minLength: undefAndZero, + minItems: undefAndZero, + minProperties: undefAndZero, + required: undefArrayEqual, + enum: undefArrayEqual, + type: unsortedNormalizedArray, + items: items$1, + anyOf: unsortedArray, + allOf: unsortedArray, + oneOf: unsortedArray, + properties: schemaGroup, + patternProperties: schemaGroup, + dependencies: schemaGroup +}; + +var acceptsUndefined = [ + 'properties', + 'patternProperties', + 'dependencies', + 'uniqueItems', + 'minLength', + 'minItems', + 'minProperties', + 'required' +]; + +var schemaProps$1 = ['additionalProperties', 'additionalItems', 'contains', 'propertyNames', 'not']; + +function compare$3(a, b, options) { + options = defaults(options, { + ignore: [] + }); + + if (emptySchema(a) && emptySchema(b)) { + return true + } + + if (!isSchema$3(a) || !isSchema$3(b)) { + throw new Error('Either of the values are not a JSON schema.') + } + if (a === b) { + return true + } + + if (isBoolean(a) && isBoolean(b)) { + return a === b + } + + if ((a === undefined && b === false) || (b === undefined && a === false)) { + return false + } + + if ((undef(a) && !undef(b)) || (!undef(a) && undef(b))) { + return false + } + + var allKeys = uniq$2(Object.keys(a).concat(Object.keys(b))); + + if (options.ignore.length) { + allKeys = allKeys.filter(k => options.ignore.indexOf(k) === -1); + } + + if (!allKeys.length) { + return true + } + + function innerCompare(a, b) { + return compare$3(a, b, options) + } + + return allKeys.every(function(key) { + var aValue = a[key]; + var bValue = b[key]; + + if (schemaProps$1.indexOf(key) !== -1) { + return compare$3(aValue, bValue, options) + } + + var comparer = comparers[key]; + if (!comparer) { + comparer = isEqual$1; + } + + // do simple lodash check first + if (isEqual$1(aValue, bValue)) { + return true + } + + if (acceptsUndefined.indexOf(key) === -1) { + if ((!has$3(a, key) && has$3(b, key)) || (has$3(a, key) && !has$3(b, key))) { + return aValue === bValue + } + } + + var result = comparer(aValue, bValue, key, innerCompare); + if (!isBoolean(result)) { + throw new Error('Comparer must return true or false') + } + return result + }) +} + +var src$1 = compare$3; + +/** +* FUNCTION: isArray( value ) +* Validates if a value is an array. +* +* @param {*} value - value to be validated +* @returns {Boolean} boolean indicating whether value is an array +*/ +function isArray$8( value ) { + return Object.prototype.toString.call( value ) === '[object Array]'; +} // end FUNCTION isArray() + +// EXPORTS // + +var lib$7 = Array.isArray || isArray$8; + +/** +* +* VALIDATE: number +* +* +* DESCRIPTION: +* - Validates if a value is a number. +* +* +* NOTES: +* [1] +* +* +* TODO: +* [1] +* +* +* LICENSE: +* MIT +* +* Copyright (c) 2014. Athan Reines. +* +* +* AUTHOR: +* Athan Reines. kgryte@gmail.com. 2014. +* +*/ + +/** +* FUNCTION: isNumber( value ) +* Validates if a value is a number. +* +* @param {*} value - value to be validated +* @returns {Boolean} boolean indicating whether value is a number +*/ +function isNumber$3( value ) { + return ( typeof value === 'number' || Object.prototype.toString.call( value ) === '[object Number]' ) && value.valueOf() === value.valueOf(); +} // end FUNCTION isNumber() + + +// EXPORTS // + +var lib$6 = isNumber$3; + +/** +* +* VALIDATE: integer +* +* +* DESCRIPTION: +* - Validates if a value is an integer. +* +* +* NOTES: +* [1] +* +* +* TODO: +* [1] +* +* +* LICENSE: +* MIT +* +* Copyright (c) 2014. Athan Reines. +* +* +* AUTHOR: +* Athan Reines. kgryte@gmail.com. 2014. +* +*/ + +// MODULES // + +var isNumber$2 = lib$6; + + +// ISINTEGER // + +/** +* FUNCTION: isInteger( value ) +* Validates if a value is an integer. +* +* @param {Number} value - value to be validated +* @returns {Boolean} boolean indicating whether value is an integer +*/ +function isInteger$1( value ) { + return isNumber$2( value ) && value%1 === 0; +} // end FUNCTION isInteger() + + +// EXPORTS // + +var lib$5 = isInteger$1; + +/** +* +* VALIDATE: integer-array +* +* +* DESCRIPTION: +* - Validates if a value is an integer array. +* +* +* NOTES: +* [1] +* +* +* TODO: +* [1] +* +* +* LICENSE: +* MIT +* +* Copyright (c) 2015. Athan Reines. +* +* +* AUTHOR: +* Athan Reines. kgryte@gmail.com. 2015. +* +*/ + +// MODULES // + +var isArray$7 = lib$7, + isInteger = lib$5; + + +// IS INTEGER ARRAY // + +/** +* FUNCTION: isIntegerArray( value ) +* Validates if a value is an integer array. +* +* @param {*} value - value to be validated +* @returns {Boolean} boolean indicating if a value is an integer array +*/ +function isIntegerArray$2( value ) { + var len; + if ( !isArray$7( value ) ) { + return false; + } + len = value.length; + if ( !len ) { + return false; + } + for ( var i = 0; i < len; i++ ) { + if ( !isInteger( value[i] ) ) { + return false; + } + } + return true; +} // end FUNCTION isIntegerArray() + + +// EXPORTS // + +var lib$4 = isIntegerArray$2; + +/** +* +* VALIDATE: function +* +* +* DESCRIPTION: +* - Validates if a value is a function. +* +* +* NOTES: +* [1] +* +* +* TODO: +* [1] +* +* +* LICENSE: +* MIT +* +* Copyright (c) 2014. Athan Reines. +* +* +* AUTHOR: +* Athan Reines. kgryte@gmail.com. 2014. +* +*/ + +/** +* FUNCTION: isFunction( value ) +* Validates if a value is a function. +* +* @param {*} value - value to be validated +* @returns {Boolean} boolean indicating whether value is a function +*/ +function isFunction$7( value ) { + return ( typeof value === 'function' ); +} // end FUNCTION isFunction() + + +// EXPORTS // + +var lib$3 = isFunction$7; + +// MODULES // + +var isArray$6 = lib$7, + isIntegerArray$1 = lib$4, + isFunction$6 = lib$3; + + +// VARIABLES // + +var MAXINT = Math.pow( 2, 31 ) - 1; + + +// FUNCTIONS // + +/** +* FUNCTION: gcd( a, b ) +* Computes the greatest common divisor of two integers `a` and `b`, using the binary GCD algorithm. +* +* @param {Number} a - integer +* @param {Number} b - integer +* @returns {Number} greatest common divisor +*/ +function gcd$1( a, b ) { + var k = 1, + t; + // Simple cases: + if ( a === 0 ) { + return b; + } + if ( b === 0 ) { + return a; + } + // Reduce `a` and/or `b` to odd numbers and keep track of the greatest power of 2 dividing both `a` and `b`... + while ( a%2 === 0 && b%2 === 0 ) { + a = a / 2; // right shift + b = b / 2; // right shift + k = k * 2; // left shift + } + // Reduce `a` to an odd number... + while ( a%2 === 0 ) { + a = a / 2; // right shift + } + // Henceforth, `a` is always odd... + while ( b ) { + // Remove all factors of 2 in `b`, as they are not common... + while ( b%2 === 0 ) { + b = b / 2; // right shift + } + // `a` and `b` are both odd. Swap values such that `b` is the larger of the two values, and then set `b` to the difference (which is even)... + if ( a > b ) { + t = b; + b = a; + a = t; + } + b = b - a; // b=0 iff b=a + } + // Restore common factors of 2... + return k * a; +} // end FUNCTION gcd() + +/** +* FUNCTION: bitwise( a, b ) +* Computes the greatest common divisor of two integers `a` and `b`, using the binary GCD algorithm and bitwise operations. +* +* @param {Number} a - safe integer +* @param {Number} b - safe integer +* @returns {Number} greatest common divisor +*/ +function bitwise( a, b ) { + var k = 0, + t; + // Simple cases: + if ( a === 0 ) { + return b; + } + if ( b === 0 ) { + return a; + } + // Reduce `a` and/or `b` to odd numbers and keep track of the greatest power of 2 dividing both `a` and `b`... + while ( (a & 1) === 0 && (b & 1) === 0 ) { + a >>>= 1; // right shift + b >>>= 1; // right shift + k++; + } + // Reduce `a` to an odd number... + while ( (a & 1) === 0 ) { + a >>>= 1; // right shift + } + // Henceforth, `a` is always odd... + while ( b ) { + // Remove all factors of 2 in `b`, as they are not common... + while ( (b & 1) === 0 ) { + b >>>= 1; // right shift + } + // `a` and `b` are both odd. Swap values such that `b` is the larger of the two values, and then set `b` to the difference (which is even)... + if ( a > b ) { + t = b; + b = a; + a = t; + } + b = b - a; // b=0 iff b=a + } + // Restore common factors of 2... + return a << k; +} // end FUNCTION bitwise() + + +// GREATEST COMMON DIVISOR // + +/** +* FUNCTION: compute( arr[, clbk] ) +* Computes the greatest common divisor. +* +* @param {Number[]|Number} arr - input array of integers +* @param {Function|Number} [clbk] - accessor function for accessing array values +* @returns {Number|Null} greatest common divisor or null +*/ +function compute() { + var nargs = arguments.length, + args, + clbk, + arr, + len, + a, b, + i; + + // Copy the input arguments to an array... + args = new Array( nargs ); + for ( i = 0; i < nargs; i++ ) { + args[ i ] = arguments[ i ]; + } + // Have we been provided with integer arguments? + if ( isIntegerArray$1( args ) ) { + if ( nargs === 2 ) { + a = args[ 0 ]; + b = args[ 1 ]; + if ( a < 0 ) { + a = -a; + } + if ( b < 0 ) { + b = -b; + } + if ( a <= MAXINT && b <= MAXINT ) { + return bitwise( a, b ); + } else { + return gcd$1( a, b ); + } + } + arr = args; + } + // If not integers, ensure the first argument is an array... + else if ( !isArray$6( args[ 0 ] ) ) { + throw new TypeError( 'gcd()::invalid input argument. Must provide an array of integers. Value: `' + args[ 0 ] + '`.' ); + } + // Have we been provided with more than one argument? If so, ensure that the accessor argument is a function... + else if ( nargs > 1 ) { + arr = args[ 0 ]; + clbk = args[ 1 ]; + if ( !isFunction$6( clbk ) ) { + throw new TypeError( 'gcd()::invalid input argument. Accessor must be a function. Value: `' + clbk + '`.' ); + } + } + // We have been provided an array... + else { + arr = args[ 0 ]; + } + len = arr.length; + + // Check if a sufficient number of values have been provided... + if ( len < 2 ) { + return null; + } + // If an accessor is provided, extract the array values... + if ( clbk ) { + a = new Array( len ); + for ( i = 0; i < len; i++ ) { + a[ i ] = clbk( arr[ i ], i ); + } + arr = a; + } + // Given an input array, ensure all array values are integers... + if ( nargs < 3 ) { + if ( !isIntegerArray$1( arr ) ) { + throw new TypeError( 'gcd()::invalid input argument. Accessed array values must be integers. Value: `' + arr + '`.' ); + } + } + // Convert any negative integers to positive integers... + for ( i = 0; i < len; i++ ) { + a = arr[ i ]; + if ( a < 0 ) { + arr[ i ] = -a; + } + } + // Exploit the fact that the gcd is an associative function... + a = arr[ 0 ]; + for ( i = 1; i < len; i++ ) { + b = arr[ i ]; + if ( b <= MAXINT && a <= MAXINT ) { + a = bitwise( a, b ); + } else { + a = gcd$1( a, b ); + } + } + return a; +} // end FUNCTION compute() + + +// EXPORTS // + +var lib$2 = compute; + +// MODULES // + +var gcd = lib$2, + isArray$5 = lib$7, + isIntegerArray = lib$4, + isFunction$5 = lib$3; + + +// LEAST COMMON MULTIPLE // + +/** +* FUNCTION: lcm( arr[, clbk] ) +* Computes the least common multiple (lcm). +* +* @param {Number[]|Number} arr - input array of integers +* @param {Function|Number} [accessor] - accessor function for accessing array values +* @returns {Number|Null} least common multiple or null +*/ +function lcm() { + var nargs = arguments.length, + args, + clbk, + arr, + len, + a, b, + i; + + // Copy the input arguments to an array... + args = new Array( nargs ); + for ( i = 0; i < nargs; i++ ) { + args[ i ] = arguments[ i ]; + } + // Have we been provided with integer arguments? + if ( isIntegerArray( args ) ) { + if ( nargs === 2 ) { + a = args[ 0 ]; + b = args[ 1 ]; + if ( a < 0 ) { + a = -a; + } + if ( b < 0 ) { + b = -b; + } + if ( a === 0 || b === 0 ) { + return 0; + } + return ( a/gcd(a,b) ) * b; + } + arr = args; + } + // If not integers, ensure that the first argument is an array... + else if ( !isArray$5( args[ 0 ] ) ) { + throw new TypeError( 'lcm()::invalid input argument. Must provide an array of integers. Value: `' + args[ 0 ] + '`.' ); + } + // Have we been provided with more than one argument? If so, ensure that the accessor argument is a function... + else if ( nargs > 1 ) { + arr = args[ 0 ]; + clbk = args[ 1 ]; + if ( !isFunction$5( clbk ) ) { + throw new TypeError( 'lcm()::invalid input argument. Accessor must be a function. Value: `' + clbk + '`.' ); + } + } + // We have been provided an array... + else { + arr = args[ 0 ]; + } + len = arr.length; + + // Check if a sufficient number of values have been provided... + if ( len < 2 ) { + return null; + } + // If an accessor is provided, extract the array values... + if ( clbk ) { + a = new Array( len ); + for ( i = 0; i < len; i++ ) { + a[ i ] = clbk( arr[ i ], i ); + } + arr = a; + } + // Given an input array, ensure all array values are integers... + if ( nargs < 3 ) { + if ( !isIntegerArray( arr ) ) { + throw new TypeError( 'lcm()::invalid input argument. Accessed array values must be integers. Value: `' + arr + '`.' ); + } + } + // Convert any negative integers to positive integers... + for ( i = 0; i < len; i++ ) { + a = arr[ i ]; + if ( a < 0 ) { + arr[ i ] = -a; + } + } + // Exploit the fact that the lcm is an associative function... + a = arr[ 0 ]; + for ( i = 1; i < len; i++ ) { + b = arr[ i ]; + if ( a === 0 || b === 0 ) { + return 0; + } + a = ( a/gcd(a,b) ) * b; + } + return a; +} // end FUNCTION lcm() + + +// EXPORTS // + +var lib$1 = lcm; + +var baseAssignValue = _baseAssignValue, + eq$1 = eq_1; + +/** + * This function is like `assignValue` except that it doesn't assign + * `undefined` values. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ +function assignMergeValue$2(object, key, value) { + if ((value !== undefined && !eq$1(object[key], value)) || + (value === undefined && !(key in object))) { + baseAssignValue(object, key, value); + } +} + +var _assignMergeValue = assignMergeValue$2; + +/** + * Gets the value at `key`, unless `key` is "__proto__" or "constructor". + * + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. + */ + +function safeGet$2(object, key) { + if (key === 'constructor' && typeof object[key] === 'function') { + return; + } + + if (key == '__proto__') { + return; + } + + return object[key]; +} + +var _safeGet = safeGet$2; + +var copyObject$1 = _copyObject, + keysIn$1 = keysIn_1; + +/** + * Converts `value` to a plain object flattening inherited enumerable string + * keyed properties of `value` to own properties of the plain object. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {Object} Returns the converted plain object. + * @example + * + * function Foo() { + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.assign({ 'a': 1 }, new Foo); + * // => { 'a': 1, 'b': 2 } + * + * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); + * // => { 'a': 1, 'b': 2, 'c': 3 } + */ +function toPlainObject$1(value) { + return copyObject$1(value, keysIn$1(value)); +} + +var toPlainObject_1 = toPlainObject$1; + +var assignMergeValue$1 = _assignMergeValue, + cloneBuffer = _cloneBufferExports, + cloneTypedArray = _cloneTypedArray, + copyArray$1 = _copyArray, + initCloneObject = _initCloneObject, + isArguments$2 = isArguments_1, + isArray$4 = isArray_1, + isArrayLikeObject$2 = isArrayLikeObject_1, + isBuffer = isBufferExports, + isFunction$4 = isFunction_1, + isObject$a = isObject_1, + isPlainObject$5 = isPlainObject_1, + isTypedArray = isTypedArray_1, + safeGet$1 = _safeGet, + toPlainObject = toPlainObject_1; + +/** + * A specialized version of `baseMerge` for arrays and objects which performs + * deep merges and tracks traversed objects enabling objects with circular + * references to be merged. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @param {string} key The key of the value to merge. + * @param {number} srcIndex The index of `source`. + * @param {Function} mergeFunc The function to merge values. + * @param {Function} [customizer] The function to customize assigned values. + * @param {Object} [stack] Tracks traversed source values and their merged + * counterparts. + */ +function baseMergeDeep$1(object, source, key, srcIndex, mergeFunc, customizer, stack) { + var objValue = safeGet$1(object, key), + srcValue = safeGet$1(source, key), + stacked = stack.get(srcValue); + + if (stacked) { + assignMergeValue$1(object, key, stacked); + return; + } + var newValue = customizer + ? customizer(objValue, srcValue, (key + ''), object, source, stack) + : undefined; + + var isCommon = newValue === undefined; + + if (isCommon) { + var isArr = isArray$4(srcValue), + isBuff = !isArr && isBuffer(srcValue), + isTyped = !isArr && !isBuff && isTypedArray(srcValue); + + newValue = srcValue; + if (isArr || isBuff || isTyped) { + if (isArray$4(objValue)) { + newValue = objValue; + } + else if (isArrayLikeObject$2(objValue)) { + newValue = copyArray$1(objValue); + } + else if (isBuff) { + isCommon = false; + newValue = cloneBuffer(srcValue, true); + } + else if (isTyped) { + isCommon = false; + newValue = cloneTypedArray(srcValue, true); + } + else { + newValue = []; + } + } + else if (isPlainObject$5(srcValue) || isArguments$2(srcValue)) { + newValue = objValue; + if (isArguments$2(objValue)) { + newValue = toPlainObject(objValue); + } + else if (!isObject$a(objValue) || isFunction$4(objValue)) { + newValue = initCloneObject(srcValue); + } + } + else { + isCommon = false; + } + } + if (isCommon) { + // Recursively merge objects and arrays (susceptible to call stack limits). + stack.set(srcValue, newValue); + mergeFunc(newValue, srcValue, srcIndex, customizer, stack); + stack['delete'](srcValue); + } + assignMergeValue$1(object, key, newValue); +} + +var _baseMergeDeep = baseMergeDeep$1; + +var Stack = _Stack, + assignMergeValue = _assignMergeValue, + baseFor = _baseFor, + baseMergeDeep = _baseMergeDeep, + isObject$9 = isObject_1, + keysIn = keysIn_1, + safeGet = _safeGet; + +/** + * The base implementation of `_.merge` without support for multiple sources. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @param {number} srcIndex The index of `source`. + * @param {Function} [customizer] The function to customize merged values. + * @param {Object} [stack] Tracks traversed source values and their merged + * counterparts. + */ +function baseMerge$2(object, source, srcIndex, customizer, stack) { + if (object === source) { + return; + } + baseFor(source, function(srcValue, key) { + stack || (stack = new Stack); + if (isObject$9(srcValue)) { + baseMergeDeep(object, source, key, srcIndex, baseMerge$2, customizer, stack); + } + else { + var newValue = customizer + ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack) + : undefined; + + if (newValue === undefined) { + newValue = srcValue; + } + assignMergeValue(object, key, newValue); + } + }, keysIn); +} + +var _baseMerge = baseMerge$2; + +var baseMerge$1 = _baseMerge, + isObject$8 = isObject_1; + +/** + * Used by `_.defaultsDeep` to customize its `_.merge` use to merge source + * objects into destination objects that are passed thru. + * + * @private + * @param {*} objValue The destination value. + * @param {*} srcValue The source value. + * @param {string} key The key of the property to merge. + * @param {Object} object The parent object of `objValue`. + * @param {Object} source The parent object of `srcValue`. + * @param {Object} [stack] Tracks traversed source values and their merged + * counterparts. + * @returns {*} Returns the value to assign. + */ +function customDefaultsMerge$1(objValue, srcValue, key, object, source, stack) { + if (isObject$8(objValue) && isObject$8(srcValue)) { + // Recursively merge objects and arrays (susceptible to call stack limits). + stack.set(srcValue, objValue); + baseMerge$1(objValue, srcValue, undefined, customDefaultsMerge$1, stack); + stack['delete'](srcValue); + } + return objValue; +} + +var _customDefaultsMerge = customDefaultsMerge$1; + +var baseRest$4 = _baseRest, + isIterateeCall$1 = _isIterateeCall; + +/** + * Creates a function like `_.assign`. + * + * @private + * @param {Function} assigner The function to assign values. + * @returns {Function} Returns the new assigner function. + */ +function createAssigner$2(assigner) { + return baseRest$4(function(object, sources) { + var index = -1, + length = sources.length, + customizer = length > 1 ? sources[length - 1] : undefined, + guard = length > 2 ? sources[2] : undefined; + + customizer = (assigner.length > 3 && typeof customizer == 'function') + ? (length--, customizer) + : undefined; + + if (guard && isIterateeCall$1(sources[0], sources[1], guard)) { + customizer = length < 3 ? undefined : customizer; + length = 1; + } + object = Object(object); + while (++index < length) { + var source = sources[index]; + if (source) { + assigner(object, source, index, customizer); + } + } + return object; + }); +} + +var _createAssigner = createAssigner$2; + +var baseMerge = _baseMerge, + createAssigner$1 = _createAssigner; + +/** + * This method is like `_.merge` except that it accepts `customizer` which + * is invoked to produce the merged values of the destination and source + * properties. If `customizer` returns `undefined`, merging is handled by the + * method instead. The `customizer` is invoked with six arguments: + * (objValue, srcValue, key, object, source, stack). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} sources The source objects. + * @param {Function} customizer The function to customize assigned values. + * @returns {Object} Returns `object`. + * @example + * + * function customizer(objValue, srcValue) { + * if (_.isArray(objValue)) { + * return objValue.concat(srcValue); + * } + * } + * + * var object = { 'a': [1], 'b': [2] }; + * var other = { 'a': [3], 'b': [4] }; + * + * _.mergeWith(object, other, customizer); + * // => { 'a': [1, 3], 'b': [2, 4] } + */ +var mergeWith$1 = createAssigner$1(function(object, source, srcIndex, customizer) { + baseMerge(object, source, srcIndex, customizer); +}); + +var mergeWith_1 = mergeWith$1; + +var apply$2 = _apply, + baseRest$3 = _baseRest, + customDefaultsMerge = _customDefaultsMerge, + mergeWith = mergeWith_1; + +/** + * This method is like `_.defaults` except that it recursively assigns + * default properties. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 3.10.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.defaults + * @example + * + * _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } }); + * // => { 'a': { 'b': 2, 'c': 3 } } + */ +var defaultsDeep$1 = baseRest$3(function(args) { + args.push(undefined, customDefaultsMerge); + return apply$2(mergeWith, undefined, args); +}); + +var defaultsDeep_1 = defaultsDeep$1; + +var baseFlatten$1 = _baseFlatten; + +/** + * Flattens `array` a single level deep. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to flatten. + * @returns {Array} Returns the new flattened array. + * @example + * + * _.flatten([1, [2, [3, [4]], 5]]); + * // => [1, 2, [3, [4]], 5] + */ +function flatten$2(array) { + var length = array == null ? 0 : array.length; + return length ? baseFlatten$1(array, 1) : []; +} + +var flatten_1 = flatten$2; + +var baseFlatten = _baseFlatten; + +/** Used as references for various `Number` constants. */ +var INFINITY = 1 / 0; + +/** + * Recursively flattens `array`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to flatten. + * @returns {Array} Returns the new flattened array. + * @example + * + * _.flattenDeep([1, [2, [3, [4]], 5]]); + * // => [1, 2, 3, 4, 5] + */ +function flattenDeep$2(array) { + var length = array == null ? 0 : array.length; + return length ? baseFlatten(array, INFINITY) : []; +} + +var flattenDeep_1 = flattenDeep$2; + +var arrayMap$2 = _arrayMap, + baseIntersection = _baseIntersection, + baseRest$2 = _baseRest, + castArrayLikeObject = _castArrayLikeObject; + +/** + * Creates an array of unique values that are included in all given arrays + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. The order and references of result values are + * determined by the first array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of intersecting values. + * @example + * + * _.intersection([2, 1], [2, 3]); + * // => [2] + */ +var intersection$1 = baseRest$2(function(arrays) { + var mapped = arrayMap$2(arrays, castArrayLikeObject); + return (mapped.length && mapped[0] === arrays[0]) + ? baseIntersection(mapped) + : []; +}); + +var intersection_1 = intersection$1; + +/** + * This function is like `baseIndexOf` except that it accepts a comparator. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @param {Function} comparator The comparator invoked per element. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + +function baseIndexOfWith$1(array, value, fromIndex, comparator) { + var index = fromIndex - 1, + length = array.length; + + while (++index < length) { + if (comparator(array[index], value)) { + return index; + } + } + return -1; +} + +var _baseIndexOfWith = baseIndexOfWith$1; + +var arrayMap$1 = _arrayMap, + baseIndexOf = _baseIndexOf, + baseIndexOfWith = _baseIndexOfWith, + baseUnary$1 = _baseUnary, + copyArray = _copyArray; + +/** Used for built-in method references. */ +var arrayProto = Array.prototype; + +/** Built-in value references. */ +var splice = arrayProto.splice; + +/** + * The base implementation of `_.pullAllBy` without support for iteratee + * shorthands. + * + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns `array`. + */ +function basePullAll$1(array, values, iteratee, comparator) { + var indexOf = comparator ? baseIndexOfWith : baseIndexOf, + index = -1, + length = values.length, + seen = array; + + if (array === values) { + values = copyArray(values); + } + if (iteratee) { + seen = arrayMap$1(array, baseUnary$1(iteratee)); + } + while (++index < length) { + var fromIndex = 0, + value = values[index], + computed = iteratee ? iteratee(value) : value; + + while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) { + if (seen !== array) { + splice.call(seen, fromIndex, 1); + } + splice.call(array, fromIndex, 1); + } + } + return array; +} + +var _basePullAll = basePullAll$1; + +var basePullAll = _basePullAll; + +/** + * This method is like `_.pull` except that it accepts an array of values to remove. + * + * **Note:** Unlike `_.difference`, this method mutates `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @returns {Array} Returns `array`. + * @example + * + * var array = ['a', 'b', 'c', 'a', 'b', 'c']; + * + * _.pullAll(array, ['a', 'c']); + * console.log(array); + * // => ['b', 'b'] + */ +function pullAll$1(array, values) { + return (array && array.length && values && values.length) + ? basePullAll(array, values) + : array; +} + +var pullAll_1 = pullAll$1; + +var identity = identity_1; + +/** + * Casts `value` to `identity` if it's not a function. + * + * @private + * @param {*} value The value to inspect. + * @returns {Function} Returns cast function. + */ +function castFunction$1(value) { + return typeof value == 'function' ? value : identity; +} + +var _castFunction = castFunction$1; + +var arrayEach = _arrayEach, + baseEach = _baseEach, + castFunction = _castFunction, + isArray$3 = isArray_1; + +/** + * Iterates over elements of `collection` and invokes `iteratee` for each element. + * The iteratee is invoked with three arguments: (value, index|key, collection). + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * **Note:** As with other "Collections" methods, objects with a "length" + * property are iterated like arrays. To avoid this behavior use `_.forIn` + * or `_.forOwn` for object iteration. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @alias each + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + * @see _.forEachRight + * @example + * + * _.forEach([1, 2], function(value) { + * console.log(value); + * }); + * // => Logs `1` then `2`. + * + * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) { + * console.log(key); + * }); + * // => Logs 'a' then 'b' (iteration order is not guaranteed). + */ +function forEach$5(collection, iteratee) { + var func = isArray$3(collection) ? arrayEach : baseEach; + return func(collection, castFunction(iteratee)); +} + +var forEach_1 = forEach$5; + +var SetCache = _SetCache, + arrayIncludes = _arrayIncludes, + arrayIncludesWith = _arrayIncludesWith, + arrayMap = _arrayMap, + baseUnary = _baseUnary, + cacheHas = _cacheHas; + +/** Used as the size to enable large array optimizations. */ +var LARGE_ARRAY_SIZE = 200; + +/** + * The base implementation of methods like `_.difference` without support + * for excluding multiple arrays or iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Array} values The values to exclude. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of filtered values. + */ +function baseDifference$1(array, values, iteratee, comparator) { + var index = -1, + includes = arrayIncludes, + isCommon = true, + length = array.length, + result = [], + valuesLength = values.length; + + if (!length) { + return result; + } + if (iteratee) { + values = arrayMap(values, baseUnary(iteratee)); + } + if (comparator) { + includes = arrayIncludesWith; + isCommon = false; + } + else if (values.length >= LARGE_ARRAY_SIZE) { + includes = cacheHas; + isCommon = false; + values = new SetCache(values); + } + outer: + while (++index < length) { + var value = array[index], + computed = iteratee == null ? value : iteratee(value); + + value = (comparator || value !== 0) ? value : 0; + if (isCommon && computed === computed) { + var valuesIndex = valuesLength; + while (valuesIndex--) { + if (values[valuesIndex] === computed) { + continue outer; + } + } + result.push(value); + } + else if (!includes(values, computed, comparator)) { + result.push(value); + } + } + return result; +} + +var _baseDifference = baseDifference$1; + +var baseDifference = _baseDifference, + baseRest$1 = _baseRest, + isArrayLikeObject$1 = isArrayLikeObject_1; + +/** + * Creates an array excluding all given values using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * **Note:** Unlike `_.pull`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...*} [values] The values to exclude. + * @returns {Array} Returns the new array of filtered values. + * @see _.difference, _.xor + * @example + * + * _.without([2, 1, 2, 3], 1, 2); + * // => [3] + */ +var without$1 = baseRest$1(function(array, values) { + return isArrayLikeObject$1(array) + ? baseDifference(array, values) + : []; +}); + +var without_1 = without$1; + +const flatten$1 = flatten_1; +const flattenDeep$1 = flattenDeep_1; +const isPlainObject$4 = isPlainObject_1; +const uniq$1 = uniq_1; +const uniqWith$3 = uniqWith_1; +const without = without_1; + +function deleteUndefinedProps$2(returnObject) { + // cleanup empty + for (const prop in returnObject) { + if (has$2(returnObject, prop) && isEmptySchema(returnObject[prop])) { + delete returnObject[prop]; + } + } + return returnObject +} + +const allUniqueKeys$3 = (arr) => uniq$1(flattenDeep$1(arr.map(keys$5))); +const getValues$2 = (schemas, key) => schemas.map(schema => schema && schema[key]); +const has$2 = (obj, propName) => Object.prototype.hasOwnProperty.call(obj, propName); +const keys$5 = obj => { + if (isPlainObject$4(obj) || Array.isArray(obj)) { + return Object.keys(obj) + } else { + return [] + } +}; + +const notUndefined$3 = (val) => val !== undefined; +const isSchema$2 = (val) => isPlainObject$4(val) || val === true || val === false; +const isEmptySchema = (obj) => (!keys$5(obj).length) && obj !== false && obj !== true; +const withoutArr$1 = (arr, ...rest) => without.apply(null, [arr].concat(flatten$1(rest))); + +var common = { + allUniqueKeys: allUniqueKeys$3, + deleteUndefinedProps: deleteUndefinedProps$2, + getValues: getValues$2, + has: has$2, + isEmptySchema, + isSchema: isSchema$2, + keys: keys$5, + notUndefined: notUndefined$3, + uniqWith: uniqWith$3, + withoutArr: withoutArr$1 +}; + +const compare$2 = src$1; +const forEach$4 = forEach_1; +const { + allUniqueKeys: allUniqueKeys$2, + deleteUndefinedProps: deleteUndefinedProps$1, + getValues: getValues$1, + keys: keys$4, + notUndefined: notUndefined$2, + uniqWith: uniqWith$2, + withoutArr +} = common; + +function removeFalseSchemas(target) { + forEach$4(target, function(schema, prop) { + if (schema === false) { + delete target[prop]; + } + }); +} + +function mergeSchemaGroup(group, mergeSchemas) { + const allKeys = allUniqueKeys$2(group); + return allKeys.reduce(function(all, key) { + const schemas = getValues$1(group, key); + const compacted = uniqWith$2(schemas.filter(notUndefined$2), compare$2); + all[key] = mergeSchemas(compacted, key); + return all + }, {}) +} + +var properties = { + keywords: ['properties', 'patternProperties', 'additionalProperties'], + resolver(values, parents, mergers, options) { + // first get rid of all non permitted properties + if (!options.ignoreAdditionalProperties) { + values.forEach(function(subSchema) { + const otherSubSchemas = values.filter(s => s !== subSchema); + const ownKeys = keys$4(subSchema.properties); + const ownPatternKeys = keys$4(subSchema.patternProperties); + const ownPatterns = ownPatternKeys.map(k => new RegExp(k)); + otherSubSchemas.forEach(function(other) { + const allOtherKeys = keys$4(other.properties); + const keysMatchingPattern = allOtherKeys.filter(k => ownPatterns.some(pk => pk.test(k))); + const additionalKeys = withoutArr(allOtherKeys, ownKeys, keysMatchingPattern); + additionalKeys.forEach(function(key) { + other.properties[key] = mergers.properties([ + other.properties[key], subSchema.additionalProperties + ], key); + }); + }); + }); + + // remove disallowed patternProperties + values.forEach(function(subSchema) { + const otherSubSchemas = values.filter(s => s !== subSchema); + const ownPatternKeys = keys$4(subSchema.patternProperties); + if (subSchema.additionalProperties === false) { + otherSubSchemas.forEach(function(other) { + const allOtherPatterns = keys$4(other.patternProperties); + const additionalPatternKeys = withoutArr(allOtherPatterns, ownPatternKeys); + additionalPatternKeys.forEach(key => delete other.patternProperties[key]); + }); + } + }); + } + + const returnObject = { + additionalProperties: mergers.additionalProperties(values.map(s => s.additionalProperties)), + patternProperties: mergeSchemaGroup(values.map(s => s.patternProperties), mergers.patternProperties), + properties: mergeSchemaGroup(values.map(s => s.properties), mergers.properties) + }; + + if (returnObject.additionalProperties === false) { + removeFalseSchemas(returnObject.properties); + } + + return deleteUndefinedProps$1(returnObject) + } +}; + +const compare$1 = src$1; +const forEach$3 = forEach_1; +const { + allUniqueKeys: allUniqueKeys$1, + deleteUndefinedProps, + has: has$1, + isSchema: isSchema$1, + notUndefined: notUndefined$1, + uniqWith: uniqWith$1 +} = common; + +function removeFalseSchemasFromArray(target) { + forEach$3(target, function(schema, index) { + if (schema === false) { + target.splice(index, 1); + } + }); +} + +function getItemSchemas(subSchemas, key) { + return subSchemas.map(function(sub) { + if (!sub) { + return undefined + } + + if (Array.isArray(sub.items)) { + const schemaAtPos = sub.items[key]; + if (isSchema$1(schemaAtPos)) { + return schemaAtPos + } else if (has$1(sub, 'additionalItems')) { + return sub.additionalItems + } + } else { + return sub.items + } + + return undefined + }) +} + +function getAdditionalSchemas(subSchemas) { + return subSchemas.map(function(sub) { + if (!sub) { + return undefined + } + if (Array.isArray(sub.items)) { + return sub.additionalItems + } + return sub.items + }) +} + +// Provide source when array +function mergeItems(group, mergeSchemas, items) { + const allKeys = allUniqueKeys$1(items); + return allKeys.reduce(function(all, key) { + const schemas = getItemSchemas(group, key); + const compacted = uniqWith$1(schemas.filter(notUndefined$1), compare$1); + all[key] = mergeSchemas(compacted, key); + return all + }, []) +} + +var items = { + keywords: ['items', 'additionalItems'], + resolver(values, parents, mergers) { + // const createSubMerger = groupKey => (schemas, key) => mergeSchemas(schemas, parents.concat(groupKey, key)) + const items = values.map(s => s.items); + const itemsCompacted = items.filter(notUndefined$1); + const returnObject = {}; + + // if all items keyword values are schemas, we can merge them as simple schemas + // if not we need to merge them as mixed + if (itemsCompacted.every(isSchema$1)) { + returnObject.items = mergers.items(items); + } else { + returnObject.items = mergeItems(values, mergers.items, items); + } + + let schemasAtLastPos; + if (itemsCompacted.every(Array.isArray)) { + schemasAtLastPos = values.map(s => s.additionalItems); + } else if (itemsCompacted.some(Array.isArray)) { + schemasAtLastPos = getAdditionalSchemas(values); + } + + if (schemasAtLastPos) { + returnObject.additionalItems = mergers.additionalItems(schemasAtLastPos); + } + + if (returnObject.additionalItems === false && Array.isArray(returnObject.items)) { + removeFalseSchemasFromArray(returnObject.items); + } + + return deleteUndefinedProps(returnObject) + } +}; + +const cloneDeep = cloneDeep_1; +const compare = src$1; +const computeLcm = lib$1; +const defaultsDeep = defaultsDeep_1; +const flatten = flatten_1; +const flattenDeep = flattenDeep_1; +const intersection = intersection_1; +const intersectionWith = intersectionWith_1; +const isEqual = isEqual_1; +const isPlainObject$3 = isPlainObject_1; +const pullAll = pullAll_1; +const sortBy = sortBy_1; +const uniq = uniq_1; +const uniqWith = uniqWith_1; + +const propertiesResolver = properties; +const itemsResolver = items; + +const contains$1 = (arr, val) => arr.indexOf(val) !== -1; +const isSchema = (val) => isPlainObject$3(val) || val === true || val === false; +const isFalse = (val) => val === false; +const isTrue = (val) => val === true; +const schemaResolver = (compacted, key, mergeSchemas) => mergeSchemas(compacted); +const stringArray = (values) => sortBy(uniq(flattenDeep(values))); +const notUndefined = (val) => val !== undefined; +const allUniqueKeys = (arr) => uniq(flattenDeep(arr.map(keys$3))); + +// resolvers +const first = compacted => compacted[0]; +const required = compacted => stringArray(compacted); +const maximumValue = compacted => Math.max.apply(Math, compacted); +const minimumValue = compacted => Math.min.apply(Math, compacted); +const uniqueItems = compacted => compacted.some(isTrue); +const examples = compacted => uniqWith(flatten(compacted), isEqual); + +function compareProp(key) { + return function(a, b) { + return compare({ + [key]: a + }, { [key]: b }) + } +} + +function getAllOf(schema) { + let { allOf = [], ...copy } = schema; + copy = isPlainObject$3(schema) ? copy : schema; // if schema is boolean + return [copy, ...allOf.map(getAllOf)] +} + +function getValues(schemas, key) { + return schemas.map(schema => schema && schema[key]) +} + +function tryMergeSchemaGroups(schemaGroups, mergeSchemas) { + return schemaGroups.map(function(schemas, index) { + try { + return mergeSchemas(schemas, index) + } catch (e) { + return undefined + } + }).filter(notUndefined) +} + +function keys$3(obj) { + if (isPlainObject$3(obj) || Array.isArray(obj)) { + return Object.keys(obj) + } else { + return [] + } +} + +function getAnyOfCombinations(arrOfArrays, combinations) { + combinations = combinations || []; + if (!arrOfArrays.length) { + return combinations + } + + const values = arrOfArrays.slice(0).shift(); + const rest = arrOfArrays.slice(1); + if (combinations.length) { + return getAnyOfCombinations(rest, flatten(combinations.map(combination => values.map(item => ([item].concat(combination)))))) + } + return getAnyOfCombinations(rest, values.map(item => (item))) +} + +function throwIncompatible(values, paths) { + let asJSON; + try { + asJSON = values.map(function(val) { + return JSON.stringify(val, null, 2) + }).join('\n'); + } catch (variable) { + asJSON = values.join(', '); + } + throw new Error('Could not resolve values for path:"' + paths.join('.') + '". They are probably incompatible. Values: \n' + asJSON) +} + +function callGroupResolver(complexKeywords, resolverName, schemas, mergeSchemas, options, parents) { + if (complexKeywords.length) { + const resolverConfig = options.complexResolvers[resolverName]; + if (!resolverConfig || !resolverConfig.resolver) { + throw new Error('No resolver found for ' + resolverName) + } + + // extract all keywords from all the schemas that have one or more + // then remove all undefined ones and not unique + const extractedKeywordsOnly = schemas.map(schema => complexKeywords.reduce((all, key) => { + if (schema[key] !== undefined) all[key] = schema[key]; + return all + }, {})); + const unique = uniqWith(extractedKeywordsOnly, compare); + + // create mergers that automatically add the path of the keyword for use in the complex resolver + const mergers = resolverConfig.keywords.reduce((all, key) => ({ + ...all, + [key]: (schemas, extraKey = []) => mergeSchemas(schemas, null, parents.concat(key, extraKey)) + }), {}); + + const result = resolverConfig.resolver(unique, parents.concat(resolverName), mergers, options); + + if (!isPlainObject$3(result)) { + throwIncompatible(unique, parents.concat(resolverName)); + } + + return result + } +} + +function createRequiredMetaArray(arr) { + return { required: arr } +} + +const schemaGroupProps = ['properties', 'patternProperties', 'definitions', 'dependencies']; +const schemaArrays = ['anyOf', 'oneOf']; +const schemaProps = [ + 'additionalProperties', + 'additionalItems', + 'contains', + 'propertyNames', + 'not', + 'items' +]; + +const defaultResolvers = { + type(compacted) { + if (compacted.some(Array.isArray)) { + const normalized = compacted.map(function(val) { + return Array.isArray(val) + ? val + : [val] + }); + const common = intersection.apply(null, normalized); + + if (common.length === 1) { + return common[0] + } else if (common.length > 1) { + return uniq(common) + } + } + }, + dependencies(compacted, paths, mergeSchemas) { + const allChildren = allUniqueKeys(compacted); + + return allChildren.reduce(function(all, childKey) { + const childSchemas = getValues(compacted, childKey); + let innerCompacted = uniqWith(childSchemas.filter(notUndefined), isEqual); + + // to support dependencies + const innerArrays = innerCompacted.filter(Array.isArray); + + if (innerArrays.length) { + if (innerArrays.length === innerCompacted.length) { + all[childKey] = stringArray(innerCompacted); + } else { + const innerSchemas = innerCompacted.filter(isSchema); + const arrayMetaScheams = innerArrays.map(createRequiredMetaArray); + all[childKey] = mergeSchemas(innerSchemas.concat(arrayMetaScheams), childKey); + } + return all + } + + innerCompacted = uniqWith(innerCompacted, compare); + + all[childKey] = mergeSchemas(innerCompacted, childKey); + return all + }, {}) + }, + oneOf(compacted, paths, mergeSchemas) { + const combinations = getAnyOfCombinations(cloneDeep(compacted)); + const result = tryMergeSchemaGroups(combinations, mergeSchemas); + const unique = uniqWith(result, compare); + + if (unique.length) { + return unique + } + }, + not(compacted) { + return { anyOf: compacted } + }, + pattern(compacted) { + return compacted.map(r => '(?=' + r + ')').join('') + }, + multipleOf(compacted) { + let integers = compacted.slice(0); + let factor = 1; + while (integers.some(n => !Number.isInteger(n))) { + integers = integers.map(n => n * 10); + factor = factor * 10; + } + return computeLcm(integers) / factor + }, + enum(compacted) { + const enums = intersectionWith.apply(null, compacted.concat(isEqual)); + if (enums.length) { + return sortBy(enums) + } + } +}; + +defaultResolvers.$id = first; +defaultResolvers.$ref = first; +defaultResolvers.$schema = first; +defaultResolvers.additionalItems = schemaResolver; +defaultResolvers.additionalProperties = schemaResolver; +defaultResolvers.anyOf = defaultResolvers.oneOf; +defaultResolvers.contains = schemaResolver; +defaultResolvers.default = first; +defaultResolvers.definitions = defaultResolvers.dependencies; +defaultResolvers.description = first; +defaultResolvers.examples = examples; +defaultResolvers.exclusiveMaximum = minimumValue; +defaultResolvers.exclusiveMinimum = maximumValue; +defaultResolvers.items = itemsResolver; +defaultResolvers.maximum = minimumValue; +defaultResolvers.maxItems = minimumValue; +defaultResolvers.maxLength = minimumValue; +defaultResolvers.maxProperties = minimumValue; +defaultResolvers.minimum = maximumValue; +defaultResolvers.minItems = maximumValue; +defaultResolvers.minLength = maximumValue; +defaultResolvers.minProperties = maximumValue; +defaultResolvers.properties = propertiesResolver; +defaultResolvers.propertyNames = schemaResolver; +defaultResolvers.required = required; +defaultResolvers.title = first; +defaultResolvers.uniqueItems = uniqueItems; + +const defaultComplexResolvers = { + properties: propertiesResolver, + items: itemsResolver +}; + +function merger(rootSchema, options, totalSchemas) { + options = defaultsDeep(options, { + ignoreAdditionalProperties: false, + resolvers: defaultResolvers, + complexResolvers: defaultComplexResolvers, + deep: true + }); + + const complexResolvers = Object.entries(options.complexResolvers); + + function mergeSchemas(schemas, base, parents) { + schemas = cloneDeep(schemas.filter(notUndefined)); + parents = parents || []; + const merged = isPlainObject$3(base) + ? base + : {}; + + // return undefined, an empty schema + if (!schemas.length) { + return + } + + if (schemas.some(isFalse)) { + return false + } + + if (schemas.every(isTrue)) { + return true + } + + // there are no false and we don't need the true ones as they accept everything + schemas = schemas.filter(isPlainObject$3); + + const allKeys = allUniqueKeys(schemas); + if (options.deep && contains$1(allKeys, 'allOf')) { + return merger({ + allOf: schemas + }, options) + } + + const complexKeysArr = complexResolvers.map(([mainKeyWord, resolverConf]) => + allKeys.filter(k => resolverConf.keywords.includes(k))); + + // remove all complex keys before simple resolvers + complexKeysArr.forEach(keys => pullAll(allKeys, keys)); + + // call all simple resolvers for relevant keywords + allKeys.forEach(function(key) { + const values = getValues(schemas, key); + const compacted = uniqWith(values.filter(notUndefined), compareProp(key)); + + // arrayprops like anyOf and oneOf must be merged first, as they contains schemas + // allOf is treated differently alltogether + if (compacted.length === 1 && contains$1(schemaArrays, key)) { + merged[key] = compacted[0].map(schema => mergeSchemas([schema], schema)); + // prop groups must always be resolved + } else if (compacted.length === 1 && !contains$1(schemaGroupProps, key) && !contains$1(schemaProps, key)) { + merged[key] = compacted[0]; + } else { + const resolver = options.resolvers[key] || options.resolvers.defaultResolver; + if (!resolver) throw new Error('No resolver found for key ' + key + '. You can provide a resolver for this keyword in the options, or provide a default resolver.') + + const merger = (schemas, extraKey = []) => mergeSchemas(schemas, null, parents.concat(key, extraKey)); + merged[key] = resolver(compacted, parents.concat(key), merger, options); + + if (merged[key] === undefined) { + throwIncompatible(compacted, parents.concat(key)); + } else if (merged[key] === undefined) { + delete merged[key]; + } + } + }); + + return complexResolvers.reduce((all, [resolverKeyword, config], index) => ({ + ...all, + ...callGroupResolver(complexKeysArr[index], resolverKeyword, schemas, mergeSchemas, options, parents) + }), merged) + } + + const allSchemas = flattenDeep(getAllOf(rootSchema)); + const merged = mergeSchemas(allSchemas); + + return merged +} + +merger.options = { + resolvers: defaultResolvers +}; + +var src = merger; + +var mergeJSONSchemaAllOf = /*@__PURE__*/getDefaultExportFromCjs(src); + +// src/index.ts +function isObject$7(obj) { + return typeof obj === "object" && obj !== null && !Array.isArray(obj); +} +function isEmptyObject(obj) { + return typeof obj === "object" && obj !== null && !Object.keys(obj).length; +} +function stripEmptyObjects(obj) { + const cleanObj = obj; + if (!isObject$7(obj) && !Array.isArray(cleanObj)) { + return cleanObj; + } else if (obj === null) { + return void 0; + } + if (!Array.isArray(cleanObj)) { + Object.keys(cleanObj).forEach((key) => { + let value = cleanObj[key]; + if (typeof value === "object" && value !== null) { + value = stripEmptyObjects(value); + if (isEmptyObject(value)) { + delete cleanObj[key]; + } else { + cleanObj[key] = value; + } + } + }); + return cleanObj; + } + cleanObj.forEach((o, idx) => { + let value = o; + if (typeof value === "object" && value !== null) { + value = stripEmptyObjects(value); + if (isEmptyObject(value)) { + delete cleanObj[idx]; + } else { + cleanObj[idx] = value; + } + } else if (value === null) { + delete cleanObj[idx]; + } + }); + return cleanObj.filter((el) => el !== void 0); +} +function removeUndefinedObjects(obj) { + if (obj === void 0) { + return void 0; + } + let withoutUndefined = JSON.parse(JSON.stringify(obj)); + withoutUndefined = stripEmptyObjects(withoutUndefined); + if (isEmptyObject(withoutUndefined)) + return void 0; + return withoutUndefined; +} + +// src/lib/clone-object.ts +function cloneObject(obj) { + if (typeof obj === "undefined") { + return void 0; + } + return JSON.parse(JSON.stringify(obj)); +} + +// src/lib/helpers.ts +function hasSchemaType(schema, discriminator) { + if (Array.isArray(schema.type)) { + return schema.type.includes(discriminator); + } + return schema.type === discriminator; +} +function isObject$6(val) { + return typeof val === "object" && val !== null && !Array.isArray(val); +} +function isPrimitive$2(val) { + return typeof val === "string" || typeof val === "number" || typeof val === "boolean"; +} + +// src/lib/matches-mimetype.ts +function matchesMediaType(types2, mediaType) { + return types2.some((type) => { + return mediaType.indexOf(type) > -1; + }); +} +var matches_mimetype_default = { + formUrlEncoded: (mimeType) => { + return matchesMediaType(["application/x-www-form-urlencoded"], mimeType); + }, + json: (contentType) => { + return matchesMediaType( + ["application/json", "application/x-json", "text/json", "text/x-json", "+json"], + contentType + ); + }, + multipart: (contentType) => { + return matchesMediaType( + ["multipart/mixed", "multipart/related", "multipart/form-data", "multipart/alternative"], + contentType + ); + }, + wildcard: (contentType) => { + return contentType === "*/*"; + }, + xml: (contentType) => { + return matchesMediaType( + [ + "application/xml", + "application/xml-external-parsed-entity", + "application/xml-dtd", + "text/xml", + "text/xml-external-parsed-entity", + "+xml" + ], + contentType + ); + } +}; +var UNSUPPORTED_SCHEMA_PROPS = [ + "example", + // OpenAPI supports `example` but we're mapping it to `examples` in this library. + "externalDocs", + "xml" +]; +var FORMAT_OPTIONS = { + INT8_MIN: 0 - 2 ** 7, + // -128 + INT8_MAX: 2 ** 7 - 1, + // 127 + INT16_MIN: 0 - 2 ** 15, + // -32768 + INT16_MAX: 2 ** 15 - 1, + // 32767 + INT32_MIN: 0 - 2 ** 31, + // -2147483648 + INT32_MAX: 2 ** 31 - 1, + // 2147483647 + INT64_MIN: 0 - 2 ** 63, + // -9223372036854775808 + INT64_MAX: 2 ** 63 - 1, + // 9223372036854775807 + UINT8_MIN: 0, + UINT8_MAX: 2 ** 8 - 1, + // 255 + UINT16_MIN: 0, + UINT16_MAX: 2 ** 16 - 1, + // 65535 + UINT32_MIN: 0, + UINT32_MAX: 2 ** 32 - 1, + // 4294967295 + UINT64_MIN: 0, + UINT64_MAX: 2 ** 64 - 1, + // 18446744073709551615 + FLOAT_MIN: 0 - 2 ** 128, + // -3.402823669209385e+38 + FLOAT_MAX: 2 ** 128 - 1, + // 3.402823669209385e+38 + DOUBLE_MIN: 0 - Number.MAX_VALUE, + DOUBLE_MAX: Number.MAX_VALUE +}; +function encodePointer(str) { + return str.replace("~", "~0").replace("/", "~1"); +} +function getSchemaVersionString(schema, api) { + if (!isOAS31(api)) { + return "http://json-schema.org/draft-04/schema#"; + } + if (schema.$schema) { + return schema.$schema; + } + if (api.jsonSchemaDialect) { + return api.jsonSchemaDialect; + } + return "https://json-schema.org/draft/2020-12/schema#"; +} +function isPolymorphicSchema(schema) { + return "allOf" in schema || "anyOf" in schema || "oneOf" in schema; +} +function isRequestBodySchema(schema) { + return "content" in schema; +} +function searchForValueByPropAndPointer(property, pointer, schemas = []) { + if (!schemas.length || !pointer.length) { + return void 0; + } + const locSplit = pointer.split("/").filter(Boolean).reverse(); + const pointers = []; + let point = ""; + for (let i = 0; i < locSplit.length; i += 1) { + point = `/${locSplit[i]}${point}`; + pointers.push(point); + } + let foundValue; + const rev = [...schemas].reverse(); + for (let i = 0; i < pointers.length; i += 1) { + for (let ii = 0; ii < rev.length; ii += 1) { + let schema = rev[ii]; + if (property === "example") { + if ("example" in schema) { + schema = schema.example; + } else { + if (!Array.isArray(schema.examples) || !schema.examples.length) { + continue; + } + schema = [...schema.examples].shift(); + } + } else { + schema = schema.default; + } + try { + foundValue = jsonpointer.get(schema, pointers[i]); + } catch (err) { + } + if (foundValue !== void 0) { + break; + } + } + if (foundValue !== void 0) { + break; + } + } + return foundValue; +} +function toJSONSchema(data, opts = {}) { + let schema = data === true ? {} : { ...data }; + const schemaAdditionalProperties = isSchema$4(schema) ? schema.additionalProperties : null; + const { + addEnumsToDescriptions, + currentLocation, + globalDefaults, + hideReadOnlyProperties, + hideWriteOnlyProperties, + isPolymorphicAllOfChild, + prevDefaultSchemas, + prevExampleSchemas, + refLogger, + transformer + } = { + addEnumsToDescriptions: false, + currentLocation: "", + globalDefaults: {}, + hideReadOnlyProperties: false, + hideWriteOnlyProperties: false, + isPolymorphicAllOfChild: false, + prevDefaultSchemas: [], + prevExampleSchemas: [], + refLogger: () => true, + transformer: (s) => s, + ...opts + }; + if (isRef(schema)) { + refLogger(schema.$ref, "ref"); + return transformer({ + $ref: schema.$ref + }); + } + if (isSchema$4(schema, isPolymorphicAllOfChild)) { + if ("allOf" in schema && Array.isArray(schema.allOf)) { + try { + schema = mergeJSONSchemaAllOf(schema, { + ignoreAdditionalProperties: true, + resolvers: { + // `merge-json-schema-allof` by default takes the first `description` when you're + // merging an `allOf` but because generally when you're merging two schemas together + // with an `allOf` you want data in the subsequent schemas to be applied to the first + // and `description` should be a part of that. + description: (obj) => { + return obj.slice(-1)[0]; + }, + // `merge-json-schema-allof` doesn't support merging enum arrays but since that's a + // safe and simple operation as enums always contain primitives we can handle it + // ourselves with a custom resolver. + enum: (obj) => { + let arr = []; + obj.forEach((e) => { + arr = arr.concat(e); + }); + return arr; + }, + // JSON Schema ony supports examples with the `examples` property, since we're + // ingesting OpenAPI definitions we need to add a custom resolver for its `example` + // property. + example: (obj) => obj[0], + // JSON Schema has no support for `format` on anything other than `string`, but since + // OpenAPI has it on `integer` and `number` we need to add a custom resolver here so we + // can still merge schemas that may have those. + format: (obj) => obj[0], + // Since JSON Schema obviously doesn't know about our vendor extension we need to tell + // the library to essentially ignore and pass it along. + "x-readme-ref-name": (obj) => obj[0] + } + }); + } catch (e) { + const { ...schemaWithoutAllOf } = schema; + schema = schemaWithoutAllOf; + delete schema.allOf; + } + if (isRef(schema)) { + refLogger(schema.$ref, "ref"); + return transformer({ + $ref: schema.$ref + }); + } + } + ["anyOf", "oneOf"].forEach((polyType) => { + if (polyType in schema && Array.isArray(schema[polyType])) { + schema[polyType].forEach((item, idx) => { + const polyOptions = { + addEnumsToDescriptions, + currentLocation: `${currentLocation}/${idx}`, + globalDefaults, + hideReadOnlyProperties, + hideWriteOnlyProperties, + isPolymorphicAllOfChild: false, + prevDefaultSchemas, + prevExampleSchemas, + refLogger, + transformer + }; + if ("properties" in schema) { + schema[polyType][idx] = toJSONSchema( + { allOf: [item, { properties: schema.properties }] }, + polyOptions + ); + } else if ("items" in schema) { + schema[polyType][idx] = toJSONSchema( + { allOf: [item, { items: schema.items }] }, + polyOptions + ); + } else { + schema[polyType][idx] = toJSONSchema(item, polyOptions); + } + if (isObject$6(schema[polyType][idx]) && "required" in schema[polyType][idx] && typeof schema[polyType][idx].required === "boolean") { + delete schema[polyType][idx].required; + } + }); + } + }); + if ("discriminator" in schema) { + if ("mapping" in schema.discriminator && typeof schema.discriminator.mapping === "object") { + const mapping = schema.discriminator.mapping; + Object.keys(mapping).forEach((k) => { + refLogger(mapping[k], "discriminator"); + }); + } + } + } + if (!("type" in schema) && !isPolymorphicSchema(schema) && !isRequestBodySchema(schema)) { + if ("properties" in schema) { + schema.type = "object"; + } else if ("items" in schema) { + schema.type = "array"; + } else ; + } + if ("type" in schema) { + if ("nullable" in schema) { + if (Array.isArray(schema.type)) { + schema.type.push("null"); + } else if (schema.type !== null && schema.type !== "null") { + schema.type = [schema.type, "null"]; + } + delete schema.nullable; + } + if (schema.type === null) { + schema.type = "null"; + } else if (Array.isArray(schema.type)) { + if (schema.type.includes(null)) { + schema.type[schema.type.indexOf(null)] = "null"; + } + schema.type = Array.from(new Set(schema.type)); + if (schema.type.length === 1) { + schema.type = schema.type.shift(); + } else if (schema.type.includes("array") || schema.type.includes("boolean") || schema.type.includes("object")) { + const isNullable = schema.type.includes("null"); + if (schema.type.length === 2 && isNullable) ; else { + const nonPrimitives = []; + Object.entries({ + // https://json-schema.org/understanding-json-schema/reference/array.html + array: [ + "additionalItems", + "contains", + "items", + "maxContains", + "maxItems", + "minContains", + "minItems", + "prefixItems", + "uniqueItems" + ], + // https://json-schema.org/understanding-json-schema/reference/boolean.html + boolean: [ + // Booleans don't have any boolean-specific properties. + ], + // https://json-schema.org/understanding-json-schema/reference/object.html + object: [ + "additionalProperties", + "maxProperties", + "minProperties", + "nullable", + "patternProperties", + "properties", + "propertyNames", + "required" + ] + }).forEach(([typeKey, keywords]) => { + if (!schema.type.includes(typeKey)) { + return; + } + const reducedSchema = removeUndefinedObjects({ + type: isNullable ? [typeKey, "null"] : typeKey, + allowEmptyValue: schema.allowEmptyValue ?? void 0, + deprecated: schema.deprecated ?? void 0, + description: schema.description ?? void 0, + readOnly: schema.readOnly ?? void 0, + title: schema.title ?? void 0, + writeOnly: schema.writeOnly ?? void 0 + }); + keywords.forEach((t) => { + if (t in schema) { + reducedSchema[t] = schema[t]; + delete schema[t]; + } + }); + nonPrimitives.push(reducedSchema); + }); + schema.type = schema.type.filter((t) => t !== "array" && t !== "boolean" && t !== "object"); + if (schema.type.length === 1) { + schema.type = schema.type.shift(); + } + if (schema.type.length > 1) { + schema = { oneOf: [schema, ...nonPrimitives] }; + } else { + schema = { oneOf: nonPrimitives }; + } + } + } + } + } + if (isSchema$4(schema, isPolymorphicAllOfChild)) { + if ("default" in schema && isObject$6(schema.default)) { + prevDefaultSchemas.push({ default: schema.default }); + } + if ("example" in schema) { + if (isPrimitive$2(schema.example)) { + schema.examples = [schema.example]; + } else if (Array.isArray(schema.example)) { + schema.examples = schema.example.filter((example) => isPrimitive$2(example)); + if (!schema.examples.length) { + delete schema.examples; + } + } else { + prevExampleSchemas.push({ example: schema.example }); + } + delete schema.example; + } else if ("examples" in schema) { + let reshapedExamples = false; + if (typeof schema.examples === "object" && !Array.isArray(schema.examples)) { + const examples = []; + Object.keys(schema.examples).forEach((name) => { + const example = schema.examples[name]; + if ("$ref" in example) { + refLogger(example.$ref, "ref"); + } else if ("value" in example) { + if (isPrimitive$2(example.value)) { + examples.push(example.value); + reshapedExamples = true; + } else if (Array.isArray(example.value) && isPrimitive$2(example.value[0])) { + examples.push(example.value[0]); + reshapedExamples = true; + } else { + prevExampleSchemas.push({ + example: example.value + }); + } + } + }); + if (examples.length) { + reshapedExamples = true; + schema.examples = examples; + } + } else if (Array.isArray(schema.examples) && isPrimitive$2(schema.examples[0])) { + reshapedExamples = true; + } + if (!reshapedExamples) { + delete schema.examples; + } + } + if (!hasSchemaType(schema, "array") && !hasSchemaType(schema, "object") && !schema.examples) { + const foundExample = searchForValueByPropAndPointer("example", currentLocation, prevExampleSchemas); + if (foundExample) { + if (isPrimitive$2(foundExample) || Array.isArray(foundExample) && isPrimitive$2(foundExample[0])) { + schema.examples = [foundExample]; + } + } + } + if (hasSchemaType(schema, "array")) { + if ("items" in schema) { + if (!Array.isArray(schema.items) && Object.keys(schema.items).length === 1 && isRef(schema.items)) { + refLogger(schema.items.$ref, "ref"); + } else if (schema.items !== true) { + schema.items = toJSONSchema(schema.items, { + addEnumsToDescriptions, + currentLocation: `${currentLocation}/0`, + globalDefaults, + hideReadOnlyProperties, + hideWriteOnlyProperties, + prevExampleSchemas, + refLogger, + transformer + }); + if (isObject$6(schema.items) && "required" in schema.items && !Array.isArray(schema.items.required)) { + delete schema.items.required; + } + } + } else if ("properties" in schema || "additionalProperties" in schema) { + schema.type = "object"; + } else { + schema.items = {}; + } + } else if (hasSchemaType(schema, "object")) { + if ("properties" in schema) { + Object.keys(schema.properties).forEach((prop) => { + if (Array.isArray(schema.properties[prop]) || typeof schema.properties[prop] === "object" && schema.properties[prop] !== null) { + const newPropSchema = toJSONSchema(schema.properties[prop], { + addEnumsToDescriptions, + currentLocation: `${currentLocation}/${encodePointer(prop)}`, + globalDefaults, + hideReadOnlyProperties, + hideWriteOnlyProperties, + prevDefaultSchemas, + prevExampleSchemas, + refLogger, + transformer + }); + let propShouldBeUpdated = true; + if ((hideReadOnlyProperties || hideWriteOnlyProperties) && !Object.keys(newPropSchema).length) { + if (Object.keys(schema.properties[prop]).length > 0) { + delete schema.properties[prop]; + propShouldBeUpdated = false; + } + } + if (propShouldBeUpdated) { + schema.properties[prop] = newPropSchema; + if (isObject$6(newPropSchema) && "required" in newPropSchema && typeof newPropSchema.required === "boolean" && newPropSchema.required === true) { + if ("required" in schema && Array.isArray(schema.required)) { + schema.required.push(prop); + } else { + schema.required = [prop]; + } + delete schema.properties[prop].required; + } + } + } + }); + if (hideReadOnlyProperties || hideWriteOnlyProperties) { + if (!Object.keys(schema.properties).length) { + return transformer({}); + } + } + } + if (typeof schemaAdditionalProperties === "object" && schemaAdditionalProperties !== null) { + if (!("type" in schemaAdditionalProperties) && !("$ref" in schemaAdditionalProperties) && // We know it will be a schema object because it's dereferenced + !isPolymorphicSchema(schemaAdditionalProperties)) { + schema.additionalProperties = true; + } else { + schema.additionalProperties = toJSONSchema(schemaAdditionalProperties, { + addEnumsToDescriptions, + currentLocation, + globalDefaults, + hideReadOnlyProperties, + hideWriteOnlyProperties, + prevDefaultSchemas, + prevExampleSchemas, + refLogger, + transformer + }); + } + } + if (!isPolymorphicSchema(schema) && !("properties" in schema) && !("additionalProperties" in schema)) { + schema.additionalProperties = true; + } + } + } + if ((schema.type === "number" || schema.type === "integer") && "format" in schema) { + const formatUpper = schema.format.toUpperCase(); + if (`${formatUpper}_MIN` in FORMAT_OPTIONS) { + if (!schema.minimum && schema.minimum !== 0 || schema.minimum < FORMAT_OPTIONS[`${formatUpper}_MIN`]) { + schema.minimum = FORMAT_OPTIONS[`${formatUpper}_MIN`]; + } + } + if (`${formatUpper}_MAX` in FORMAT_OPTIONS) { + if (!schema.maximum && schema.maximum !== 0 || schema.maximum > FORMAT_OPTIONS[`${formatUpper}_MAX`]) { + schema.maximum = FORMAT_OPTIONS[`${formatUpper}_MAX`]; + } + } + } + if (isSchema$4(schema, isPolymorphicAllOfChild) && globalDefaults && Object.keys(globalDefaults).length > 0 && currentLocation) { + try { + const userJwtDefault = jsonpointer.get(globalDefaults, currentLocation); + if (userJwtDefault) { + schema.default = userJwtDefault; + } + } catch (err) { + } + } + if ("default" in schema && typeof schema.default !== "undefined") { + if (hasSchemaType(schema, "object")) { + delete schema.default; + } else { + if ("enum" in schema && !addEnumsToDescriptions) { + schema.description = schema.description ? `${schema.description.replace(/\n$/, "")} + +Default: \`${schema.default}\`` : `Default: ${schema.default}`; + } + if ("allowEmptyValue" in schema && schema.allowEmptyValue && schema.default === "" || schema.default !== "") ; else { + delete schema.default; + } + } + } else if (prevDefaultSchemas.length) { + const foundDefault = searchForValueByPropAndPointer("default", currentLocation, prevDefaultSchemas); + if (isPrimitive$2(foundDefault) || foundDefault === null || Array.isArray(foundDefault) && hasSchemaType(schema, "array")) { + schema.default = foundDefault; + } + } + if (isSchema$4(schema, isPolymorphicAllOfChild) && "enum" in schema && Array.isArray(schema.enum)) { + schema.enum = Array.from(new Set(schema.enum)); + if (addEnumsToDescriptions) { + const enums = schema.enum.filter(Boolean).map((str) => `\`${str}\``).join(" "); + if (enums.length) { + if ("description" in schema) { + schema.description += ` + +${enums}`; + } else { + schema.description = enums; + } + } + } + } + if ("anyOf" in schema || "oneOf" in schema) { + if ("properties" in schema) { + delete schema.properties; + } + if ("items" in schema) { + delete schema.items; + } + } + for (let i = 0; i < UNSUPPORTED_SCHEMA_PROPS.length; i += 1) { + delete schema[UNSUPPORTED_SCHEMA_PROPS[i]]; + } + if (hideReadOnlyProperties && "readOnly" in schema && schema.readOnly === true) { + return {}; + } else if (hideWriteOnlyProperties && "writeOnly" in schema && schema.writeOnly === true) { + return {}; + } + return transformer(schema); +} + +// src/operation/get-parameters-as-json-schema.ts +var types = { + path: "Path Params", + query: "Query Params", + body: "Body Params", + cookie: "Cookie Params", + formData: "Form Data", + header: "Headers", + metadata: "Metadata" + // This a special type reserved for https://npm.im/api +}; +function getParametersAsJSONSchema(operation, api, opts) { + let hasCircularRefs = false; + let hasDiscriminatorMappingRefs = false; + function refLogger(ref, type) { + if (type === "ref") { + hasCircularRefs = true; + } else { + hasDiscriminatorMappingRefs = true; + } + } + function getDeprecated(schema, type) { + if (opts.retainDeprecatedProperties) { + return null; + } + if (!schema || !schema.properties) + return null; + const deprecatedBody = cloneObject(schema); + const requiredParams = schema.required || []; + const allDeprecatedProps = {}; + Object.keys(deprecatedBody.properties).forEach((key) => { + const deprecatedProp = deprecatedBody.properties[key]; + if (deprecatedProp.deprecated && !requiredParams.includes(key) && !deprecatedProp.readOnly) { + allDeprecatedProps[key] = deprecatedProp; + } + }); + deprecatedBody.properties = allDeprecatedProps; + const deprecatedSchema = toJSONSchema(deprecatedBody, { + globalDefaults: opts.globalDefaults, + hideReadOnlyProperties: opts.hideReadOnlyProperties, + hideWriteOnlyProperties: opts.hideWriteOnlyProperties, + prevExampleSchemas: [], + refLogger, + transformer: opts.transformer + }); + if (Object.keys(deprecatedSchema).length === 0 || Object.keys(deprecatedSchema.properties).length === 0) { + return null; + } + Object.keys(schema.properties).forEach((key) => { + if (schema.properties[key].deprecated && !requiredParams.includes(key)) { + delete schema.properties[key]; + } + }); + return { + type, + schema: isPrimitive$2(deprecatedSchema) ? deprecatedSchema : { + ...deprecatedSchema, + $schema: getSchemaVersionString(deprecatedSchema, api) + } + }; + } + function transformRequestBody() { + const requestBody = operation.getRequestBody(); + if (!requestBody || !Array.isArray(requestBody)) + return null; + const [mediaType, mediaTypeObject, description] = requestBody; + const type = mediaType === "application/x-www-form-urlencoded" ? "formData" : "body"; + if (!mediaTypeObject.schema || !Object.keys(mediaTypeObject.schema).length) { + return null; + } + const prevExampleSchemas = []; + if ("example" in mediaTypeObject) { + prevExampleSchemas.push({ example: mediaTypeObject.example }); + } else if ("examples" in mediaTypeObject) { + prevExampleSchemas.push({ + examples: Object.values(mediaTypeObject.examples).map((example) => example.value).filter((val) => val !== void 0) + }); + } + const requestSchema = cloneObject(mediaTypeObject.schema); + const cleanedSchema = toJSONSchema(requestSchema, { + globalDefaults: opts.globalDefaults, + hideReadOnlyProperties: opts.hideReadOnlyProperties, + hideWriteOnlyProperties: opts.hideWriteOnlyProperties, + prevExampleSchemas, + refLogger, + transformer: opts.transformer + }); + if (!Object.keys(cleanedSchema).length) { + return null; + } + return { + type, + label: types[type], + schema: isPrimitive$2(cleanedSchema) ? cleanedSchema : { + ...cleanedSchema, + $schema: getSchemaVersionString(cleanedSchema, api) + }, + deprecatedProps: getDeprecated(cleanedSchema, type), + ...description ? { description } : {} + }; + } + function transformComponents() { + if (!("components" in api)) { + return false; + } + const components2 = { + ...Object.keys(api.components).map((componentType) => ({ [componentType]: {} })).reduce((prev, next) => Object.assign(prev, next), {}) + }; + Object.keys(api.components).forEach((componentType) => { + if (typeof api.components[componentType] === "object" && !Array.isArray(api.components[componentType])) { + Object.keys(api.components[componentType]).forEach((schemaName) => { + const componentSchema = cloneObject(api.components[componentType][schemaName]); + components2[componentType][schemaName] = toJSONSchema(componentSchema, { + globalDefaults: opts.globalDefaults, + hideReadOnlyProperties: opts.hideReadOnlyProperties, + hideWriteOnlyProperties: opts.hideWriteOnlyProperties, + refLogger, + transformer: opts.transformer + }); + }); + } + }); + Object.keys(components2).forEach((componentType) => { + if (!Object.keys(components2[componentType]).length) { + delete components2[componentType]; + } + }); + return components2; + } + function transformParameters() { + const operationParams = operation.getParameters(); + const transformed = Object.keys(types).map((type) => { + const required = []; + const parameters = operationParams.filter((param) => param.in === type); + if (parameters.length === 0) { + return null; + } + const properties = parameters.reduce((prev, current) => { + let schema2 = {}; + if ("schema" in current) { + const currentSchema = current.schema ? cloneObject(current.schema) : {}; + if (current.example) { + currentSchema.example = current.example; + } else if (current.examples) { + currentSchema.examples = current.examples; + } + if (current.deprecated) + currentSchema.deprecated = current.deprecated; + const interimSchema = toJSONSchema(currentSchema, { + currentLocation: `/${current.name}`, + globalDefaults: opts.globalDefaults, + hideReadOnlyProperties: opts.hideReadOnlyProperties, + hideWriteOnlyProperties: opts.hideWriteOnlyProperties, + refLogger, + transformer: opts.transformer + }); + schema2 = isPrimitive$2(interimSchema) ? interimSchema : { + ...interimSchema, + // Note: this applies a `$schema` version to each field in the larger schema + // object. It's not really **correct** but it's what we have to do because + // there's a chance that the end user has indicated the schemas are different. + $schema: getSchemaVersionString(currentSchema, api) + }; + } else if ("content" in current && typeof current.content === "object") { + const contentKeys = Object.keys(current.content); + if (contentKeys.length) { + let contentType; + if (contentKeys.length === 1) { + contentType = contentKeys[0]; + } else { + const jsonLikeContentTypes = contentKeys.filter((k) => matches_mimetype_default.json(k)); + if (jsonLikeContentTypes.length) { + contentType = jsonLikeContentTypes[0]; + } else { + contentType = contentKeys[0]; + } + } + if (typeof current.content[contentType] === "object" && "schema" in current.content[contentType]) { + const currentSchema = current.content[contentType].schema ? cloneObject(current.content[contentType].schema) : {}; + if (current.example) { + currentSchema.example = current.example; + } else if (current.examples) { + currentSchema.examples = current.examples; + } + if (current.deprecated) + currentSchema.deprecated = current.deprecated; + const interimSchema = toJSONSchema(currentSchema, { + currentLocation: `/${current.name}`, + globalDefaults: opts.globalDefaults, + hideReadOnlyProperties: opts.hideReadOnlyProperties, + hideWriteOnlyProperties: opts.hideWriteOnlyProperties, + refLogger, + transformer: opts.transformer + }); + schema2 = isPrimitive$2(interimSchema) ? interimSchema : { + ...interimSchema, + // Note: this applies a `$schema` version to each field in the larger schema + // object. It's not really **correct** but it's what we have to do because + // there's a chance that the end user has indicated the schemas are different. + $schema: getSchemaVersionString(currentSchema, api) + }; + } + } + } + if (current.description) { + if (!isPrimitive$2(schema2)) { + schema2.description = current.description; + } + } + prev[current.name] = schema2; + if (current.required) { + required.push(current.name); + } + return prev; + }, {}); + const schema = { + type: "object", + properties, + required + }; + return { + type, + label: types[type], + schema, + deprecatedProps: getDeprecated(schema, type) + }; + }).filter(Boolean); + if (!opts.mergeIntoBodyAndMetadata) { + return transformed; + } else if (!transformed.length) { + return []; + } + const deprecatedProps = transformed.map((r) => r.deprecatedProps?.schema || null).filter(Boolean); + return [ + { + type: "metadata", + label: types.metadata, + schema: { + allOf: transformed.map((r) => r.schema) + }, + deprecatedProps: deprecatedProps.length ? { + type: "metadata", + schema: { + allOf: deprecatedProps + } + } : null + } + ]; + } + if (!operation.hasParameters() && !operation.hasRequestBody()) { + return null; + } + const typeKeys = Object.keys(types); + const jsonSchema = [transformRequestBody()].concat(...transformParameters()).filter(Boolean); + const shouldIncludeComponents = hasCircularRefs || hasDiscriminatorMappingRefs && opts.includeDiscriminatorMappingRefs; + const components = shouldIncludeComponents ? transformComponents() : false; + return jsonSchema.map((group) => { + if (components && shouldIncludeComponents) { + group.schema.components = components; + } + if (!group.deprecatedProps) + delete group.deprecatedProps; + return group; + }).sort((a, b) => { + return typeKeys.indexOf(a.type) - typeKeys.indexOf(b.type); + }); +} + +function findSchemaDefinition($ref, definition = {}) { + const origRef = $ref; + $ref = $ref.trim(); + if ($ref === "") { + return false; + } + if ($ref.startsWith("#")) { + $ref = decodeURIComponent($ref.substring(1)); + } else { + throw new Error(`Could not find a definition for ${origRef}.`); + } + const current = jsonpointer.get(definition, $ref); + if (current === void 0) { + throw new Error(`Could not find a definition for ${origRef}.`); + } + return current; +} + +// src/utils.ts +var supportedMethods = /* @__PURE__ */ new Set(["get", "put", "post", "delete", "options", "head", "patch", "trace"]); +var utils_default = { + findSchemaDefinition, + jsonSchemaTypes: types, + matchesMimeType: matches_mimetype_default +}; + +// eslint-disable-next-line no-empty-function +var noop$1 = function () {}; + +var _undefined = noop$1(); // Support ES3 engines + +var isValue$3 = function (val) { return val !== _undefined && val !== null; }; + +var isValue$2 = isValue$3; + +var forEach$2 = Array.prototype.forEach, create$1 = Object.create; + +var process$1 = function (src, obj) { + var key; + for (key in src) obj[key] = src[key]; +}; + +// eslint-disable-next-line no-unused-vars +var normalizeOptions = function (opts1 /*, …options*/) { + var result = create$1(null); + forEach$2.call(arguments, function (options) { + if (!isValue$2(options)) return; + process$1(Object(options), result); + }); + return result; +}; + +var isImplemented$7 = function () { + var sign = Math.sign; + if (typeof sign !== "function") return false; + return sign(10) === 1 && sign(-20) === -1; +}; + +var shim$5; +var hasRequiredShim$5; + +function requireShim$5 () { + if (hasRequiredShim$5) return shim$5; + hasRequiredShim$5 = 1; + + shim$5 = function (value) { + value = Number(value); + if (isNaN(value) || value === 0) return value; + return value > 0 ? 1 : -1; + }; + return shim$5; +} + +var sign$2 = isImplemented$7() ? Math.sign : requireShim$5(); + +var sign$1 = sign$2 + , abs = Math.abs + , floor = Math.floor; + +var toInteger$1 = function (value) { + if (isNaN(value)) return 0; + value = Number(value); + if (value === 0 || !isFinite(value)) return value; + return sign$1(value) * floor(abs(value)); +}; + +var toInteger = toInteger$1 + , max$1 = Math.max; + +var toPosInteger = function (value) { return max$1(0, toInteger(value)); }; + +var toPosInt = toPosInteger; + +var resolveLength$2 = function (optsLength, fnLength, isAsync) { + var length; + if (isNaN(optsLength)) { + length = fnLength; + if (!(length >= 0)) return 1; + if (isAsync && length) return length - 1; + return length; + } + if (optsLength === false) return false; + return toPosInt(optsLength); +}; + +var validCallable = function (fn) { + if (typeof fn !== "function") throw new TypeError(fn + " is not a function"); + return fn; +}; + +var validValue; +var hasRequiredValidValue; + +function requireValidValue () { + if (hasRequiredValidValue) return validValue; + hasRequiredValidValue = 1; + + var isValue = isValue$3; + + validValue = function (value) { + if (!isValue(value)) throw new TypeError("Cannot use null or undefined"); + return value; + }; + return validValue; +} + +var callable$3 = validCallable + , value = requireValidValue() + , bind = Function.prototype.bind + , call$1 = Function.prototype.call + , keys$2 = Object.keys + , objPropertyIsEnumerable = Object.prototype.propertyIsEnumerable; + +var _iterate = function (method, defVal) { + return function (obj, cb /*, thisArg, compareFn*/) { + var list, thisArg = arguments[2], compareFn = arguments[3]; + obj = Object(value(obj)); + callable$3(cb); + + list = keys$2(obj); + if (compareFn) { + list.sort(typeof compareFn === "function" ? bind.call(compareFn, obj) : undefined); + } + if (typeof method !== "function") method = list[method]; + return call$1.call(method, list, function (key, index) { + if (!objPropertyIsEnumerable.call(obj, key)) return defVal; + return call$1.call(cb, thisArg, obj[key], key, obj, index); + }); + }; +}; + +var forEach$1 = _iterate("forEach"); + +var registeredExtensions = {}; + +var custom = {exports: {}}; + +var isImplemented$6 = function () { + var assign = Object.assign, obj; + if (typeof assign !== "function") return false; + obj = { foo: "raz" }; + assign(obj, { bar: "dwa" }, { trzy: "trzy" }); + return obj.foo + obj.bar + obj.trzy === "razdwatrzy"; +}; + +var isImplemented$5; +var hasRequiredIsImplemented$5; + +function requireIsImplemented$5 () { + if (hasRequiredIsImplemented$5) return isImplemented$5; + hasRequiredIsImplemented$5 = 1; + + isImplemented$5 = function () { + try { + Object.keys("primitive"); + return true; + } catch (e) { + return false; + } + }; + return isImplemented$5; +} + +var shim$4; +var hasRequiredShim$4; + +function requireShim$4 () { + if (hasRequiredShim$4) return shim$4; + hasRequiredShim$4 = 1; + + var isValue = isValue$3; + + var keys = Object.keys; + + shim$4 = function (object) { return keys(isValue(object) ? Object(object) : object); }; + return shim$4; +} + +var keys$1; +var hasRequiredKeys; + +function requireKeys () { + if (hasRequiredKeys) return keys$1; + hasRequiredKeys = 1; + + keys$1 = requireIsImplemented$5()() ? Object.keys : requireShim$4(); + return keys$1; +} + +var shim$3; +var hasRequiredShim$3; + +function requireShim$3 () { + if (hasRequiredShim$3) return shim$3; + hasRequiredShim$3 = 1; + + var keys = requireKeys() + , value = requireValidValue() + , max = Math.max; + + shim$3 = function (dest, src /*, …srcn*/) { + var error, i, length = max(arguments.length, 2), assign; + dest = Object(value(dest)); + assign = function (key) { + try { + dest[key] = src[key]; + } catch (e) { + if (!error) error = e; + } + }; + for (i = 1; i < length; ++i) { + src = arguments[i]; + keys(src).forEach(assign); + } + if (error !== undefined) throw error; + return dest; + }; + return shim$3; +} + +var assign = isImplemented$6() ? Object.assign : requireShim$3(); + +var isValue$1 = isValue$3; + +var map$1 = { function: true, object: true }; + +var isObject$5 = function (value) { return (isValue$1(value) && map$1[typeof value]) || false; }; + +(function (module) { + + var assign$1 = assign + , isObject = isObject$5 + , isValue = isValue$3 + , captureStackTrace = Error.captureStackTrace; + + module.exports = function (message /*, code, ext*/) { + var err = new Error(message), code = arguments[1], ext = arguments[2]; + if (!isValue(ext)) { + if (isObject(code)) { + ext = code; + code = null; + } + } + if (isValue(ext)) assign$1(err, ext); + if (isValue(code)) err.code = code; + if (captureStackTrace) captureStackTrace(err, module.exports); + return err; + }; +} (custom)); + +var customExports = custom.exports; + +var _defineLength = {exports: {}}; + +var mixin; +var hasRequiredMixin; + +function requireMixin () { + if (hasRequiredMixin) return mixin; + hasRequiredMixin = 1; + + var value = requireValidValue() + , defineProperty = Object.defineProperty + , getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor + , getOwnPropertyNames = Object.getOwnPropertyNames + , getOwnPropertySymbols = Object.getOwnPropertySymbols; + + mixin = function (target, source) { + var error, sourceObject = Object(value(source)); + target = Object(value(target)); + getOwnPropertyNames(sourceObject).forEach(function (name) { + try { + defineProperty(target, name, getOwnPropertyDescriptor(source, name)); + } catch (e) { error = e; } + }); + if (typeof getOwnPropertySymbols === "function") { + getOwnPropertySymbols(sourceObject).forEach(function (symbol) { + try { + defineProperty(target, symbol, getOwnPropertyDescriptor(source, symbol)); + } catch (e) { error = e; } + }); + } + if (error !== undefined) throw error; + return target; + }; + return mixin; +} + +var hasRequired_defineLength; + +function require_defineLength () { + if (hasRequired_defineLength) return _defineLength.exports; + hasRequired_defineLength = 1; + + var toPosInt = toPosInteger; + + var test = function (arg1, arg2) { return arg2; }; + + var desc, defineProperty, generate, mixin; + + try { + Object.defineProperty(test, "length", { + configurable: true, + writable: false, + enumerable: false, + value: 1 + }); + } + catch (ignore) {} + + if (test.length === 1) { + // ES6 + desc = { configurable: true, writable: false, enumerable: false }; + defineProperty = Object.defineProperty; + _defineLength.exports = function (fn, length) { + length = toPosInt(length); + if (fn.length === length) return fn; + desc.value = length; + return defineProperty(fn, "length", desc); + }; + } else { + mixin = requireMixin(); + generate = (function () { + var cache = []; + return function (length) { + var args, i = 0; + if (cache[length]) return cache[length]; + args = []; + while (length--) args.push("a" + (++i).toString(36)); + // eslint-disable-next-line no-new-func + return new Function( + "fn", + "return function (" + args.join(", ") + ") { return fn.apply(this, arguments); };" + ); + }; + })(); + _defineLength.exports = function (src, length) { + var target; + length = toPosInt(length); + if (src.length === length) return src; + target = generate(length)(src); + try { mixin(target, src); } + catch (ignore) {} + return target; + }; + } + return _defineLength.exports; +} + +var d$1 = {exports: {}}; + +var is$4; +var hasRequiredIs$4; + +function requireIs$4 () { + if (hasRequiredIs$4) return is$4; + hasRequiredIs$4 = 1; + + // ES3 safe + var _undefined = void 0; + + is$4 = function (value) { return value !== _undefined && value !== null; }; + return is$4; +} + +var is$3; +var hasRequiredIs$3; + +function requireIs$3 () { + if (hasRequiredIs$3) return is$3; + hasRequiredIs$3 = 1; + + var isValue = requireIs$4(); + + // prettier-ignore + var possibleTypes = { "object": true, "function": true, "undefined": true /* document.all */ }; + + is$3 = function (value) { + if (!isValue(value)) return false; + return hasOwnProperty.call(possibleTypes, typeof value); + }; + return is$3; +} + +var is$2; +var hasRequiredIs$2; + +function requireIs$2 () { + if (hasRequiredIs$2) return is$2; + hasRequiredIs$2 = 1; + + var isObject = requireIs$3(); + + is$2 = function (value) { + if (!isObject(value)) return false; + try { + if (!value.constructor) return false; + return value.constructor.prototype === value; + } catch (error) { + return false; + } + }; + return is$2; +} + +var is$1; +var hasRequiredIs$1; + +function requireIs$1 () { + if (hasRequiredIs$1) return is$1; + hasRequiredIs$1 = 1; + + var isPrototype = requireIs$2(); + + is$1 = function (value) { + if (typeof value !== "function") return false; + + if (!hasOwnProperty.call(value, "length")) return false; + + try { + if (typeof value.length !== "number") return false; + if (typeof value.call !== "function") return false; + if (typeof value.apply !== "function") return false; + } catch (error) { + return false; + } + + return !isPrototype(value); + }; + return is$1; +} + +var is; +var hasRequiredIs; + +function requireIs () { + if (hasRequiredIs) return is; + hasRequiredIs = 1; + + var isFunction = requireIs$1(); + + var classRe = /^\s*class[\s{/}]/, functionToString = Function.prototype.toString; + + is = function (value) { + if (!isFunction(value)) return false; + if (classRe.test(functionToString.call(value))) return false; + return true; + }; + return is; +} + +var isImplemented$4; +var hasRequiredIsImplemented$4; + +function requireIsImplemented$4 () { + if (hasRequiredIsImplemented$4) return isImplemented$4; + hasRequiredIsImplemented$4 = 1; + + var str = "razdwatrzy"; + + isImplemented$4 = function () { + if (typeof str.contains !== "function") return false; + return str.contains("dwa") === true && str.contains("foo") === false; + }; + return isImplemented$4; +} + +var shim$2; +var hasRequiredShim$2; + +function requireShim$2 () { + if (hasRequiredShim$2) return shim$2; + hasRequiredShim$2 = 1; + + var indexOf = String.prototype.indexOf; + + shim$2 = function (searchString /*, position*/) { + return indexOf.call(this, searchString, arguments[1]) > -1; + }; + return shim$2; +} + +var contains; +var hasRequiredContains; + +function requireContains () { + if (hasRequiredContains) return contains; + hasRequiredContains = 1; + + contains = requireIsImplemented$4()() ? String.prototype.contains : requireShim$2(); + return contains; +} + +var hasRequiredD; + +function requireD () { + if (hasRequiredD) return d$1.exports; + hasRequiredD = 1; + + var isValue = requireIs$4() + , isPlainFunction = requireIs() + , assign$1 = assign + , normalizeOpts = normalizeOptions + , contains = requireContains(); + + var d = (d$1.exports = function (dscr, value/*, options*/) { + var c, e, w, options, desc; + if (arguments.length < 2 || typeof dscr !== "string") { + options = value; + value = dscr; + dscr = null; + } else { + options = arguments[2]; + } + if (isValue(dscr)) { + c = contains.call(dscr, "c"); + e = contains.call(dscr, "e"); + w = contains.call(dscr, "w"); + } else { + c = w = true; + e = false; + } + + desc = { value: value, configurable: c, enumerable: e, writable: w }; + return !options ? desc : assign$1(normalizeOpts(options), desc); + }); + + d.gs = function (dscr, get, set/*, options*/) { + var c, e, options, desc; + if (typeof dscr !== "string") { + options = set; + set = get; + get = dscr; + dscr = null; + } else { + options = arguments[3]; + } + if (!isValue(get)) { + get = undefined; + } else if (!isPlainFunction(get)) { + options = get; + get = set = undefined; + } else if (!isValue(set)) { + set = undefined; + } else if (!isPlainFunction(set)) { + options = set; + set = undefined; + } + if (isValue(dscr)) { + c = contains.call(dscr, "c"); + e = contains.call(dscr, "e"); + } else { + c = true; + e = false; + } + + desc = { get: get, set: set, configurable: c, enumerable: e }; + return !options ? desc : assign$1(normalizeOpts(options), desc); + }; + return d$1.exports; +} + +var eventEmitter = {exports: {}}; + +(function (module, exports) { + + var d = requireD() + , callable = validCallable + + , apply = Function.prototype.apply, call = Function.prototype.call + , create = Object.create, defineProperty = Object.defineProperty + , defineProperties = Object.defineProperties + , hasOwnProperty = Object.prototype.hasOwnProperty + , descriptor = { configurable: true, enumerable: false, writable: true } + + , on, once, off, emit, methods, descriptors, base; + + on = function (type, listener) { + var data; + + callable(listener); + + if (!hasOwnProperty.call(this, '__ee__')) { + data = descriptor.value = create(null); + defineProperty(this, '__ee__', descriptor); + descriptor.value = null; + } else { + data = this.__ee__; + } + if (!data[type]) data[type] = listener; + else if (typeof data[type] === 'object') data[type].push(listener); + else data[type] = [data[type], listener]; + + return this; + }; + + once = function (type, listener) { + var once, self; + + callable(listener); + self = this; + on.call(this, type, once = function () { + off.call(self, type, once); + apply.call(listener, this, arguments); + }); + + once.__eeOnceListener__ = listener; + return this; + }; + + off = function (type, listener) { + var data, listeners, candidate, i; + + callable(listener); + + if (!hasOwnProperty.call(this, '__ee__')) return this; + data = this.__ee__; + if (!data[type]) return this; + listeners = data[type]; + + if (typeof listeners === 'object') { + for (i = 0; (candidate = listeners[i]); ++i) { + if ((candidate === listener) || + (candidate.__eeOnceListener__ === listener)) { + if (listeners.length === 2) data[type] = listeners[i ? 0 : 1]; + else listeners.splice(i, 1); + } + } + } else { + if ((listeners === listener) || + (listeners.__eeOnceListener__ === listener)) { + delete data[type]; + } + } + + return this; + }; + + emit = function (type) { + var i, l, listener, listeners, args; + + if (!hasOwnProperty.call(this, '__ee__')) return; + listeners = this.__ee__[type]; + if (!listeners) return; + + if (typeof listeners === 'object') { + l = arguments.length; + args = new Array(l - 1); + for (i = 1; i < l; ++i) args[i - 1] = arguments[i]; + + listeners = listeners.slice(); + for (i = 0; (listener = listeners[i]); ++i) { + apply.call(listener, this, args); + } + } else { + switch (arguments.length) { + case 1: + call.call(listeners, this); + break; + case 2: + call.call(listeners, this, arguments[1]); + break; + case 3: + call.call(listeners, this, arguments[1], arguments[2]); + break; + default: + l = arguments.length; + args = new Array(l - 1); + for (i = 1; i < l; ++i) { + args[i - 1] = arguments[i]; + } + apply.call(listeners, this, args); + } + } + }; + + methods = { + on: on, + once: once, + off: off, + emit: emit + }; + + descriptors = { + on: d(on), + once: d(once), + off: d(off), + emit: d(emit) + }; + + base = defineProperties({}, descriptors); + + module.exports = exports = function (o) { + return (o == null) ? create(base) : defineProperties(Object(o), descriptors); + }; + exports.methods = methods; +} (eventEmitter, eventEmitter.exports)); + +var eventEmitterExports = eventEmitter.exports; + +var isImplemented$3; +var hasRequiredIsImplemented$3; + +function requireIsImplemented$3 () { + if (hasRequiredIsImplemented$3) return isImplemented$3; + hasRequiredIsImplemented$3 = 1; + + isImplemented$3 = function () { + var from = Array.from, arr, result; + if (typeof from !== "function") return false; + arr = ["raz", "dwa"]; + result = from(arr); + return Boolean(result && result !== arr && result[1] === "dwa"); + }; + return isImplemented$3; +} + +var isImplemented$2; +var hasRequiredIsImplemented$2; + +function requireIsImplemented$2 () { + if (hasRequiredIsImplemented$2) return isImplemented$2; + hasRequiredIsImplemented$2 = 1; + + isImplemented$2 = function () { + if (typeof globalThis !== "object") return false; + if (!globalThis) return false; + return globalThis.Array === Array; + }; + return isImplemented$2; +} + +var implementation; +var hasRequiredImplementation; + +function requireImplementation () { + if (hasRequiredImplementation) return implementation; + hasRequiredImplementation = 1; + var naiveFallback = function () { + if (typeof self === "object" && self) return self; + if (typeof window === "object" && window) return window; + throw new Error("Unable to resolve global `this`"); + }; + + implementation = (function () { + if (this) return this; + + // Unexpected strict mode (may happen if e.g. bundled into ESM module) + + // Thanks @mathiasbynens -> https://mathiasbynens.be/notes/globalthis + // In all ES5+ engines global object inherits from Object.prototype + // (if you approached one that doesn't please report) + try { + Object.defineProperty(Object.prototype, "__global__", { + get: function () { return this; }, + configurable: true + }); + } catch (error) { + // Unfortunate case of Object.prototype being sealed (via preventExtensions, seal or freeze) + return naiveFallback(); + } + try { + // Safari case (window.__global__ is resolved with global context, but __global__ does not) + if (!__global__) return naiveFallback(); + return __global__; + } finally { + delete Object.prototype.__global__; + } + })(); + return implementation; +} + +var globalThis_1; +var hasRequiredGlobalThis; + +function requireGlobalThis () { + if (hasRequiredGlobalThis) return globalThis_1; + hasRequiredGlobalThis = 1; + + globalThis_1 = requireIsImplemented$2()() ? globalThis : requireImplementation(); + return globalThis_1; +} + +var isImplemented$1; +var hasRequiredIsImplemented$1; + +function requireIsImplemented$1 () { + if (hasRequiredIsImplemented$1) return isImplemented$1; + hasRequiredIsImplemented$1 = 1; + + var global = requireGlobalThis() + , validTypes = { object: true, symbol: true }; + + isImplemented$1 = function () { + var Symbol = global.Symbol; + var symbol; + if (typeof Symbol !== "function") return false; + symbol = Symbol("test symbol"); + try { String(symbol); } + catch (e) { return false; } + + // Return 'true' also for polyfills + if (!validTypes[typeof Symbol.iterator]) return false; + if (!validTypes[typeof Symbol.toPrimitive]) return false; + if (!validTypes[typeof Symbol.toStringTag]) return false; + + return true; + }; + return isImplemented$1; +} + +var isSymbol; +var hasRequiredIsSymbol; + +function requireIsSymbol () { + if (hasRequiredIsSymbol) return isSymbol; + hasRequiredIsSymbol = 1; + + isSymbol = function (value) { + if (!value) return false; + if (typeof value === "symbol") return true; + if (!value.constructor) return false; + if (value.constructor.name !== "Symbol") return false; + return value[value.constructor.toStringTag] === "Symbol"; + }; + return isSymbol; +} + +var validateSymbol; +var hasRequiredValidateSymbol; + +function requireValidateSymbol () { + if (hasRequiredValidateSymbol) return validateSymbol; + hasRequiredValidateSymbol = 1; + + var isSymbol = requireIsSymbol(); + + validateSymbol = function (value) { + if (!isSymbol(value)) throw new TypeError(value + " is not a symbol"); + return value; + }; + return validateSymbol; +} + +var generateName; +var hasRequiredGenerateName; + +function requireGenerateName () { + if (hasRequiredGenerateName) return generateName; + hasRequiredGenerateName = 1; + + var d = requireD(); + + var create = Object.create, defineProperty = Object.defineProperty, objPrototype = Object.prototype; + + var created = create(null); + generateName = function (desc) { + var postfix = 0, name, ie11BugWorkaround; + while (created[desc + (postfix || "")]) ++postfix; + desc += postfix || ""; + created[desc] = true; + name = "@@" + desc; + defineProperty( + objPrototype, + name, + d.gs(null, function (value) { + // For IE11 issue see: + // https://connect.microsoft.com/IE/feedbackdetail/view/1928508/ + // ie11-broken-getters-on-dom-objects + // https://github.com/medikoo/es6-symbol/issues/12 + if (ie11BugWorkaround) return; + ie11BugWorkaround = true; + defineProperty(this, name, d(value)); + ie11BugWorkaround = false; + }) + ); + return name; + }; + return generateName; +} + +var standardSymbols; +var hasRequiredStandardSymbols; + +function requireStandardSymbols () { + if (hasRequiredStandardSymbols) return standardSymbols; + hasRequiredStandardSymbols = 1; + + var d = requireD() + , NativeSymbol = requireGlobalThis().Symbol; + + standardSymbols = function (SymbolPolyfill) { + return Object.defineProperties(SymbolPolyfill, { + // To ensure proper interoperability with other native functions (e.g. Array.from) + // fallback to eventual native implementation of given symbol + hasInstance: d( + "", (NativeSymbol && NativeSymbol.hasInstance) || SymbolPolyfill("hasInstance") + ), + isConcatSpreadable: d( + "", + (NativeSymbol && NativeSymbol.isConcatSpreadable) || + SymbolPolyfill("isConcatSpreadable") + ), + iterator: d("", (NativeSymbol && NativeSymbol.iterator) || SymbolPolyfill("iterator")), + match: d("", (NativeSymbol && NativeSymbol.match) || SymbolPolyfill("match")), + replace: d("", (NativeSymbol && NativeSymbol.replace) || SymbolPolyfill("replace")), + search: d("", (NativeSymbol && NativeSymbol.search) || SymbolPolyfill("search")), + species: d("", (NativeSymbol && NativeSymbol.species) || SymbolPolyfill("species")), + split: d("", (NativeSymbol && NativeSymbol.split) || SymbolPolyfill("split")), + toPrimitive: d( + "", (NativeSymbol && NativeSymbol.toPrimitive) || SymbolPolyfill("toPrimitive") + ), + toStringTag: d( + "", (NativeSymbol && NativeSymbol.toStringTag) || SymbolPolyfill("toStringTag") + ), + unscopables: d( + "", (NativeSymbol && NativeSymbol.unscopables) || SymbolPolyfill("unscopables") + ) + }); + }; + return standardSymbols; +} + +var symbolRegistry; +var hasRequiredSymbolRegistry; + +function requireSymbolRegistry () { + if (hasRequiredSymbolRegistry) return symbolRegistry; + hasRequiredSymbolRegistry = 1; + + var d = requireD() + , validateSymbol = requireValidateSymbol(); + + var registry = Object.create(null); + + symbolRegistry = function (SymbolPolyfill) { + return Object.defineProperties(SymbolPolyfill, { + for: d(function (key) { + if (registry[key]) return registry[key]; + return (registry[key] = SymbolPolyfill(String(key))); + }), + keyFor: d(function (symbol) { + var key; + validateSymbol(symbol); + for (key in registry) { + if (registry[key] === symbol) return key; + } + return undefined; + }) + }); + }; + return symbolRegistry; +} + +var polyfill; +var hasRequiredPolyfill; + +function requirePolyfill () { + if (hasRequiredPolyfill) return polyfill; + hasRequiredPolyfill = 1; + + var d = requireD() + , validateSymbol = requireValidateSymbol() + , NativeSymbol = requireGlobalThis().Symbol + , generateName = requireGenerateName() + , setupStandardSymbols = requireStandardSymbols() + , setupSymbolRegistry = requireSymbolRegistry(); + + var create = Object.create + , defineProperties = Object.defineProperties + , defineProperty = Object.defineProperty; + + var SymbolPolyfill, HiddenSymbol, isNativeSafe; + + if (typeof NativeSymbol === "function") { + try { + String(NativeSymbol()); + isNativeSafe = true; + } catch (ignore) {} + } else { + NativeSymbol = null; + } + + // Internal constructor (not one exposed) for creating Symbol instances. + // This one is used to ensure that `someSymbol instanceof Symbol` always return false + HiddenSymbol = function Symbol(description) { + if (this instanceof HiddenSymbol) throw new TypeError("Symbol is not a constructor"); + return SymbolPolyfill(description); + }; + + // Exposed `Symbol` constructor + // (returns instances of HiddenSymbol) + polyfill = SymbolPolyfill = function Symbol(description) { + var symbol; + if (this instanceof Symbol) throw new TypeError("Symbol is not a constructor"); + if (isNativeSafe) return NativeSymbol(description); + symbol = create(HiddenSymbol.prototype); + description = description === undefined ? "" : String(description); + return defineProperties(symbol, { + __description__: d("", description), + __name__: d("", generateName(description)) + }); + }; + + setupStandardSymbols(SymbolPolyfill); + setupSymbolRegistry(SymbolPolyfill); + + // Internal tweaks for real symbol producer + defineProperties(HiddenSymbol.prototype, { + constructor: d(SymbolPolyfill), + toString: d("", function () { return this.__name__; }) + }); + + // Proper implementation of methods exposed on Symbol.prototype + // They won't be accessible on produced symbol instances as they derive from HiddenSymbol.prototype + defineProperties(SymbolPolyfill.prototype, { + toString: d(function () { return "Symbol (" + validateSymbol(this).__description__ + ")"; }), + valueOf: d(function () { return validateSymbol(this); }) + }); + defineProperty( + SymbolPolyfill.prototype, + SymbolPolyfill.toPrimitive, + d("", function () { + var symbol = validateSymbol(this); + if (typeof symbol === "symbol") return symbol; + return symbol.toString(); + }) + ); + defineProperty(SymbolPolyfill.prototype, SymbolPolyfill.toStringTag, d("c", "Symbol")); + + // Proper implementaton of toPrimitive and toStringTag for returned symbol instances + defineProperty( + HiddenSymbol.prototype, SymbolPolyfill.toStringTag, + d("c", SymbolPolyfill.prototype[SymbolPolyfill.toStringTag]) + ); + + // Note: It's important to define `toPrimitive` as last one, as some implementations + // implement `toPrimitive` natively without implementing `toStringTag` (or other specified symbols) + // And that may invoke error in definition flow: + // See: https://github.com/medikoo/es6-symbol/issues/13#issuecomment-164146149 + defineProperty( + HiddenSymbol.prototype, SymbolPolyfill.toPrimitive, + d("c", SymbolPolyfill.prototype[SymbolPolyfill.toPrimitive]) + ); + return polyfill; +} + +var es6Symbol; +var hasRequiredEs6Symbol; + +function requireEs6Symbol () { + if (hasRequiredEs6Symbol) return es6Symbol; + hasRequiredEs6Symbol = 1; + + es6Symbol = requireIsImplemented$1()() + ? requireGlobalThis().Symbol + : requirePolyfill(); + return es6Symbol; +} + +var isArguments$1; +var hasRequiredIsArguments; + +function requireIsArguments () { + if (hasRequiredIsArguments) return isArguments$1; + hasRequiredIsArguments = 1; + + var objToString = Object.prototype.toString + , id = objToString.call((function () { return arguments; })()); + + isArguments$1 = function (value) { return objToString.call(value) === id; }; + return isArguments$1; +} + +var isFunction$3; +var hasRequiredIsFunction; + +function requireIsFunction () { + if (hasRequiredIsFunction) return isFunction$3; + hasRequiredIsFunction = 1; + + var objToString = Object.prototype.toString + , isFunctionStringTag = RegExp.prototype.test.bind(/^[object [A-Za-z0-9]*Function]$/); + + isFunction$3 = function (value) { + return typeof value === "function" && isFunctionStringTag(objToString.call(value)); + }; + return isFunction$3; +} + +var isString$2; +var hasRequiredIsString; + +function requireIsString () { + if (hasRequiredIsString) return isString$2; + hasRequiredIsString = 1; + + var objToString = Object.prototype.toString, id = objToString.call(""); + + isString$2 = function (value) { + return ( + typeof value === "string" || + (value && + typeof value === "object" && + (value instanceof String || objToString.call(value) === id)) || + false + ); + }; + return isString$2; +} + +var shim$1; +var hasRequiredShim$1; + +function requireShim$1 () { + if (hasRequiredShim$1) return shim$1; + hasRequiredShim$1 = 1; + + var iteratorSymbol = requireEs6Symbol().iterator + , isArguments = requireIsArguments() + , isFunction = requireIsFunction() + , toPosInt = toPosInteger + , callable = validCallable + , validValue = requireValidValue() + , isValue = isValue$3 + , isString = requireIsString() + , isArray = Array.isArray + , call = Function.prototype.call + , desc = { configurable: true, enumerable: true, writable: true, value: null } + , defineProperty = Object.defineProperty; + + // eslint-disable-next-line complexity, max-lines-per-function + shim$1 = function (arrayLike /*, mapFn, thisArg*/) { + var mapFn = arguments[1] + , thisArg = arguments[2] + , Context + , i + , j + , arr + , length + , code + , iterator + , result + , getIterator + , value; + + arrayLike = Object(validValue(arrayLike)); + + if (isValue(mapFn)) callable(mapFn); + if (!this || this === Array || !isFunction(this)) { + // Result: Plain array + if (!mapFn) { + if (isArguments(arrayLike)) { + // Source: Arguments + length = arrayLike.length; + if (length !== 1) return Array.apply(null, arrayLike); + arr = new Array(1); + arr[0] = arrayLike[0]; + return arr; + } + if (isArray(arrayLike)) { + // Source: Array + arr = new Array((length = arrayLike.length)); + for (i = 0; i < length; ++i) arr[i] = arrayLike[i]; + return arr; + } + } + arr = []; + } else { + // Result: Non plain array + Context = this; + } + + if (!isArray(arrayLike)) { + if ((getIterator = arrayLike[iteratorSymbol]) !== undefined) { + // Source: Iterator + iterator = callable(getIterator).call(arrayLike); + if (Context) arr = new Context(); + result = iterator.next(); + i = 0; + while (!result.done) { + value = mapFn ? call.call(mapFn, thisArg, result.value, i) : result.value; + if (Context) { + desc.value = value; + defineProperty(arr, i, desc); + } else { + arr[i] = value; + } + result = iterator.next(); + ++i; + } + length = i; + } else if (isString(arrayLike)) { + // Source: String + length = arrayLike.length; + if (Context) arr = new Context(); + for (i = 0, j = 0; i < length; ++i) { + value = arrayLike[i]; + if (i + 1 < length) { + code = value.charCodeAt(0); + // eslint-disable-next-line max-depth + if (code >= 0xd800 && code <= 0xdbff) value += arrayLike[++i]; + } + value = mapFn ? call.call(mapFn, thisArg, value, j) : value; + if (Context) { + desc.value = value; + defineProperty(arr, j, desc); + } else { + arr[j] = value; + } + ++j; + } + length = j; + } + } + if (length === undefined) { + // Source: array or array-like + length = toPosInt(arrayLike.length); + if (Context) arr = new Context(length); + for (i = 0; i < length; ++i) { + value = mapFn ? call.call(mapFn, thisArg, arrayLike[i], i) : arrayLike[i]; + if (Context) { + desc.value = value; + defineProperty(arr, i, desc); + } else { + arr[i] = value; + } + } + } + if (Context) { + desc.value = null; + arr.length = length; + } + return arr; + }; + return shim$1; +} + +var from$1; +var hasRequiredFrom; + +function requireFrom () { + if (hasRequiredFrom) return from$1; + hasRequiredFrom = 1; + + from$1 = requireIsImplemented$3()() ? Array.from : requireShim$1(); + return from$1; +} + +var from = requireFrom() + , isArray$2 = Array.isArray; + +var toArray$1 = function (arrayLike) { return isArray$2(arrayLike) ? arrayLike : from(arrayLike); }; + +var toArray = toArray$1 + , isValue = isValue$3 + , callable$2 = validCallable; + +var slice = Array.prototype.slice, resolveArgs; + +resolveArgs = function (args) { + return this.map(function (resolve, i) { + return resolve ? resolve(args[i]) : args[i]; + }).concat(slice.call(args, this.length)); +}; + +var resolveResolve$1 = function (resolvers) { + resolvers = toArray(resolvers); + resolvers.forEach(function (resolve) { + if (isValue(resolve)) callable$2(resolve); + }); + return resolveArgs.bind(resolvers); +}; + +var callable$1 = validCallable; + +var resolveNormalize$1 = function (userNormalizer) { + var normalizer; + if (typeof userNormalizer === "function") return { set: userNormalizer, get: userNormalizer }; + normalizer = { get: callable$1(userNormalizer.get) }; + if (userNormalizer.set !== undefined) { + normalizer.set = callable$1(userNormalizer.set); + if (userNormalizer.delete) normalizer.delete = callable$1(userNormalizer.delete); + if (userNormalizer.clear) normalizer.clear = callable$1(userNormalizer.clear); + return normalizer; + } + normalizer.set = normalizer.get; + return normalizer; +}; + +/* eslint no-eq-null: 0, eqeqeq: 0, no-unused-vars: 0 */ + +var customError = customExports + , defineLength = require_defineLength() + , d = requireD() + , ee = eventEmitterExports.methods + , resolveResolve = resolveResolve$1 + , resolveNormalize = resolveNormalize$1; + +var apply$1 = Function.prototype.apply + , call = Function.prototype.call + , create = Object.create + , defineProperties = Object.defineProperties + , on = ee.on + , emit = ee.emit; + +var configureMap = function (original, length, options) { + var cache = create(null) + , conf + , memLength + , get + , set + , del + , clear + , extDel + , extGet + , extHas + , normalizer + , getListeners + , setListeners + , deleteListeners + , memoized + , resolve; + if (length !== false) memLength = length; + else if (isNaN(original.length)) memLength = 1; + else memLength = original.length; + + if (options.normalizer) { + normalizer = resolveNormalize(options.normalizer); + get = normalizer.get; + set = normalizer.set; + del = normalizer.delete; + clear = normalizer.clear; + } + if (options.resolvers != null) resolve = resolveResolve(options.resolvers); + + if (get) { + memoized = defineLength(function (arg) { + var id, result, args = arguments; + if (resolve) args = resolve(args); + id = get(args); + if (id !== null) { + if (hasOwnProperty.call(cache, id)) { + if (getListeners) conf.emit("get", id, args, this); + return cache[id]; + } + } + if (args.length === 1) result = call.call(original, this, args[0]); + else result = apply$1.call(original, this, args); + if (id === null) { + id = get(args); + if (id !== null) throw customError("Circular invocation", "CIRCULAR_INVOCATION"); + id = set(args); + } else if (hasOwnProperty.call(cache, id)) { + throw customError("Circular invocation", "CIRCULAR_INVOCATION"); + } + cache[id] = result; + if (setListeners) conf.emit("set", id, null, result); + return result; + }, memLength); + } else if (length === 0) { + memoized = function () { + var result; + if (hasOwnProperty.call(cache, "data")) { + if (getListeners) conf.emit("get", "data", arguments, this); + return cache.data; + } + if (arguments.length) result = apply$1.call(original, this, arguments); + else result = call.call(original, this); + if (hasOwnProperty.call(cache, "data")) { + throw customError("Circular invocation", "CIRCULAR_INVOCATION"); + } + cache.data = result; + if (setListeners) conf.emit("set", "data", null, result); + return result; + }; + } else { + memoized = function (arg) { + var result, args = arguments, id; + if (resolve) args = resolve(arguments); + id = String(args[0]); + if (hasOwnProperty.call(cache, id)) { + if (getListeners) conf.emit("get", id, args, this); + return cache[id]; + } + if (args.length === 1) result = call.call(original, this, args[0]); + else result = apply$1.call(original, this, args); + if (hasOwnProperty.call(cache, id)) { + throw customError("Circular invocation", "CIRCULAR_INVOCATION"); + } + cache[id] = result; + if (setListeners) conf.emit("set", id, null, result); + return result; + }; + } + conf = { + original: original, + memoized: memoized, + profileName: options.profileName, + get: function (args) { + if (resolve) args = resolve(args); + if (get) return get(args); + return String(args[0]); + }, + has: function (id) { return hasOwnProperty.call(cache, id); }, + delete: function (id) { + var result; + if (!hasOwnProperty.call(cache, id)) return; + if (del) del(id); + result = cache[id]; + delete cache[id]; + if (deleteListeners) conf.emit("delete", id, result); + }, + clear: function () { + var oldCache = cache; + if (clear) clear(); + cache = create(null); + conf.emit("clear", oldCache); + }, + on: function (type, listener) { + if (type === "get") getListeners = true; + else if (type === "set") setListeners = true; + else if (type === "delete") deleteListeners = true; + return on.call(this, type, listener); + }, + emit: emit, + updateEnv: function () { original = conf.original; } + }; + if (get) { + extDel = defineLength(function (arg) { + var id, args = arguments; + if (resolve) args = resolve(args); + id = get(args); + if (id === null) return; + conf.delete(id); + }, memLength); + } else if (length === 0) { + extDel = function () { return conf.delete("data"); }; + } else { + extDel = function (arg) { + if (resolve) arg = resolve(arguments)[0]; + return conf.delete(arg); + }; + } + extGet = defineLength(function () { + var id, args = arguments; + if (length === 0) return cache.data; + if (resolve) args = resolve(args); + if (get) id = get(args); + else id = String(args[0]); + return cache[id]; + }); + extHas = defineLength(function () { + var id, args = arguments; + if (length === 0) return conf.has("data"); + if (resolve) args = resolve(args); + if (get) id = get(args); + else id = String(args[0]); + if (id === null) return false; + return conf.has(id); + }); + defineProperties(memoized, { + __memoized__: d(true), + delete: d(extDel), + clear: d(conf.clear), + _get: d(extGet), + _has: d(extHas) + }); + return conf; +}; + +var callable = validCallable + , forEach = forEach$1 + , extensions = registeredExtensions + , configure = configureMap + , resolveLength$1 = resolveLength$2; + +var plain$1 = function self(fn /*, options */) { + var options, length, conf; + + callable(fn); + options = Object(arguments[1]); + + if (options.async && options.promise) { + throw new Error("Options 'async' and 'promise' cannot be used together"); + } + + // Do not memoize already memoized function + if (hasOwnProperty.call(fn, "__memoized__") && !options.force) return fn; + + // Resolve length; + length = resolveLength$1(options.length, fn.length, options.async && extensions.async); + + // Configure cache map + conf = configure(fn, length, options); + + // Bind eventual extensions + forEach(extensions, function (extFn, name) { + if (options[name]) extFn(options[name], conf, options); + }); + + if (self.__profiler__) self.__profiler__(conf); + + conf.updateEnv(); + return conf.memoized; +}; + +var primitive$1; +var hasRequiredPrimitive; + +function requirePrimitive () { + if (hasRequiredPrimitive) return primitive$1; + hasRequiredPrimitive = 1; + + primitive$1 = function (args) { + var id, i, length = args.length; + if (!length) return "\u0002"; + id = String(args[i = 0]); + while (--length) id += "\u0001" + args[++i]; + return id; + }; + return primitive$1; +} + +var getPrimitiveFixed; +var hasRequiredGetPrimitiveFixed; + +function requireGetPrimitiveFixed () { + if (hasRequiredGetPrimitiveFixed) return getPrimitiveFixed; + hasRequiredGetPrimitiveFixed = 1; + + getPrimitiveFixed = function (length) { + if (!length) { + return function () { + return ""; + }; + } + return function (args) { + var id = String(args[0]), i = 0, currentLength = length; + while (--currentLength) { + id += "\u0001" + args[++i]; + } + return id; + }; + }; + return getPrimitiveFixed; +} + +var isImplemented; +var hasRequiredIsImplemented; + +function requireIsImplemented () { + if (hasRequiredIsImplemented) return isImplemented; + hasRequiredIsImplemented = 1; + + isImplemented = function () { + var numberIsNaN = Number.isNaN; + if (typeof numberIsNaN !== "function") return false; + return !numberIsNaN({}) && numberIsNaN(NaN) && !numberIsNaN(34); + }; + return isImplemented; +} + +var shim; +var hasRequiredShim; + +function requireShim () { + if (hasRequiredShim) return shim; + hasRequiredShim = 1; + + shim = function (value) { + // eslint-disable-next-line no-self-compare + return value !== value; + }; + return shim; +} + +var isNan; +var hasRequiredIsNan; + +function requireIsNan () { + if (hasRequiredIsNan) return isNan; + hasRequiredIsNan = 1; + + isNan = requireIsImplemented()() ? Number.isNaN : requireShim(); + return isNan; +} + +var eIndexOf; +var hasRequiredEIndexOf; + +function requireEIndexOf () { + if (hasRequiredEIndexOf) return eIndexOf; + hasRequiredEIndexOf = 1; + + var numberIsNaN = requireIsNan() + , toPosInt = toPosInteger + , value = requireValidValue() + , indexOf = Array.prototype.indexOf + , objHasOwnProperty = Object.prototype.hasOwnProperty + , abs = Math.abs + , floor = Math.floor; + + eIndexOf = function (searchElement /*, fromIndex*/) { + var i, length, fromIndex, val; + if (!numberIsNaN(searchElement)) return indexOf.apply(this, arguments); + + length = toPosInt(value(this).length); + fromIndex = arguments[1]; + if (isNaN(fromIndex)) fromIndex = 0; + else if (fromIndex >= 0) fromIndex = floor(fromIndex); + else fromIndex = toPosInt(this.length) - floor(abs(fromIndex)); + + for (i = fromIndex; i < length; ++i) { + if (objHasOwnProperty.call(this, i)) { + val = this[i]; + if (numberIsNaN(val)) return i; // Jslint: ignore + } + } + return -1; + }; + return eIndexOf; +} + +/* eslint max-statements: 0 */ + +var get; +var hasRequiredGet; + +function requireGet () { + if (hasRequiredGet) return get; + hasRequiredGet = 1; + + var indexOf = requireEIndexOf(); + + var create = Object.create; + + get = function () { + var lastId = 0, map = [], cache = create(null); + return { + get: function (args) { + var index = 0, set = map, i, length = args.length; + if (length === 0) return set[length] || null; + if ((set = set[length])) { + while (index < length - 1) { + i = indexOf.call(set[0], args[index]); + if (i === -1) return null; + set = set[1][i]; + ++index; + } + i = indexOf.call(set[0], args[index]); + if (i === -1) return null; + return set[1][i] || null; + } + return null; + }, + set: function (args) { + var index = 0, set = map, i, length = args.length; + if (length === 0) { + set[length] = ++lastId; + } else { + if (!set[length]) { + set[length] = [[], []]; + } + set = set[length]; + while (index < length - 1) { + i = indexOf.call(set[0], args[index]); + if (i === -1) { + i = set[0].push(args[index]) - 1; + set[1].push([[], []]); + } + set = set[1][i]; + ++index; + } + i = indexOf.call(set[0], args[index]); + if (i === -1) { + i = set[0].push(args[index]) - 1; + } + set[1][i] = ++lastId; + } + cache[lastId] = args; + return lastId; + }, + delete: function (id) { + var index = 0, set = map, i, args = cache[id], length = args.length, path = []; + if (length === 0) { + delete set[length]; + } else if ((set = set[length])) { + while (index < length - 1) { + i = indexOf.call(set[0], args[index]); + if (i === -1) { + return; + } + path.push(set, i); + set = set[1][i]; + ++index; + } + i = indexOf.call(set[0], args[index]); + if (i === -1) { + return; + } + id = set[1][i]; + set[0].splice(i, 1); + set[1].splice(i, 1); + while (!set[0].length && path.length) { + i = path.pop(); + set = path.pop(); + set[0].splice(i, 1); + set[1].splice(i, 1); + } + } + delete cache[id]; + }, + clear: function () { + map = []; + cache = create(null); + } + }; + }; + return get; +} + +var get1; +var hasRequiredGet1; + +function requireGet1 () { + if (hasRequiredGet1) return get1; + hasRequiredGet1 = 1; + + var indexOf = requireEIndexOf(); + + get1 = function () { + var lastId = 0, argsMap = [], cache = []; + return { + get: function (args) { + var index = indexOf.call(argsMap, args[0]); + return index === -1 ? null : cache[index]; + }, + set: function (args) { + argsMap.push(args[0]); + cache.push(++lastId); + return lastId; + }, + delete: function (id) { + var index = indexOf.call(cache, id); + if (index !== -1) { + argsMap.splice(index, 1); + cache.splice(index, 1); + } + }, + clear: function () { + argsMap = []; + cache = []; + } + }; + }; + return get1; +} + +var getFixed; +var hasRequiredGetFixed; + +function requireGetFixed () { + if (hasRequiredGetFixed) return getFixed; + hasRequiredGetFixed = 1; + + var indexOf = requireEIndexOf() + , create = Object.create; + + getFixed = function (length) { + var lastId = 0, map = [[], []], cache = create(null); + return { + get: function (args) { + var index = 0, set = map, i; + while (index < length - 1) { + i = indexOf.call(set[0], args[index]); + if (i === -1) return null; + set = set[1][i]; + ++index; + } + i = indexOf.call(set[0], args[index]); + if (i === -1) return null; + return set[1][i] || null; + }, + set: function (args) { + var index = 0, set = map, i; + while (index < length - 1) { + i = indexOf.call(set[0], args[index]); + if (i === -1) { + i = set[0].push(args[index]) - 1; + set[1].push([[], []]); + } + set = set[1][i]; + ++index; + } + i = indexOf.call(set[0], args[index]); + if (i === -1) { + i = set[0].push(args[index]) - 1; + } + set[1][i] = ++lastId; + cache[lastId] = args; + return lastId; + }, + delete: function (id) { + var index = 0, set = map, i, path = [], args = cache[id]; + while (index < length - 1) { + i = indexOf.call(set[0], args[index]); + if (i === -1) { + return; + } + path.push(set, i); + set = set[1][i]; + ++index; + } + i = indexOf.call(set[0], args[index]); + if (i === -1) { + return; + } + id = set[1][i]; + set[0].splice(i, 1); + set[1].splice(i, 1); + while (!set[0].length && path.length) { + i = path.pop(); + set = path.pop(); + set[0].splice(i, 1); + set[1].splice(i, 1); + } + delete cache[id]; + }, + clear: function () { + map = [[], []]; + cache = create(null); + } + }; + }; + return getFixed; +} + +var async = {}; + +var map; +var hasRequiredMap; + +function requireMap () { + if (hasRequiredMap) return map; + hasRequiredMap = 1; + + var callable = validCallable + , forEach = forEach$1 + , call = Function.prototype.call; + + map = function (obj, cb /*, thisArg*/) { + var result = {}, thisArg = arguments[2]; + callable(cb); + forEach(obj, function (value, key, targetObj, index) { + result[key] = call.call(cb, thisArg, value, key, targetObj, index); + }); + return result; + }; + return map; +} + +var nextTick; +var hasRequiredNextTick; + +function requireNextTick () { + if (hasRequiredNextTick) return nextTick; + hasRequiredNextTick = 1; + + var ensureCallable = function (fn) { + if (typeof fn !== 'function') throw new TypeError(fn + " is not a function"); + return fn; + }; + + var byObserver = function (Observer) { + var node = document.createTextNode(''), queue, currentQueue, i = 0; + new Observer(function () { + var callback; + if (!queue) { + if (!currentQueue) return; + queue = currentQueue; + } else if (currentQueue) { + queue = currentQueue.concat(queue); + } + currentQueue = queue; + queue = null; + if (typeof currentQueue === 'function') { + callback = currentQueue; + currentQueue = null; + callback(); + return; + } + node.data = (i = ++i % 2); // Invoke other batch, to handle leftover callbacks in case of crash + while (currentQueue) { + callback = currentQueue.shift(); + if (!currentQueue.length) currentQueue = null; + callback(); + } + }).observe(node, { characterData: true }); + return function (fn) { + ensureCallable(fn); + if (queue) { + if (typeof queue === 'function') queue = [queue, fn]; + else queue.push(fn); + return; + } + queue = fn; + node.data = (i = ++i % 2); + }; + }; + + nextTick = (function () { + // Node.js + if ((typeof process === 'object') && process && (typeof process.nextTick === 'function')) { + return process.nextTick; + } + + // queueMicrotask + if (typeof queueMicrotask === "function") { + return function (cb) { queueMicrotask(ensureCallable(cb)); }; + } + + // MutationObserver + if ((typeof document === 'object') && document) { + if (typeof MutationObserver === 'function') return byObserver(MutationObserver); + if (typeof WebKitMutationObserver === 'function') return byObserver(WebKitMutationObserver); + } + + // W3C Draft + // http://dvcs.w3.org/hg/webperf/raw-file/tip/specs/setImmediate/Overview.html + if (typeof setImmediate === 'function') { + return function (cb) { setImmediate(ensureCallable(cb)); }; + } + + // Wide available standard + if ((typeof setTimeout === 'function') || (typeof setTimeout === 'object')) { + return function (cb) { setTimeout(ensureCallable(cb), 0); }; + } + + return null; + }()); + return nextTick; +} + +/* eslint consistent-this: 0, no-shadow:0, no-eq-null: 0, eqeqeq: 0, no-unused-vars: 0 */ + +var hasRequiredAsync; + +function requireAsync () { + if (hasRequiredAsync) return async; + hasRequiredAsync = 1; + + var aFrom = requireFrom() + , objectMap = requireMap() + , mixin = requireMixin() + , defineLength = require_defineLength() + , nextTick = requireNextTick(); + + var slice = Array.prototype.slice, apply = Function.prototype.apply, create = Object.create; + + registeredExtensions.async = function (tbi, conf) { + var waiting = create(null) + , cache = create(null) + , base = conf.memoized + , original = conf.original + , currentCallback + , currentContext + , currentArgs; + + // Initial + conf.memoized = defineLength(function (arg) { + var args = arguments, last = args[args.length - 1]; + if (typeof last === "function") { + currentCallback = last; + args = slice.call(args, 0, -1); + } + return base.apply(currentContext = this, currentArgs = args); + }, base); + try { mixin(conf.memoized, base); } + catch (ignore) {} + + // From cache (sync) + conf.on("get", function (id) { + var cb, context, args; + if (!currentCallback) return; + + // Unresolved + if (waiting[id]) { + if (typeof waiting[id] === "function") waiting[id] = [waiting[id], currentCallback]; + else waiting[id].push(currentCallback); + currentCallback = null; + return; + } + + // Resolved, assure next tick invocation + cb = currentCallback; + context = currentContext; + args = currentArgs; + currentCallback = currentContext = currentArgs = null; + nextTick(function () { + var data; + if (hasOwnProperty.call(cache, id)) { + data = cache[id]; + conf.emit("getasync", id, args, context); + apply.call(cb, data.context, data.args); + } else { + // Purged in a meantime, we shouldn't rely on cached value, recall + currentCallback = cb; + currentContext = context; + currentArgs = args; + base.apply(context, args); + } + }); + }); + + // Not from cache + conf.original = function () { + var args, cb, origCb, result; + if (!currentCallback) return apply.call(original, this, arguments); + args = aFrom(arguments); + cb = function self(err) { + var cb, args, id = self.id; + if (id == null) { + // Shouldn't happen, means async callback was called sync way + nextTick(apply.bind(self, this, arguments)); + return undefined; + } + delete self.id; + cb = waiting[id]; + delete waiting[id]; + if (!cb) { + // Already processed, + // outcome of race condition: asyncFn(1, cb), asyncFn.clear(), asyncFn(1, cb) + return undefined; + } + args = aFrom(arguments); + if (conf.has(id)) { + if (err) { + conf.delete(id); + } else { + cache[id] = { context: this, args: args }; + conf.emit("setasync", id, typeof cb === "function" ? 1 : cb.length); + } + } + if (typeof cb === "function") { + result = apply.call(cb, this, args); + } else { + cb.forEach(function (cb) { result = apply.call(cb, this, args); }, this); + } + return result; + }; + origCb = currentCallback; + currentCallback = currentContext = currentArgs = null; + args.push(cb); + result = apply.call(original, this, args); + cb.cb = origCb; + currentCallback = cb; + return result; + }; + + // After not from cache call + conf.on("set", function (id) { + if (!currentCallback) { + conf.delete(id); + return; + } + if (waiting[id]) { + // Race condition: asyncFn(1, cb), asyncFn.clear(), asyncFn(1, cb) + if (typeof waiting[id] === "function") waiting[id] = [waiting[id], currentCallback.cb]; + else waiting[id].push(currentCallback.cb); + } else { + waiting[id] = currentCallback.cb; + } + delete currentCallback.cb; + currentCallback.id = id; + currentCallback = null; + }); + + // On delete + conf.on("delete", function (id) { + var result; + // If false, we don't have value yet, so we assume that intention is not + // to memoize this call. After value is obtained we don't cache it but + // gracefully pass to callback + if (hasOwnProperty.call(waiting, id)) return; + if (!cache[id]) return; + result = cache[id]; + delete cache[id]; + conf.emit("deleteasync", id, slice.call(result.args, 1)); + }); + + // On clear + conf.on("clear", function () { + var oldCache = cache; + cache = create(null); + conf.emit( + "clearasync", objectMap(oldCache, function (data) { return slice.call(data.args, 1); }) + ); + }); + }; + return async; +} + +var promise = {}; + +var primitiveSet; +var hasRequiredPrimitiveSet; + +function requirePrimitiveSet () { + if (hasRequiredPrimitiveSet) return primitiveSet; + hasRequiredPrimitiveSet = 1; + + var forEach = Array.prototype.forEach, create = Object.create; + + // eslint-disable-next-line no-unused-vars + primitiveSet = function (arg /*, …args*/) { + var set = create(null); + forEach.call(arguments, function (name) { set[name] = true; }); + return set; + }; + return primitiveSet; +} + +var isCallable; +var hasRequiredIsCallable; + +function requireIsCallable () { + if (hasRequiredIsCallable) return isCallable; + hasRequiredIsCallable = 1; + + isCallable = function (obj) { return typeof obj === "function"; }; + return isCallable; +} + +var validateStringifiable; +var hasRequiredValidateStringifiable; + +function requireValidateStringifiable () { + if (hasRequiredValidateStringifiable) return validateStringifiable; + hasRequiredValidateStringifiable = 1; + + var isCallable = requireIsCallable(); + + validateStringifiable = function (stringifiable) { + try { + if (stringifiable && isCallable(stringifiable.toString)) return stringifiable.toString(); + return String(stringifiable); + } catch (e) { + throw new TypeError("Passed argument cannot be stringifed"); + } + }; + return validateStringifiable; +} + +var validateStringifiableValue; +var hasRequiredValidateStringifiableValue; + +function requireValidateStringifiableValue () { + if (hasRequiredValidateStringifiableValue) return validateStringifiableValue; + hasRequiredValidateStringifiableValue = 1; + + var ensureValue = requireValidValue() + , stringifiable = requireValidateStringifiable(); + + validateStringifiableValue = function (value) { return stringifiable(ensureValue(value)); }; + return validateStringifiableValue; +} + +var safeToString; +var hasRequiredSafeToString; + +function requireSafeToString () { + if (hasRequiredSafeToString) return safeToString; + hasRequiredSafeToString = 1; + + var isCallable = requireIsCallable(); + + safeToString = function (value) { + try { + if (value && isCallable(value.toString)) return value.toString(); + return String(value); + } catch (e) { + return ""; + } + }; + return safeToString; +} + +var toShortStringRepresentation; +var hasRequiredToShortStringRepresentation; + +function requireToShortStringRepresentation () { + if (hasRequiredToShortStringRepresentation) return toShortStringRepresentation; + hasRequiredToShortStringRepresentation = 1; + + var safeToString = requireSafeToString(); + + var reNewLine = /[\n\r\u2028\u2029]/g; + + toShortStringRepresentation = function (value) { + var string = safeToString(value); + // Trim if too long + if (string.length > 100) string = string.slice(0, 99) + "…"; + // Replace eventual new lines + string = string.replace(reNewLine, function (char) { + return JSON.stringify(char).slice(1, -1); + }); + return string; + }; + return toShortStringRepresentation; +} + +var isPromise$2 = {exports: {}}; + +var hasRequiredIsPromise; + +function requireIsPromise () { + if (hasRequiredIsPromise) return isPromise$2.exports; + hasRequiredIsPromise = 1; + isPromise$2.exports = isPromise; + isPromise$2.exports.default = isPromise; + + function isPromise(obj) { + return !!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function'; + } + return isPromise$2.exports; +} + +/* eslint max-statements: 0 */ + +var hasRequiredPromise; + +function requirePromise () { + if (hasRequiredPromise) return promise; + hasRequiredPromise = 1; + + var objectMap = requireMap() + , primitiveSet = requirePrimitiveSet() + , ensureString = requireValidateStringifiableValue() + , toShortString = requireToShortStringRepresentation() + , isPromise = requireIsPromise() + , nextTick = requireNextTick(); + + var create = Object.create + , supportedModes = primitiveSet("then", "then:finally", "done", "done:finally"); + + registeredExtensions.promise = function (mode, conf) { + var waiting = create(null), cache = create(null), promises = create(null); + + if (mode === true) { + mode = null; + } else { + mode = ensureString(mode); + if (!supportedModes[mode]) { + throw new TypeError("'" + toShortString(mode) + "' is not valid promise mode"); + } + } + + // After not from cache call + conf.on("set", function (id, ignore, promise) { + var isFailed = false; + + if (!isPromise(promise)) { + // Non promise result + cache[id] = promise; + conf.emit("setasync", id, 1); + return; + } + waiting[id] = 1; + promises[id] = promise; + var onSuccess = function (result) { + var count = waiting[id]; + if (isFailed) { + throw new Error( + "Memoizee error: Detected unordered then|done & finally resolution, which " + + "in turn makes proper detection of success/failure impossible (when in " + + "'done:finally' mode)\n" + + "Consider to rely on 'then' or 'done' mode instead." + ); + } + if (!count) return; // Deleted from cache before resolved + delete waiting[id]; + cache[id] = result; + conf.emit("setasync", id, count); + }; + var onFailure = function () { + isFailed = true; + if (!waiting[id]) return; // Deleted from cache (or succeed in case of finally) + delete waiting[id]; + delete promises[id]; + conf.delete(id); + }; + + var resolvedMode = mode; + if (!resolvedMode) resolvedMode = "then"; + + if (resolvedMode === "then") { + var nextTickFailure = function () { nextTick(onFailure); }; + // Eventual finally needs to be attached to non rejected promise + // (so we not force propagation of unhandled rejection) + promise = promise.then(function (result) { + nextTick(onSuccess.bind(this, result)); + }, nextTickFailure); + // If `finally` is a function we attach to it to remove cancelled promises. + if (typeof promise.finally === "function") { + promise.finally(nextTickFailure); + } + } else if (resolvedMode === "done") { + // Not recommended, as it may mute any eventual "Unhandled error" events + if (typeof promise.done !== "function") { + throw new Error( + "Memoizee error: Retrieved promise does not implement 'done' " + + "in 'done' mode" + ); + } + promise.done(onSuccess, onFailure); + } else if (resolvedMode === "done:finally") { + // The only mode with no side effects assuming library does not throw unconditionally + // for rejected promises. + if (typeof promise.done !== "function") { + throw new Error( + "Memoizee error: Retrieved promise does not implement 'done' " + + "in 'done:finally' mode" + ); + } + if (typeof promise.finally !== "function") { + throw new Error( + "Memoizee error: Retrieved promise does not implement 'finally' " + + "in 'done:finally' mode" + ); + } + promise.done(onSuccess); + promise.finally(onFailure); + } + }); + + // From cache (sync) + conf.on("get", function (id, args, context) { + var promise; + if (waiting[id]) { + ++waiting[id]; // Still waiting + return; + } + promise = promises[id]; + var emit = function () { conf.emit("getasync", id, args, context); }; + if (isPromise(promise)) { + if (typeof promise.done === "function") promise.done(emit); + else { + promise.then(function () { nextTick(emit); }); + } + } else { + emit(); + } + }); + + // On delete + conf.on("delete", function (id) { + delete promises[id]; + if (waiting[id]) { + delete waiting[id]; + return; // Not yet resolved + } + if (!hasOwnProperty.call(cache, id)) return; + var result = cache[id]; + delete cache[id]; + conf.emit("deleteasync", id, [result]); + }); + + // On clear + conf.on("clear", function () { + var oldCache = cache; + cache = create(null); + waiting = create(null); + promises = create(null); + conf.emit("clearasync", objectMap(oldCache, function (data) { return [data]; })); + }); + }; + return promise; +} + +var dispose = {}; + +var hasRequiredDispose; + +function requireDispose () { + if (hasRequiredDispose) return dispose; + hasRequiredDispose = 1; + + var callable = validCallable + , forEach = forEach$1 + , extensions = registeredExtensions + + , apply = Function.prototype.apply; + + extensions.dispose = function (dispose, conf, options) { + var del; + callable(dispose); + if ((options.async && extensions.async) || (options.promise && extensions.promise)) { + conf.on("deleteasync", del = function (id, resultArray) { + apply.call(dispose, null, resultArray); + }); + conf.on("clearasync", function (cache) { + forEach(cache, function (result, id) { + del(id, result); + }); + }); + return; + } + conf.on("delete", del = function (id, result) { + dispose(result); + }); + conf.on("clear", function (cache) { + forEach(cache, function (result, id) { + del(id, result); + }); + }); + }; + return dispose; +} + +var maxAge = {}; + +var maxTimeout; +var hasRequiredMaxTimeout; + +function requireMaxTimeout () { + if (hasRequiredMaxTimeout) return maxTimeout; + hasRequiredMaxTimeout = 1; + + maxTimeout = 2147483647; + return maxTimeout; +} + +var validTimeout; +var hasRequiredValidTimeout; + +function requireValidTimeout () { + if (hasRequiredValidTimeout) return validTimeout; + hasRequiredValidTimeout = 1; + + var toPosInt = toPosInteger + , maxTimeout = requireMaxTimeout(); + + validTimeout = function (value) { + value = toPosInt(value); + if (value > maxTimeout) throw new TypeError(value + " exceeds maximum possible timeout"); + return value; + }; + return validTimeout; +} + +/* eslint consistent-this: 0 */ + +var hasRequiredMaxAge; + +function requireMaxAge () { + if (hasRequiredMaxAge) return maxAge; + hasRequiredMaxAge = 1; + + var aFrom = requireFrom() + , forEach = forEach$1 + , nextTick = requireNextTick() + , isPromise = requireIsPromise() + , timeout = requireValidTimeout() + , extensions = registeredExtensions; + + var noop = Function.prototype, max = Math.max, min = Math.min, create = Object.create; + + extensions.maxAge = function (maxAge, conf, options) { + var timeouts, postfix, preFetchAge, preFetchTimeouts; + + maxAge = timeout(maxAge); + if (!maxAge) return; + + timeouts = create(null); + postfix = + (options.async && extensions.async) || (options.promise && extensions.promise) + ? "async" + : ""; + conf.on("set" + postfix, function (id) { + timeouts[id] = setTimeout(function () { conf.delete(id); }, maxAge); + if (typeof timeouts[id].unref === "function") timeouts[id].unref(); + if (!preFetchTimeouts) return; + if (preFetchTimeouts[id]) { + if (preFetchTimeouts[id] !== "nextTick") clearTimeout(preFetchTimeouts[id]); + } + preFetchTimeouts[id] = setTimeout(function () { + delete preFetchTimeouts[id]; + }, preFetchAge); + if (typeof preFetchTimeouts[id].unref === "function") preFetchTimeouts[id].unref(); + }); + conf.on("delete" + postfix, function (id) { + clearTimeout(timeouts[id]); + delete timeouts[id]; + if (!preFetchTimeouts) return; + if (preFetchTimeouts[id] !== "nextTick") clearTimeout(preFetchTimeouts[id]); + delete preFetchTimeouts[id]; + }); + + if (options.preFetch) { + if (options.preFetch === true || isNaN(options.preFetch)) { + preFetchAge = 0.333; + } else { + preFetchAge = max(min(Number(options.preFetch), 1), 0); + } + if (preFetchAge) { + preFetchTimeouts = {}; + preFetchAge = (1 - preFetchAge) * maxAge; + conf.on("get" + postfix, function (id, args, context) { + if (!preFetchTimeouts[id]) { + preFetchTimeouts[id] = "nextTick"; + nextTick(function () { + var result; + if (preFetchTimeouts[id] !== "nextTick") return; + delete preFetchTimeouts[id]; + conf.delete(id); + if (options.async) { + args = aFrom(args); + args.push(noop); + } + result = conf.memoized.apply(context, args); + if (options.promise) { + // Supress eventual error warnings + if (isPromise(result)) { + if (typeof result.done === "function") result.done(noop, noop); + else result.then(noop, noop); + } + } + }); + } + }); + } + } + + conf.on("clear" + postfix, function () { + forEach(timeouts, function (id) { clearTimeout(id); }); + timeouts = {}; + if (preFetchTimeouts) { + forEach(preFetchTimeouts, function (id) { if (id !== "nextTick") clearTimeout(id); }); + preFetchTimeouts = {}; + } + }); + }; + return maxAge; +} + +var max = {}; + +var lruQueue; +var hasRequiredLruQueue; + +function requireLruQueue () { + if (hasRequiredLruQueue) return lruQueue; + hasRequiredLruQueue = 1; + + var toPosInt = toPosInteger + + , create = Object.create, hasOwnProperty = Object.prototype.hasOwnProperty; + + lruQueue = function (limit) { + var size = 0, base = 1, queue = create(null), map = create(null), index = 0, del; + limit = toPosInt(limit); + return { + hit: function (id) { + var oldIndex = map[id], nuIndex = ++index; + queue[nuIndex] = id; + map[id] = nuIndex; + if (!oldIndex) { + ++size; + if (size <= limit) return; + id = queue[base]; + del(id); + return id; + } + delete queue[oldIndex]; + if (base !== oldIndex) return; + while (!hasOwnProperty.call(queue, ++base)) continue; //jslint: skip + }, + delete: del = function (id) { + var oldIndex = map[id]; + if (!oldIndex) return; + delete queue[oldIndex]; + delete map[id]; + --size; + if (base !== oldIndex) return; + if (!size) { + index = 0; + base = 1; + return; + } + while (!hasOwnProperty.call(queue, ++base)) continue; //jslint: skip + }, + clear: function () { + size = 0; + base = 1; + queue = create(null); + map = create(null); + index = 0; + } + }; + }; + return lruQueue; +} + +var hasRequiredMax; + +function requireMax () { + if (hasRequiredMax) return max; + hasRequiredMax = 1; + + var toPosInteger$1 = toPosInteger + , lruQueue = requireLruQueue() + , extensions = registeredExtensions; + + extensions.max = function (max, conf, options) { + var postfix, queue, hit; + + max = toPosInteger$1(max); + if (!max) return; + + queue = lruQueue(max); + postfix = (options.async && extensions.async) || (options.promise && extensions.promise) + ? "async" : ""; + + conf.on("set" + postfix, hit = function (id) { + id = queue.hit(id); + if (id === undefined) return; + conf.delete(id); + }); + conf.on("get" + postfix, hit); + conf.on("delete" + postfix, queue.delete); + conf.on("clear" + postfix, queue.clear); + }; + return max; +} + +var refCounter = {}; + +var hasRequiredRefCounter; + +function requireRefCounter () { + if (hasRequiredRefCounter) return refCounter; + hasRequiredRefCounter = 1; + + var d = requireD() + , extensions = registeredExtensions + + , create = Object.create, defineProperties = Object.defineProperties; + + extensions.refCounter = function (ignore, conf, options) { + var cache, postfix; + + cache = create(null); + postfix = (options.async && extensions.async) || (options.promise && extensions.promise) + ? "async" : ""; + + conf.on("set" + postfix, function (id, length) { + cache[id] = length || 1; + }); + conf.on("get" + postfix, function (id) { + ++cache[id]; + }); + conf.on("delete" + postfix, function (id) { + delete cache[id]; + }); + conf.on("clear" + postfix, function () { + cache = {}; + }); + + defineProperties(conf.memoized, { + deleteRef: d(function () { + var id = conf.get(arguments); + if (id === null) return null; + if (!cache[id]) return null; + if (!--cache[id]) { + conf.delete(id); + return true; + } + return false; + }), + getRefCount: d(function () { + var id = conf.get(arguments); + if (id === null) return 0; + if (!cache[id]) return 0; + return cache[id]; + }) + }); + }; + return refCounter; +} + +var normalizeOpts = normalizeOptions + , resolveLength = resolveLength$2 + , plain = plain$1; + +var memoizee = function (fn/*, options*/) { + var options = normalizeOpts(arguments[1]), length; + + if (!options.normalizer) { + length = options.length = resolveLength(options.length, fn.length, options.async); + if (length !== 0) { + if (options.primitive) { + if (length === false) { + options.normalizer = requirePrimitive(); + } else if (length > 1) { + options.normalizer = requireGetPrimitiveFixed()(length); + } + } else if (length === false) options.normalizer = requireGet()(); + else if (length === 1) options.normalizer = requireGet1()(); + else options.normalizer = requireGetFixed()(length); + } + } + + // Assure extensions + if (options.async) requireAsync(); + if (options.promise) requirePromise(); + if (options.dispose) requireDispose(); + if (options.maxAge) requireMaxAge(); + if (options.max) requireMax(); + if (options.refCounter) requireRefCounter(); + + return plain(fn, options); +}; + +var memoize = /*@__PURE__*/getDefaultExportFromCjs(memoizee); + +// src/lib/dedupe-common-parameters.ts +function dedupeCommonParameters(parameters, commonParameters) { + return commonParameters.filter((param) => { + return !parameters.find((param2) => { + if (param.name && param2.name) { + return param.name === param2.name && param.in === param2.in; + } else if (isRef(param) && isRef(param2)) { + return param.$ref === param2.$ref; + } + return false; + }); + }); +} + +// src/samples/utils.ts +function usesPolymorphism(schema) { + if (schema.oneOf) { + return "oneOf"; + } else if (schema.anyOf) { + return "anyOf"; + } else if (schema.allOf) { + return "allOf"; + } + return false; +} +function objectify(thing) { + if (!isObject$6(thing)) { + return {}; + } + return thing; +} +function normalizeArray(arr) { + if (Array.isArray(arr)) { + return arr; + } + return [arr]; +} +function isFunc(thing) { + return typeof thing === "function"; +} +function deeplyStripKey(input, keyToStrip, predicate = (obj, key) => true) { + if (typeof input !== "object" || Array.isArray(input) || input === null || !keyToStrip) { + return input; + } + const obj = { ...input }; + Object.keys(obj).forEach((k) => { + if (k === keyToStrip && predicate(obj[k], k)) { + delete obj[k]; + return; + } + obj[k] = deeplyStripKey(obj[k], keyToStrip, predicate); + }); + return obj; +} + +// src/samples/index.ts +var sampleDefaults = (genericSample) => { + return (schema) => typeof schema.default === typeof genericSample ? schema.default : genericSample; +}; +var primitives = { + string: sampleDefaults("string"), + string_email: sampleDefaults("user@example.com"), + "string_date-time": sampleDefaults((/* @__PURE__ */ new Date()).toISOString()), + string_date: sampleDefaults((/* @__PURE__ */ new Date()).toISOString().substring(0, 10)), + "string_YYYY-MM-DD": sampleDefaults((/* @__PURE__ */ new Date()).toISOString().substring(0, 10)), + string_uuid: sampleDefaults("3fa85f64-5717-4562-b3fc-2c963f66afa6"), + string_hostname: sampleDefaults("example.com"), + string_ipv4: sampleDefaults("198.51.100.42"), + string_ipv6: sampleDefaults("2001:0db8:5b96:0000:0000:426f:8e17:642a"), + number: sampleDefaults(0), + number_float: sampleDefaults(0), + integer: sampleDefaults(0), + boolean: sampleDefaults(true) +}; +var primitive = (schema) => { + schema = objectify(schema); + const { format } = schema; + let { type } = schema; + if (type === "null") { + return null; + } else if (Array.isArray(type)) { + if (type.length === 1) { + type = type[0]; + } else { + if (type.includes("null")) { + type = type.filter((t) => t !== "null"); + } + type = type.shift(); + } + } + const fn = primitives[`${type}_${format}`] || primitives[type]; + if (isFunc(fn)) { + return fn(schema); + } + return `Unknown Type: ${schema.type}`; +}; +function sampleFromSchema(schema, opts = {}) { + const objectifySchema = objectify(schema); + let { type } = objectifySchema; + const hasPolymorphism = usesPolymorphism(objectifySchema); + if (hasPolymorphism === "allOf") { + try { + return sampleFromSchema( + mergeJSONSchemaAllOf(objectifySchema, { + resolvers: { + // Ignore any unrecognized OAS-specific keywords that might be present on the schema + // (like `xml`). + defaultResolver: mergeJSONSchemaAllOf.options.resolvers.title + } + }), + opts + ); + } catch (error) { + return void 0; + } + } else if (hasPolymorphism) { + const samples = objectifySchema[hasPolymorphism].map((s) => { + return sampleFromSchema(s, opts); + }); + if (samples.length === 1) { + return samples[0]; + } else if (samples.some((s) => s === null)) { + return samples.find((s) => s !== null); + } + return samples[0]; + } + const { example, additionalProperties, properties, items } = objectifySchema; + const { includeReadOnly, includeWriteOnly } = opts; + if (example !== void 0) { + return deeplyStripKey(example, "$$ref", (val) => { + return typeof val === "string" && val.indexOf("#") > -1; + }); + } + if (!type) { + if (properties || additionalProperties) { + type = "object"; + } else if (items) { + type = "array"; + } else { + return void 0; + } + } + if (type === "object" || Array.isArray(type) && type.includes("object")) { + const props = objectify(properties); + const obj = {}; + for (const name in props) { + if (props[name] && props[name].deprecated) { + continue; + } + if (props[name] && props[name].readOnly && !includeReadOnly) { + continue; + } + if (props[name] && props[name].writeOnly && !includeWriteOnly) { + continue; + } + obj[name] = sampleFromSchema(props[name], opts); + } + if (additionalProperties === true) { + obj.additionalProp = {}; + } else if (additionalProperties) { + const additionalProps = objectify(additionalProperties); + const additionalPropVal = sampleFromSchema(additionalProps, opts); + obj.additionalProp = additionalPropVal; + } + return obj; + } + if (type === "array" || Array.isArray(type) && type.includes("array")) { + if (typeof items === "undefined") { + return []; + } + if (Array.isArray(items.anyOf)) { + return items.anyOf.map((i) => sampleFromSchema(i, opts)); + } + if (Array.isArray(items.oneOf)) { + return items.oneOf.map((i) => sampleFromSchema(i, opts)); + } + return [sampleFromSchema(items, opts)]; + } + if (schema.enum) { + if (schema.default) { + return schema.default; + } + return normalizeArray(schema.enum)[0]; + } + if (type === "file") { + return void 0; + } + return primitive(schema); +} +var samples_default = memoize(sampleFromSchema); + +// src/lib/get-mediatype-examples.ts +function getMediaTypeExamples(mediaType, mediaTypeObject, opts = {}) { + if (mediaTypeObject.example) { + return [ + { + value: mediaTypeObject.example + } + ]; + } else if (mediaTypeObject.examples) { + const { examples } = mediaTypeObject; + const multipleExamples = Object.keys(examples).map((key) => { + let summary = key; + let description; + let example = examples[key]; + if (example !== null && typeof example === "object") { + if ("summary" in example) { + summary = example.summary; + } + if ("description" in example) { + description = example.description; + } + if ("value" in example) { + if (example.value !== null && typeof example.value === "object" && "$ref" in example.value) { + return false; + } + example = example.value; + } + } + const ret = { summary, title: key, value: example }; + if (description) { + ret.description = description; + } + return ret; + }).filter(Boolean); + if (multipleExamples.length) { + return multipleExamples; + } + } + if (mediaTypeObject.schema) { + if (!matches_mimetype_default.xml(mediaType)) { + return [ + { + value: samples_default(JSON.parse(JSON.stringify(mediaTypeObject.schema)), opts) + } + ]; + } + } + return []; +} + +// src/operation/get-response-examples.ts +function getResponseExamples(operation) { + return Object.keys(operation.responses || {}).map((status) => { + const response = operation.responses[status]; + let onlyHeaders = false; + if (isRef(response)) { + return false; + } + const mediaTypes = {}; + (response.content ? Object.keys(response.content) : []).forEach((mediaType) => { + if (!mediaType) + return; + const mediaTypeObject = response.content[mediaType]; + const examples = getMediaTypeExamples(mediaType, mediaTypeObject, { + includeReadOnly: true, + includeWriteOnly: false + }); + if (examples) { + mediaTypes[mediaType] = examples; + } + }); + if (response.headers && Object.keys(response.headers).length && !Object.keys(mediaTypes).length) { + mediaTypes["*/*"] = []; + onlyHeaders = true; + } + if (!Object.keys(mediaTypes).length) { + return false; + } + return { + status, + mediaTypes, + ...onlyHeaders ? { onlyHeaders } : {} + }; + }).filter(Boolean); +} + +// src/operation/get-callback-examples.ts +function getCallbackExamples(operation) { + const ret = []; + return ret.concat( + ...Object.keys(operation.callbacks || {}).map((identifier) => { + const callback = operation.callbacks[identifier]; + return [].concat( + ...Object.keys(callback).map((expression) => { + return Object.keys(callback[expression]).map((method) => { + const pathItem = callback[expression]; + const example = getResponseExamples(pathItem[method]); + if (example.length === 0) + return false; + return { + identifier, + expression, + method, + example + }; + }); + }) + ).filter(Boolean); + }) + ); +} + +// src/operation/get-requestbody-examples.ts +function getRequestBodyExamples(operation) { + const requestBody = operation.requestBody; + if (!requestBody || !requestBody.content) { + return []; + } + return Object.keys(requestBody.content || {}).map((mediaType) => { + const mediaTypeObject = requestBody.content[mediaType]; + const examples = getMediaTypeExamples(mediaType, mediaTypeObject, { + includeReadOnly: false, + includeWriteOnly: true + }); + if (!examples.length) { + return false; + } + return { + mediaType, + examples + }; + }).filter(Boolean); +} + +// src/operation/get-response-as-json-schema.ts +var isJSON = matches_mimetype_default.json; +function buildHeadersSchema(response, opts) { + const headers = response.headers; + const headersSchema = { + type: "object", + properties: {} + }; + Object.keys(headers).forEach((key) => { + if (headers[key] && headers[key].schema) { + const header = headers[key]; + headersSchema.properties[key] = toJSONSchema(header.schema, { + addEnumsToDescriptions: true, + transformer: opts.transformer + }); + if (header.description) { + headersSchema.properties[key].description = header.description; + } + } + }); + const headersWrapper = { + schema: headersSchema, + type: "object", + label: "Headers" + }; + if (response.description && headersWrapper.schema) { + headersWrapper.description = response.description; + } + return headersWrapper; +} +function getResponseAsJSONSchema(operation, api, statusCode, opts) { + const response = operation.getResponseByStatusCode(statusCode); + const jsonSchema = []; + if (!response) { + return null; + } + let hasCircularRefs = false; + let hasDiscriminatorMappingRefs = false; + function refLogger(ref, type) { + if (type === "ref") { + hasCircularRefs = true; + } else { + hasDiscriminatorMappingRefs = true; + } + } + function getPreferredSchema(content) { + if (!content) { + return null; + } + const contentTypes = Object.keys(content); + if (!contentTypes.length) { + return null; + } + for (let i = 0; i < contentTypes.length; i++) { + if (isJSON(contentTypes[i])) { + return toJSONSchema(cloneObject(content[contentTypes[i]].schema), { + addEnumsToDescriptions: true, + refLogger, + transformer: opts.transformer + }); + } + } + const contentType = contentTypes.shift(); + return toJSONSchema(cloneObject(content[contentType].schema), { + addEnumsToDescriptions: true, + refLogger, + transformer: opts.transformer + }); + } + const foundSchema = getPreferredSchema(response.content); + if (foundSchema) { + const schema = cloneObject(foundSchema); + const schemaWrapper = { + // If there's no `type` then the root schema is a circular `$ref` that we likely won't be + // able to render so instead of generating a JSON Schema with an `undefined` type we should + // default to `string` so there's at least *something* the end-user can interact with. + type: foundSchema.type || "string", + schema: isPrimitive$2(schema) ? schema : { + ...schema, + $schema: getSchemaVersionString(schema, api) + }, + label: "Response body" + }; + if (response.description && schemaWrapper.schema) { + schemaWrapper.description = response.description; + } + if (api.components && schemaWrapper.schema) { + if (hasCircularRefs || hasDiscriminatorMappingRefs && opts.includeDiscriminatorMappingRefs) { + schemaWrapper.schema.components = api.components; + } + } + jsonSchema.push(schemaWrapper); + } + if (response.headers) { + jsonSchema.push(buildHeadersSchema(response, opts)); + } + return jsonSchema.length ? jsonSchema : null; +} + +// src/operation.ts +var Operation = class { + constructor(api, path, method, operation) { + this.schema = operation; + this.api = api; + this.path = path; + this.method = method; + this.contentType = void 0; + this.requestBodyExamples = void 0; + this.responseExamples = void 0; + this.callbackExamples = void 0; + } + getSummary() { + if (this.schema?.summary && typeof this.schema.summary === "string") { + return this.schema.summary; + } else if (this.api.paths[this.path].summary && typeof this.api.paths[this.path].summary === "string") { + return this.api.paths[this.path].summary; + } + return void 0; + } + getDescription() { + if (this.schema?.description && typeof this.schema.description === "string") { + return this.schema.description; + } else if (this.api.paths[this.path].description && typeof this.api.paths[this.path].description === "string") { + return this.api.paths[this.path].description; + } + return void 0; + } + getContentType() { + if (this.contentType) { + return this.contentType; + } + let types = []; + if (this.schema.requestBody) { + if ("$ref" in this.schema.requestBody) { + this.schema.requestBody = findSchemaDefinition(this.schema.requestBody.$ref, this.api); + } + if ("content" in this.schema.requestBody) { + types = Object.keys(this.schema.requestBody.content); + } + } + this.contentType = "application/json"; + if (types && types.length) { + this.contentType = types[0]; + } + types.forEach((t) => { + if (matches_mimetype_default.json(t)) { + this.contentType = t; + } + }); + return this.contentType; + } + isFormUrlEncoded() { + return matches_mimetype_default.formUrlEncoded(this.getContentType()); + } + isMultipart() { + return matches_mimetype_default.multipart(this.getContentType()); + } + isJson() { + return matches_mimetype_default.json(this.getContentType()); + } + isXml() { + return matches_mimetype_default.xml(this.getContentType()); + } + /** + * Returns an array of all security requirements associated wtih this operation. If none are + * defined at the operation level, the securities for the entire API definition are returned + * (with an empty array as a final fallback). + * + */ + getSecurity() { + if (!this.api?.components?.securitySchemes || !Object.keys(this.api.components.securitySchemes).length) { + return []; + } + return this.schema.security || this.api.security || []; + } + /** + * Retrieve a collection of grouped security schemes. The inner array determines AND-grouped + * security schemes, the outer array determines OR-groups. + * + * @see {@link https://swagger.io/docs/specification/authentication/#multiple} + * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#security-requirement-object} + * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#securityRequirementObject} + * @param filterInvalid Optional flag that, when set to `true`, filters out invalid/nonexistent + * security schemes, rather than returning `false`. + */ + getSecurityWithTypes(filterInvalid = false) { + const securityRequirements = this.getSecurity(); + return securityRequirements.map((requirement) => { + let keys; + try { + keys = Object.keys(requirement); + } catch (e) { + return false; + } + const keysWithTypes = keys.map((key) => { + let security; + try { + security = this.api.components.securitySchemes[key]; + } catch (e) { + return false; + } + if (!security) + return false; + let type = null; + if (security.type === "http") { + if (security.scheme === "basic") + type = "Basic"; + else if (security.scheme === "bearer") + type = "Bearer"; + else + type = security.type; + } else if (security.type === "oauth2") { + type = "OAuth2"; + } else if (security.type === "apiKey") { + if (security.in === "query") + type = "Query"; + else if (security.in === "header") + type = "Header"; + else if (security.in === "cookie") + type = "Cookie"; + else + type = security.type; + } else { + return false; + } + return { + type, + security: { + ...security, + _key: key + } + }; + }); + if (filterInvalid) + return keysWithTypes.filter((key) => key !== false); + return keysWithTypes; + }); + } + /** + * Retrieve an object where the keys are unique scheme types, and the values are arrays + * containing each security scheme of that type. + * + */ + prepareSecurity() { + const securitiesWithTypes = this.getSecurityWithTypes(); + return securitiesWithTypes.reduce( + (prev, securities) => { + if (!securities) + return prev; + securities.forEach((security) => { + if (!security) + return; + if (!prev[security.type]) + prev[security.type] = []; + const exists = prev[security.type].findIndex((sec) => sec._key === security.security._key); + if (exists < 0) { + prev[security.type].push(security.security); + } + }); + return prev; + }, + {} + ); + } + getHeaders() { + this.headers = { + request: [], + response: [] + }; + const security = this.prepareSecurity(); + if (security.Header) { + this.headers.request = security.Header.map((h) => { + return h.name; + }); + } + if (security.Bearer || security.Basic || security.OAuth2) { + this.headers.request.push("Authorization"); + } + if (security.Cookie) { + this.headers.request.push("Cookie"); + } + if (this.schema.parameters) { + this.headers.request = this.headers.request.concat( + // Remove the reference object because we will have already dereferenced. + this.schema.parameters.map((p) => { + if (p.in && p.in === "header") + return p.name; + return void 0; + }).filter((p) => p) + ); + } + if (this.schema.responses) { + this.headers.response = Object.keys(this.schema.responses).filter((r) => this.schema.responses[r].headers).map( + (r) => ( + // Remove the reference object because we will have already dereferenced. + Object.keys(this.schema.responses[r].headers) + ) + ).reduce((a, b) => a.concat(b), []); + } + if (!this.headers.request.includes("Content-Type") && this.schema.requestBody) { + if (this.schema.requestBody.content && Object.keys(this.schema.requestBody.content)) { + this.headers.request.push("Content-Type"); + } + } + if (this.schema.responses) { + if (Object.keys(this.schema.responses).some( + (response) => !!this.schema.responses[response].content + )) { + if (!this.headers.request.includes("Accept")) + this.headers.request.push("Accept"); + if (!this.headers.response.includes("Content-Type")) + this.headers.response.push("Content-Type"); + } + } + return this.headers; + } + /** + * Determine if the operation has an operation present in its schema. Note that if one is present + * in the schema but is an empty string then this will return false. + * + */ + hasOperationId() { + return Boolean("operationId" in this.schema && this.schema.operationId.length); + } + /** + * Get an `operationId` for this operation. If one is not present (it's not required by the spec!) + * a hash of the path and method will be returned instead. + * + */ + getOperationId(opts) { + function sanitize(id) { + return id.replace(opts?.camelCase ? /[^a-zA-Z0-9_]/g : /[^a-zA-Z0-9]/g, "-").replace(/--+/g, "-").replace(/^-|-$/g, ""); + } + let operationId; + if (this.hasOperationId()) { + operationId = this.schema.operationId; + } else { + operationId = sanitize(this.path).toLowerCase(); + } + const method = this.method.toLowerCase(); + if (opts?.camelCase) { + operationId = operationId.replace(/[^a-zA-Z0-9_]+(.)/g, (_, chr) => chr.toUpperCase()); + if (this.hasOperationId()) { + operationId = sanitize(operationId); + } + operationId = operationId.replace(/^[0-9]/g, (match) => `_${match}`); + operationId = operationId.charAt(0).toLowerCase() + operationId.slice(1); + if (operationId.startsWith(method)) { + return operationId; + } + if (this.hasOperationId()) { + return operationId; + } + operationId = operationId.charAt(0).toUpperCase() + operationId.slice(1); + return `${method}${operationId}`; + } else if (this.hasOperationId()) { + return operationId; + } + return `${method}_${operationId}`; + } + /** + * Return an array of all tags, and their metadata, that exist on this operation. + * + */ + getTags() { + if (!("tags" in this.schema)) { + return []; + } + const oasTagMap = /* @__PURE__ */ new Map(); + if ("tags" in this.api) { + this.api.tags.forEach((tag) => { + oasTagMap.set(tag.name, tag); + }); + } + const oasTags = Object.fromEntries(oasTagMap); + const tags = []; + if (Array.isArray(this.schema.tags)) { + this.schema.tags.forEach((tag) => { + if (tag in oasTags) { + tags.push(oasTags[tag]); + } else { + tags.push({ + name: tag + }); + } + }); + } + return tags; + } + /** + * Return is the operation is flagged as `deprecated` or not. + * + */ + isDeprecated() { + return "deprecated" in this.schema ? this.schema.deprecated : false; + } + /** + * Determine if the operation has any (non-request body) parameters. + * + */ + hasParameters() { + return !!this.getParameters().length; + } + /** + * Return the parameters (non-request body) on the operation. + * + */ + getParameters() { + let parameters = this.schema?.parameters || []; + const commonParams = this.api?.paths?.[this.path]?.parameters || []; + if (commonParams.length) { + parameters = parameters.concat(dedupeCommonParameters(parameters, commonParams) || []); + } + return parameters; + } + /** + * Determine if this operation has any required parameters. + * + */ + hasRequiredParameters() { + return this.getParameters().some((param) => "required" in param && param.required); + } + /** + * Convert the operation into an array of JSON Schema schemas for each available type of + * parameter available on the operation. + * + */ + getParametersAsJSONSchema(opts = {}) { + return getParametersAsJSONSchema(this, this.api, { + includeDiscriminatorMappingRefs: true, + transformer: (s) => s, + ...opts + }); + } + /** + * Get a single response for this status code, formatted as JSON schema. + * + * @param statusCode Status code to pull a JSON Schema response for. + */ + getResponseAsJSONSchema(statusCode, opts = {}) { + return getResponseAsJSONSchema(this, this.api, statusCode, { + includeDiscriminatorMappingRefs: true, + transformer: (s) => s, + ...opts + }); + } + /** + * Get an array of all valid response status codes for this operation. + * + */ + getResponseStatusCodes() { + return this.schema.responses ? Object.keys(this.schema.responses) : []; + } + /** + * Determine if the operation has any request bodies. + * + */ + hasRequestBody() { + return !!this.schema.requestBody; + } + /** + * Retrieve the list of all available media types that the operations request body can accept. + * + * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#mediaTypeObject} + * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#mediaTypeObject} + */ + getRequestBodyMediaTypes() { + if (!this.hasRequestBody()) { + return []; + } + const requestBody = this.schema.requestBody; + if (isRef(requestBody)) { + return []; + } + return Object.keys(requestBody.content); + } + /** + * Determine if this operation has a required request body. + * + */ + hasRequiredRequestBody() { + if (!this.hasRequestBody()) { + return false; + } + const requestBody = this.schema.requestBody; + if (isRef(requestBody)) { + return false; + } + if (requestBody.required) { + return true; + } + return !!this.getParametersAsJSONSchema().filter((js) => ["body", "formData"].includes(js.type)).find((js) => js.schema && Array.isArray(js.schema.required) && js.schema.required.length); + } + /** + * Retrieve a specific request body content schema off this operation. + * + * If no media type is supplied this will return either the first available JSON-like request + * body, or the first available if there are no JSON-like media types present. When this return + * comes back it's in the form of an array with the first key being the selected media type, + * followed by the media type object in question. + * + * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#mediaTypeObject} + * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#mediaTypeObject} + * @param mediaType Specific request body media type to retrieve if present. + */ + getRequestBody(mediaType) { + if (!this.hasRequestBody()) { + return false; + } + const requestBody = this.schema.requestBody; + if (isRef(requestBody)) { + return false; + } + if (mediaType) { + if (!(mediaType in requestBody.content)) { + return false; + } + return requestBody.content[mediaType]; + } + let availableMediaType; + const mediaTypes = this.getRequestBodyMediaTypes(); + mediaTypes.forEach((mt) => { + if (!availableMediaType && matches_mimetype_default.json(mt)) { + availableMediaType = mt; + } + }); + if (!availableMediaType) { + mediaTypes.forEach((mt) => { + if (!availableMediaType) { + availableMediaType = mt; + } + }); + } + if (availableMediaType) { + return [ + availableMediaType, + requestBody.content[availableMediaType], + ...requestBody.description ? [requestBody.description] : [] + ]; + } + return false; + } + /** + * Retrieve an array of request body examples that this operation has. + * + */ + getRequestBodyExamples() { + if (this.requestBodyExamples) { + return this.requestBodyExamples; + } + this.requestBodyExamples = getRequestBodyExamples(this.schema); + return this.requestBodyExamples; + } + /** + * Return a specific response out of the operation by a given HTTP status code. + * + * @param statusCode Status code to pull a response object for. + */ + getResponseByStatusCode(statusCode) { + if (!this.schema.responses) { + return false; + } + if (typeof this.schema.responses[statusCode] === "undefined") { + return false; + } + const response = this.schema.responses[statusCode]; + if (isRef(response)) { + return false; + } + return response; + } + /** + * Retrieve an array of response examples that this operation has. + * + */ + getResponseExamples() { + if (this.responseExamples) { + return this.responseExamples; + } + this.responseExamples = getResponseExamples(this.schema); + return this.responseExamples; + } + /** + * Determine if the operation has callbacks. + * + */ + hasCallbacks() { + return !!this.schema.callbacks; + } + /** + * Retrieve a specific callback. + * + * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#callbackObject} + * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#callbackObject} + * @param identifier Callback identifier to look for. + * @param expression Callback expression to look for. + * @param method HTTP Method on the callback to look for. + */ + getCallback(identifier, expression, method) { + if (!this.schema.callbacks) + return false; + const callback = this.schema.callbacks[identifier] ? this.schema.callbacks[identifier][expression] : false; + if (!callback || !callback[method]) + return false; + return new Callback(this.api, expression, method, callback[method], identifier, callback); + } + /** + * Retrieve an array of operations created from each callback. + * + */ + getCallbacks() { + const callbackOperations = []; + if (!this.hasCallbacks()) + return false; + Object.keys(this.schema.callbacks).forEach((callback) => { + Object.keys(this.schema.callbacks[callback]).forEach((expression) => { + const cb = this.schema.callbacks[callback]; + if (!isRef(cb)) { + const exp = cb[expression]; + if (!isRef(exp)) { + Object.keys(exp).forEach((method) => { + if (!supportedMethods.has(method)) + return; + callbackOperations.push(this.getCallback(callback, expression, method)); + }); + } + } + }); + }); + return callbackOperations; + } + /** + * Retrieve an array of callback examples that this operation has. + * + */ + getCallbackExamples() { + if (this.callbackExamples) { + return this.callbackExamples; + } + this.callbackExamples = getCallbackExamples(this.schema); + return this.callbackExamples; + } + /** + * Determine if a given a custom specification extension exists within the operation. + * + * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions} + * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specificationExtensions} + * @param extension Specification extension to lookup. + */ + hasExtension(extension) { + return Boolean(this.schema && extension in this.schema); + } + /** + * Retrieve a custom specification extension off of the operation. + * + * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions} + * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specificationExtensions} + * @param extension Specification extension to lookup. + */ + getExtension(extension) { + return this.schema?.[extension]; + } +}; +var Callback = class extends Operation { + constructor(oas, path, method, operation, identifier, parentPathItem) { + super(oas, path, method, operation); + this.identifier = identifier; + this.parentSchema = parentPathItem; + } + /** + * Return the primary identifier for this callback. + * + * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#callback-object} + * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#callbackObject} + */ + getIdentifier() { + return this.identifier; + } + getSummary() { + if (this.schema?.summary && typeof this.schema.summary === "string") { + return this.schema.summary; + } else if (this.parentSchema.summary && typeof this.parentSchema.summary === "string") { + return this.parentSchema.summary; + } + return void 0; + } + getDescription() { + if (this.schema?.description && typeof this.schema.description === "string") { + return this.schema.description; + } else if (this.parentSchema.description && typeof this.parentSchema.description === "string") { + return this.parentSchema.description; + } + return void 0; + } + getParameters() { + let parameters = this.schema?.parameters || []; + const commonParams = this.parentSchema.parameters || []; + if (commonParams.length) { + parameters = parameters.concat(dedupeCommonParameters(parameters, commonParams) || []); + } + return parameters; + } +}; +var Webhook = class extends Operation { +}; + +/** + * Tokenize input string. + */ +function lexer(str) { + var tokens = []; + var i = 0; + while (i < str.length) { + var char = str[i]; + if (char === "*" || char === "+" || char === "?") { + tokens.push({ type: "MODIFIER", index: i, value: str[i++] }); + continue; + } + if (char === "\\") { + tokens.push({ type: "ESCAPED_CHAR", index: i++, value: str[i++] }); + continue; + } + if (char === "{") { + tokens.push({ type: "OPEN", index: i, value: str[i++] }); + continue; + } + if (char === "}") { + tokens.push({ type: "CLOSE", index: i, value: str[i++] }); + continue; + } + if (char === ":") { + var name = ""; + var j = i + 1; + while (j < str.length) { + var code = str.charCodeAt(j); + if ( + // `0-9` + (code >= 48 && code <= 57) || + // `A-Z` + (code >= 65 && code <= 90) || + // `a-z` + (code >= 97 && code <= 122) || + // `_` + code === 95) { + name += str[j++]; + continue; + } + break; + } + if (!name) + throw new TypeError("Missing parameter name at ".concat(i)); + tokens.push({ type: "NAME", index: i, value: name }); + i = j; + continue; + } + if (char === "(") { + var count = 1; + var pattern = ""; + var j = i + 1; + if (str[j] === "?") { + throw new TypeError("Pattern cannot start with \"?\" at ".concat(j)); + } + while (j < str.length) { + if (str[j] === "\\") { + pattern += str[j++] + str[j++]; + continue; + } + if (str[j] === ")") { + count--; + if (count === 0) { + j++; + break; + } + } + else if (str[j] === "(") { + count++; + if (str[j + 1] !== "?") { + throw new TypeError("Capturing groups are not allowed at ".concat(j)); + } + } + pattern += str[j++]; + } + if (count) + throw new TypeError("Unbalanced pattern at ".concat(i)); + if (!pattern) + throw new TypeError("Missing pattern at ".concat(i)); + tokens.push({ type: "PATTERN", index: i, value: pattern }); + i = j; + continue; + } + tokens.push({ type: "CHAR", index: i, value: str[i++] }); + } + tokens.push({ type: "END", index: i, value: "" }); + return tokens; +} +/** + * Parse a string for the raw tokens. + */ +function parse(str, options) { + if (options === void 0) { options = {}; } + var tokens = lexer(str); + var _a = options.prefixes, prefixes = _a === void 0 ? "./" : _a; + var defaultPattern = "[^".concat(escapeString(options.delimiter || "/#?"), "]+?"); + var result = []; + var key = 0; + var i = 0; + var path = ""; + var tryConsume = function (type) { + if (i < tokens.length && tokens[i].type === type) + return tokens[i++].value; + }; + var mustConsume = function (type) { + var value = tryConsume(type); + if (value !== undefined) + return value; + var _a = tokens[i], nextType = _a.type, index = _a.index; + throw new TypeError("Unexpected ".concat(nextType, " at ").concat(index, ", expected ").concat(type)); + }; + var consumeText = function () { + var result = ""; + var value; + while ((value = tryConsume("CHAR") || tryConsume("ESCAPED_CHAR"))) { + result += value; + } + return result; + }; + while (i < tokens.length) { + var char = tryConsume("CHAR"); + var name = tryConsume("NAME"); + var pattern = tryConsume("PATTERN"); + if (name || pattern) { + var prefix = char || ""; + if (prefixes.indexOf(prefix) === -1) { + path += prefix; + prefix = ""; + } + if (path) { + result.push(path); + path = ""; + } + result.push({ + name: name || key++, + prefix: prefix, + suffix: "", + pattern: pattern || defaultPattern, + modifier: tryConsume("MODIFIER") || "", + }); + continue; + } + var value = char || tryConsume("ESCAPED_CHAR"); + if (value) { + path += value; + continue; + } + if (path) { + result.push(path); + path = ""; + } + var open = tryConsume("OPEN"); + if (open) { + var prefix = consumeText(); + var name_1 = tryConsume("NAME") || ""; + var pattern_1 = tryConsume("PATTERN") || ""; + var suffix = consumeText(); + mustConsume("CLOSE"); + result.push({ + name: name_1 || (pattern_1 ? key++ : ""), + pattern: name_1 && !pattern_1 ? defaultPattern : pattern_1, + prefix: prefix, + suffix: suffix, + modifier: tryConsume("MODIFIER") || "", + }); + continue; + } + mustConsume("END"); + } + return result; +} +/** + * Create path match function from `path-to-regexp` spec. + */ +function match(str, options) { + var keys = []; + var re = pathToRegexp(str, keys, options); + return regexpToFunction(re, keys, options); +} +/** + * Create a path match function from `path-to-regexp` output. + */ +function regexpToFunction(re, keys, options) { + if (options === void 0) { options = {}; } + var _a = options.decode, decode = _a === void 0 ? function (x) { return x; } : _a; + return function (pathname) { + var m = re.exec(pathname); + if (!m) + return false; + var path = m[0], index = m.index; + var params = Object.create(null); + var _loop_1 = function (i) { + if (m[i] === undefined) + return "continue"; + var key = keys[i - 1]; + if (key.modifier === "*" || key.modifier === "+") { + params[key.name] = m[i].split(key.prefix + key.suffix).map(function (value) { + return decode(value, key); + }); + } + else { + params[key.name] = decode(m[i], key); + } + }; + for (var i = 1; i < m.length; i++) { + _loop_1(i); + } + return { path: path, index: index, params: params }; + }; +} +/** + * Escape a regular expression string. + */ +function escapeString(str) { + return str.replace(/([.+*?=^!:${}()[\]|/\\])/g, "\\$1"); +} +/** + * Get the flags for a regexp from the options. + */ +function flags(options) { + return options && options.sensitive ? "" : "i"; +} +/** + * Pull out keys from a regexp. + */ +function regexpToRegexp(path, keys) { + if (!keys) + return path; + var groupsRegex = /\((?:\?<(.*?)>)?(?!\?)/g; + var index = 0; + var execResult = groupsRegex.exec(path.source); + while (execResult) { + keys.push({ + // Use parenthesized substring match if available, index otherwise + name: execResult[1] || index++, + prefix: "", + suffix: "", + modifier: "", + pattern: "", + }); + execResult = groupsRegex.exec(path.source); + } + return path; +} +/** + * Transform an array into a regexp. + */ +function arrayToRegexp(paths, keys, options) { + var parts = paths.map(function (path) { return pathToRegexp(path, keys, options).source; }); + return new RegExp("(?:".concat(parts.join("|"), ")"), flags(options)); +} +/** + * Create a path regexp from string input. + */ +function stringToRegexp(path, keys, options) { + return tokensToRegexp(parse(path, options), keys, options); +} +/** + * Expose a function for taking tokens and returning a RegExp. + */ +function tokensToRegexp(tokens, keys, options) { + if (options === void 0) { options = {}; } + var _a = options.strict, strict = _a === void 0 ? false : _a, _b = options.start, start = _b === void 0 ? true : _b, _c = options.end, end = _c === void 0 ? true : _c, _d = options.encode, encode = _d === void 0 ? function (x) { return x; } : _d, _e = options.delimiter, delimiter = _e === void 0 ? "/#?" : _e, _f = options.endsWith, endsWith = _f === void 0 ? "" : _f; + var endsWithRe = "[".concat(escapeString(endsWith), "]|$"); + var delimiterRe = "[".concat(escapeString(delimiter), "]"); + var route = start ? "^" : ""; + // Iterate over the tokens and create our regexp string. + for (var _i = 0, tokens_1 = tokens; _i < tokens_1.length; _i++) { + var token = tokens_1[_i]; + if (typeof token === "string") { + route += escapeString(encode(token)); + } + else { + var prefix = escapeString(encode(token.prefix)); + var suffix = escapeString(encode(token.suffix)); + if (token.pattern) { + if (keys) + keys.push(token); + if (prefix || suffix) { + if (token.modifier === "+" || token.modifier === "*") { + var mod = token.modifier === "*" ? "?" : ""; + route += "(?:".concat(prefix, "((?:").concat(token.pattern, ")(?:").concat(suffix).concat(prefix, "(?:").concat(token.pattern, "))*)").concat(suffix, ")").concat(mod); + } + else { + route += "(?:".concat(prefix, "(").concat(token.pattern, ")").concat(suffix, ")").concat(token.modifier); + } + } + else { + if (token.modifier === "+" || token.modifier === "*") { + route += "((?:".concat(token.pattern, ")").concat(token.modifier, ")"); + } + else { + route += "(".concat(token.pattern, ")").concat(token.modifier); + } + } + } + else { + route += "(?:".concat(prefix).concat(suffix, ")").concat(token.modifier); + } + } + } + if (end) { + if (!strict) + route += "".concat(delimiterRe, "?"); + route += !options.endsWith ? "$" : "(?=".concat(endsWithRe, ")"); + } + else { + var endToken = tokens[tokens.length - 1]; + var isEndDelimited = typeof endToken === "string" + ? delimiterRe.indexOf(endToken[endToken.length - 1]) > -1 + : endToken === undefined; + if (!strict) { + route += "(?:".concat(delimiterRe, "(?=").concat(endsWithRe, "))?"); + } + if (!isEndDelimited) { + route += "(?=".concat(delimiterRe, "|").concat(endsWithRe, ")"); + } + } + return new RegExp(route, flags(options)); +} +/** + * Normalize the given path string, returning a regular expression. + * + * An empty array can be passed in for the keys, which will hold the + * placeholder key descriptions. For example, using `/user/:id`, `keys` will + * contain `[{ name: 'id', delimiter: '/', optional: false, repeat: false }]`. + */ +function pathToRegexp(path, keys, options) { + if (path instanceof RegExp) + return regexpToRegexp(path, keys); + if (Array.isArray(path)) + return arrayToRegexp(path, keys, options); + return stringToRegexp(path, keys, options); +} + +// src/lib/get-auth.ts +function getKey(user, scheme) { + switch (scheme.type) { + case "oauth2": + case "apiKey": + return user[scheme._key] || user.apiKey || scheme["x-default"] || null; + case "http": + if (scheme.scheme === "basic") { + return user[scheme._key] || { user: user.user || null, pass: user.pass || null }; + } + if (scheme.scheme === "bearer") { + return user[scheme._key] || user.apiKey || null; + } + return null; + default: + return null; + } +} +function getByScheme(user, scheme = {}, selectedApp) { + if (user?.keys && user.keys.length) { + if (selectedApp) { + return getKey( + user.keys.find((key) => key.name === selectedApp), + scheme + ); + } + return getKey(user.keys[0], scheme); + } + return getKey(user, scheme); +} +function getAuth(api, user, selectedApp) { + return Object.keys(api?.components?.securitySchemes || {}).map((scheme) => { + return { + [scheme]: getByScheme( + user, + { + // This sucks but since we dereference we'll never have a `$ref` pointer here with a + // `ReferenceObject` type. + ...api.components.securitySchemes[scheme], + _key: scheme + }, + selectedApp + ) + }; + }).reduce((prev, next) => Object.assign(prev, next), {}); +} + +// src/lib/get-user-variable.ts +function getUserVariable(user, property, selectedApp) { + let key = user; + if ("keys" in user && Array.isArray(user.keys) && user.keys.length) { + if (selectedApp) { + key = user.keys.find((k) => k.name === selectedApp); + } else { + key = user.keys[0]; + } + } + return key[property] || null; +} + +// src/index.ts +var SERVER_VARIABLE_REGEX = /{([-_a-zA-Z0-9:.[\]]+)}/g; +function ensureProtocol(url) { + if (url.match(/^\/\//)) { + return `https:${url}`; + } + if (!url.match(/\/\//)) { + return `https://${url}`; + } + return url; +} +function stripTrailingSlash(url) { + if (url[url.length - 1] === "/") { + return url.slice(0, -1); + } + return url; +} +function normalizedUrl(api, selected) { + const exampleDotCom = "https://example.com"; + let url; + try { + url = api.servers[selected].url; + if (!url) + throw new Error("no url"); + url = stripTrailingSlash(url); + if (url.startsWith("/") && !url.startsWith("//")) { + const urlWithOrigin = new URL(exampleDotCom); + urlWithOrigin.pathname = url; + url = urlWithOrigin.href; + } + } catch (e) { + url = exampleDotCom; + } + return ensureProtocol(url); +} +function transformUrlIntoRegex(url) { + return stripTrailingSlash(url.replace(SERVER_VARIABLE_REGEX, "([-_a-zA-Z0-9:.[\\]]+)")); +} +function normalizePath(path) { + return path.replace(/({?){(.*?)}(}?)/g, (str, ...args) => { + return `:${args[1].replace("-", "")}`; + }).replace(/::/, "\\::").split("?")[0]; +} +function generatePathMatches(paths, pathName, origin) { + const prunedPathName = pathName.split("?")[0]; + return Object.keys(paths).map((path) => { + const cleanedPath = normalizePath(path); + let matchResult; + try { + const matchStatement = match(cleanedPath, { decode: decodeURIComponent }); + matchResult = matchStatement(prunedPathName); + } catch (err) { + return; + } + const slugs = {}; + if (matchResult && Object.keys(matchResult.params).length) { + Object.keys(matchResult.params).forEach((param) => { + slugs[`:${param}`] = matchResult.params[param]; + }); + } + return { + url: { + origin, + path: cleanedPath.replace(/\\::/, "::"), + nonNormalizedPath: path, + slugs + }, + operation: paths[path], + match: matchResult + }; + }).filter(Boolean).filter((p) => p.match); +} +function filterPathMethods(pathMatches, targetMethod) { + const regExp = pathToRegexp(targetMethod); + return pathMatches.map((p) => { + const captures = Object.keys(p.operation).filter((r) => regExp.exec(r)); + if (captures.length) { + const method = captures[0]; + p.url.method = method.toUpperCase(); + return { + url: p.url, + operation: p.operation[method] + }; + } + return false; + }).filter(Boolean); +} +function findTargetPath(pathMatches) { + let minCount = Object.keys(pathMatches[0].url.slugs).length; + let operation; + for (let m = 0; m < pathMatches.length; m += 1) { + const selection = pathMatches[m]; + const paramCount = Object.keys(selection.url.slugs).length; + if (paramCount <= minCount) { + minCount = paramCount; + operation = selection; + } + } + return operation; +} +var Oas = class _Oas { + /** + * @param oas An OpenAPI definition. + * @param user The information about a user that we should use when pulling auth tokens from + * security schemes. + */ + constructor(oas, user) { + if (typeof oas === "string") { + oas = JSON.parse(oas); + } + this.api = oas; + this.user = user || {}; + this.promises = []; + this.dereferencing = { + processing: false, + complete: false, + circularRefs: [] + }; + } + /** + * This will initialize a new instance of the `Oas` class. This method is useful if you're using + * Typescript and are attempting to supply an untyped JSON object into `Oas` as it will force-type + * that object to an `OASDocument` for you. + * + * @param oas An OpenAPI definition. + * @param user The information about a user that we should use when pulling auth tokens from + * security schemes. + */ + static init(oas, user) { + return new _Oas(oas, user); + } + /** + * Retrieve the OpenAPI version that this API definition is targeted for. + */ + getVersion() { + if (this.api.openapi) { + return this.api.openapi; + } + throw new Error("Unable to recognize what specification version this API definition conforms to."); + } + /** + * Retrieve the current OpenAPI API Definition. + * + */ + getDefinition() { + return this.api; + } + url(selected = 0, variables) { + const url = normalizedUrl(this.api, selected); + return this.replaceUrl(url, variables || this.variables(selected)).trim(); + } + variables(selected = 0) { + let variables; + try { + variables = this.api.servers[selected].variables; + if (!variables) + throw new Error("no variables"); + } catch (e) { + variables = {}; + } + return variables; + } + defaultVariables(selected = 0) { + const variables = this.variables(selected); + const defaults = {}; + Object.keys(variables).forEach((key) => { + defaults[key] = getUserVariable(this.user, key) || variables[key].default || ""; + }); + return defaults; + } + splitUrl(selected = 0) { + const url = normalizedUrl(this.api, selected); + const variables = this.variables(selected); + return url.split(/({.+?})/).filter(Boolean).map((part, i) => { + const isVariable = part.match(/[{}]/); + const value = part.replace(/[{}]/g, ""); + const key = `${value}-${i}`; + if (!isVariable) { + return { + type: "text", + value, + key + }; + } + const variable = variables?.[value]; + return { + type: "variable", + value, + key, + description: variable?.description, + enum: variable?.enum + }; + }); + } + /** + * With a fully composed server URL, run through our list of known OAS servers and return back + * which server URL was selected along with any contained server variables split out. + * + * For example, if you have an OAS server URL of `https://{name}.example.com:{port}/{basePath}`, + * and pass in `https://buster.example.com:3000/pet` to this function, you'll get back the + * following: + * + * { selected: 0, variables: { name: 'buster', port: 3000, basePath: 'pet' } } + * + * Re-supplying this data to `oas.url()` should return the same URL you passed into this method. + * + * @param baseUrl A given URL to extract server variables out of. + */ + splitVariables(baseUrl) { + const matchedServer = (this.api.servers || []).map((server, i) => { + const rgx = transformUrlIntoRegex(server.url); + const found = new RegExp(rgx).exec(baseUrl); + if (!found) { + return false; + } + const variables = {}; + Array.from(server.url.matchAll(SERVER_VARIABLE_REGEX)).forEach((variable, y) => { + variables[variable[1]] = found[y + 1]; + }); + return { + selected: i, + variables + }; + }).filter(Boolean); + return matchedServer.length ? matchedServer[0] : false; + } + /** + * Replace templated variables with supplied data in a given URL. + * + * There are a couple ways that this will utilize variable data: + * + * - If data is stored in `this.user` and it matches up with the variable name in the URL user + * data will always take priority. See `getUserVariable` for some more information on how this + * data is pulled from `this.user`. + * - Supplying a `variables` object. This incoming `variables` object can be two formats: + * `{ variableName: { default: 'value' } }` and `{ variableName: 'value' }`. If the former is + * present, that will take prescendence over the latter. + * + * If no variables supplied match up with the template name, the template name will instead be + * used as the variable data. + * + * @param url A URL to swap variables into. + * @param variables An object containing variables to swap into the URL. + */ + replaceUrl(url, variables = {}) { + return stripTrailingSlash( + url.replace(SERVER_VARIABLE_REGEX, (original, key) => { + const userVariable = getUserVariable(this.user, key); + if (userVariable) { + return userVariable; + } + if (key in variables) { + const data = variables[key]; + if (typeof data === "object") { + if (!Array.isArray(data) && data !== null && "default" in data) { + return data.default; + } + } else { + return data; + } + } + return original; + }) + ); + } + /** + * Retrieve an Operation of Webhook class instance for a given path and method. + * + * @param path Path to lookup and retrieve. + * @param method HTTP Method to retrieve on the path. + */ + operation(path, method, opts = {}) { + let operation = { + parameters: [] + }; + if (opts.isWebhook) { + const api = this.api; + if (api?.webhooks[path]?.[method]) { + operation = api.webhooks[path][method]; + return new Webhook(api, path, method, operation); + } + } + if (this?.api?.paths?.[path]?.[method]) { + operation = this.api.paths[path][method]; + } + return new Operation(this.api, path, method, operation); + } + findOperationMatches(url) { + const { origin, hostname } = new URL(url); + const originRegExp = new RegExp(origin, "i"); + const { servers, paths } = this.api; + let pathName; + let targetServer; + let matchedServer; + if (!servers || !servers.length) { + matchedServer = { + url: "https://example.com" + }; + } else { + matchedServer = servers.find((s) => originRegExp.exec(this.replaceUrl(s.url, s.variables || {}))); + if (!matchedServer) { + const hostnameRegExp = new RegExp(hostname); + matchedServer = servers.find((s) => hostnameRegExp.exec(this.replaceUrl(s.url, s.variables || {}))); + } + } + if (!matchedServer) { + const matchedServerAndPath = servers.map((server) => { + const rgx = transformUrlIntoRegex(server.url); + const found = new RegExp(rgx).exec(url); + if (!found) { + return false; + } + return { + matchedServer: server, + pathName: url.split(new RegExp(rgx)).slice(-1).pop() + }; + }).filter(Boolean); + if (!matchedServerAndPath.length) { + return void 0; + } + pathName = matchedServerAndPath[0].pathName; + targetServer = { + ...matchedServerAndPath[0].matchedServer + }; + } else { + targetServer = { + ...matchedServer, + url: this.replaceUrl(matchedServer.url, matchedServer.variables || {}) + }; + [, pathName] = url.split(new RegExp(targetServer.url, "i")); + } + if (pathName === void 0) + return void 0; + if (pathName === "") + pathName = "/"; + const annotatedPaths = generatePathMatches(paths, pathName, targetServer.url); + if (!annotatedPaths.length) + return void 0; + return annotatedPaths; + } + /** + * Discover an operation in an OAS from a fully-formed URL and HTTP method. Will return an object + * containing a `url` object and another one for `operation`. This differs from `getOperation()` + * in that it does not return an instance of the `Operation` class. + * + * @param url A full URL to look up. + * @param method The cooresponding HTTP method to look up. + */ + findOperation(url, method) { + const annotatedPaths = this.findOperationMatches(url); + if (!annotatedPaths) { + return void 0; + } + const matches = filterPathMethods(annotatedPaths, method); + if (!matches.length) + return void 0; + return findTargetPath(matches); + } + /** + * Discover an operation in an OAS from a fully-formed URL without an HTTP method. Will return an + * object containing a `url` object and another one for `operation`. + * + * @param url A full URL to look up. + */ + findOperationWithoutMethod(url) { + const annotatedPaths = this.findOperationMatches(url); + if (!annotatedPaths) { + return void 0; + } + return findTargetPath(annotatedPaths); + } + /** + * Retrieve an operation in an OAS from a fully-formed URL and HTTP method. Differs from + * `findOperation` in that while this method will return an `Operation` instance, + * `findOperation()` does not. + * + * @param url A full URL to look up. + * @param method The cooresponding HTTP method to look up. + */ + getOperation(url, method) { + const op = this.findOperation(url, method); + if (op === void 0) { + return void 0; + } + return this.operation(op.url.nonNormalizedPath, method); + } + /** + * With an object of user information, retrieve the appropriate API auth keys from the current + * OAS definition. + * + * @see {@link https://docs.readme.com/docs/passing-data-to-jwt} + * @param user User + * @param selectedApp The user app to retrieve an auth key for. + */ + getAuth(user, selectedApp) { + if (!this.api?.components?.securitySchemes) { + return {}; + } + return getAuth(this.api, user, selectedApp); + } + /** + * Returns the `paths` object that exists in this API definition but with every `method` mapped + * to an instance of the `Operation` class. + * + * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.0.md#oasObject} + * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#openapi-object} + */ + getPaths() { + const paths = {}; + Object.keys(this.api.paths ? this.api.paths : []).forEach((path) => { + if (path.startsWith("x-")) { + return; + } + paths[path] = {}; + if ("$ref" in this.api.paths[path]) { + this.api.paths[path] = utils_default.findSchemaDefinition(this.api.paths[path].$ref, this.api); + } + Object.keys(this.api.paths[path]).forEach((method) => { + if (!supportedMethods.has(method)) + return; + paths[path][method] = this.operation(path, method); + }); + }); + return paths; + } + /** + * Returns the `webhooks` object that exists in this API definition but with every `method` + * mapped to an instance of the `Webhook` class. + * + * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.0.md#oasObject} + * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#openapi-object} + */ + getWebhooks() { + const webhooks = {}; + const api = this.api; + Object.keys(api.webhooks ? api.webhooks : []).forEach((id) => { + webhooks[id] = {}; + Object.keys(api.webhooks[id]).forEach((method) => { + webhooks[id][method] = this.operation(id, method, { isWebhook: true }); + }); + }); + return webhooks; + } + /** + * Return an array of all tag names that exist on this API definition. + * + * Note: This method right now does **not** factor in webhooks that have tags. + * + * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.0.md#oasObject} + * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#openapi-object} + * @param setIfMissing If a tag is not present on an operation that operations path will be added + * into the list of tags returned. + */ + getTags(setIfMissing = false) { + const allTags = /* @__PURE__ */ new Set(); + Object.entries(this.getPaths()).forEach(([path, operations]) => { + Object.values(operations).forEach((operation) => { + const tags = operation.getTags(); + if (setIfMissing && !tags.length) { + allTags.add(path); + return; + } + tags.forEach((tag) => { + allTags.add(tag.name); + }); + }); + }); + return Array.from(allTags); + } + /** + * Determine if a given a custom specification extension exists within the API definition. + * + * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions} + * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specificationExtensions} + * @param extension Specification extension to lookup. + */ + hasExtension(extension) { + return Boolean(this.api && extension in this.api); + } + /** + * Retrieve a custom specification extension off of the API definition. + * + * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions} + * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specificationExtensions} + * @param extension Specification extension to lookup. + */ + getExtension(extension) { + return this.api?.[extension]; + } + /** + * Retrieve any circular `$ref` pointers that maybe present within the API definition. + * + * This method requires that you first dereference the definition. + * + * @see Oas.dereference + */ + getCircularReferences() { + if (!this.dereferencing.complete) { + throw new Error("#dereference() must be called first in order for this method to obtain circular references."); + } + return this.dereferencing.circularRefs; + } + /** + * Dereference the current OAS definition so it can be parsed free of worries of `$ref` schemas + * and circular structures. + * + */ + async dereference(opts = { preserveRefAsJSONSchemaTitle: false }) { + if (this.dereferencing.complete) { + return new Promise((resolve) => { + resolve(true); + }); + } + if (this.dereferencing.processing) { + return new Promise((resolve, reject) => { + this.promises.push({ resolve, reject }); + }); + } + this.dereferencing.processing = true; + const { api, promises } = this; + if (api && api.components && api.components.schemas && typeof api.components.schemas === "object") { + Object.keys(api.components.schemas).forEach((schemaName) => { + if (isPrimitive$2(api.components.schemas[schemaName]) || Array.isArray(api.components.schemas[schemaName]) || api.components.schemas[schemaName] === null) { + return; + } + if (opts.preserveRefAsJSONSchemaTitle) { + api.components.schemas[schemaName].title = schemaName; + } + api.components.schemas[schemaName]["x-readme-ref-name"] = schemaName; + }); + } + const parser = new $RefParser$2(); + return parser.dereference(api || {}, { + resolve: { + // We shouldn't be resolving external pointers at this point so just ignore them. + external: false + }, + dereference: { + // If circular `$refs` are ignored they'll remain in the OAS as `$ref: String`, otherwise + // `$ref‘ just won't exist. This allows us to do easy circular reference detection. + circular: "ignore" + } + }).then((dereferenced) => { + let circularRefs = []; + if (parser.$refs.circular) { + circularRefs = parser.$refs.circularRefs.map((pointer) => { + return `#${pointer.split("#")[1]}`; + }); + } + this.api = dereferenced; + this.promises = promises; + this.dereferencing = { + processing: false, + complete: true, + circularRefs + }; + if (opts.cb) { + opts.cb(); + } + }).then(() => { + return this.promises.map((deferred) => deferred.resolve()); + }); + } +}; + +// src/analyzer/queries/openapi.ts +function additionalProperties(definition) { + return query(["$..additionalProperties"], definition).map((res) => refizePointer(res.pointer)); +} +function callbacks(definition) { + return query(["$.components.callbacks", "$.paths..callbacks"], definition).map((res) => refizePointer(res.pointer)); +} +async function circularRefs(definition) { + const oas = new Oas(JSON.parse(JSON.stringify(definition))); + await oas.dereference(); + const results = oas.getCircularReferences(); + results.sort(); + return results; +} +function discriminators(definition) { + return query(["$..discriminator"], definition).map((res) => refizePointer(res.pointer)); +} +function links(definition) { + return query(["$..links"], definition).map((res) => refizePointer(res.pointer)); +} +function mediaTypes(definition) { + const results = Array.from( + new Set( + query(["$..paths..content"], definition).map((res) => { + return Object.keys(res.value); + }).flat() + ) + ); + results.sort(); + return results; +} +function parameterSerialization(definition) { + return query(["$..parameters[*].style^"], definition).map((res) => refizePointer(res.pointer)); +} +function polymorphism(definition) { + const results = Array.from( + new Set(query(["$..allOf^", "$..anyOf^", "$..oneOf^"], definition).map((res) => refizePointer(res.pointer))) + ); + results.sort(); + return results; +} +function securityTypes(definition) { + return Array.from(new Set(query(["$.components.securitySchemes..type"], definition).map((res) => res.value))); +} +function serverVariables(definition) { + return query(["$.servers..variables^"], definition).map((res) => refizePointer(res.pointer)); +} +function totalOperations(definition) { + return query(["$..paths[*]"], definition).map((res) => Object.keys(res.value)).flat().length; +} +function webhooks(definition) { + return query(["$.webhooks[*]"], definition).map((res) => refizePointer(res.pointer)); +} +function xml(definition) { + return query( + [ + "$.components.schemas..xml^", + "$..parameters..xml^", + "$..requestBody..xml^", + "$..requestBody..['application/xml']", + "$..requestBody..['application/xml-external-parsed-entity']", + "$..requestBody..['application/xml-dtd']", + "$..requestBody..['text/xml']", + "$..requestBody..['text/xml-external-parsed-entity']", + "$..requestBody.content[?(@property.match(/\\+xml$/i))]", + "$..responses..['application/xml']", + "$..responses..['application/xml-external-parsed-entity']", + "$..responses..['application/xml-dtd']", + "$..responses..['text/xml']", + "$..responses..['text/xml-external-parsed-entity']", + "$..responses[*].content[?(@property.match(/\\+xml$/i))]" + ], + definition + ).map((res) => refizePointer(res.pointer)); +} + +// src/analyzer/queries/readme.ts +function authDefaults(definition) { + return query(["$.components.securitySchemes..['x-default']^"], definition).map((res) => refizePointer(res.pointer)); +} +function codeSampleLanguages(definition) { + const results = Array.from( + new Set( + query(["$..['x-readme']['samples-languages']", "$..['x-samples-languages']"], definition).map((res) => res.value).reduce((prev, next) => prev.concat(next), []) + ) + ); + results.sort(); + return results; +} +function codeSamplesDisabled(definition) { + return Array.from( + new Set( + query( + [ + "$['x-samples-enabled']^", + "$['x-readme']['samples-enabled']", + "$..paths[*]..['x-samples-enabled']^", + "$..paths[*]..['x-readme']['samples-enabled']^^" + ], + definition + ).map((res) => refizePointer(res.pointer)) + ) + ); +} +function corsProxyDisabled(definition) { + return Array.from( + new Set( + query( + [ + "$['x-proxy-enabled']^", + "$['x-readme']['proxy-enabled']", + "$..paths[*]..['x-proxy-enabled']^", + "$..paths[*]..['x-readme']['proxy-enabled']^^" + ], + definition + ).map((res) => refizePointer(res.pointer)) + ) + ); +} +function customCodeSamples(definition) { + return query(["$..['x-code-samples']", "$..['x-readme']['code-samples']"], definition).filter((res) => { + return Array.isArray(res.value) && res.value.length ? res : false; + }).map((res) => refizePointer(res.pointer)); +} +function explorerDisabled(definition) { + return query( + [ + "$['x-explorer-enabled']^", + "$['x-readme']['explorer-enabled']", + "$..paths[*]..['x-explorer-enabled']^", + "$..paths[*]..['x-readme']['explorer-enabled']^^" + ], + definition + ).map((res) => refizePointer(res.pointer)); +} +function rawBody(definition) { + return query(["$..RAW_BODY^^"], definition).map((res) => refizePointer(res.pointer)); +} +function staticHeaders(definition) { + return query(["$..['x-headers']", "$..['x-readme']['headers']"], definition).filter((res) => { + return Array.isArray(res.value) && res.value.length ? res : false; + }).map((res) => refizePointer(res.pointer)); +} + +// src/analyzer/index.ts +async function analyzer(definition) { + const additionalProperties2 = additionalProperties(definition); + const callbacks2 = callbacks(definition); + const circularRefs2 = await circularRefs(definition); + const discriminators2 = discriminators(definition); + const links2 = links(definition); + const parameterSerialization2 = parameterSerialization(definition); + const polymorphism2 = polymorphism(definition); + const serverVariables2 = serverVariables(definition); + const webhooks2 = webhooks(definition); + const xml2 = xml(definition); + const authDefaults2 = authDefaults(definition); + const codeSampleLanguages2 = codeSampleLanguages(definition); + const customCodeSamples2 = customCodeSamples(definition); + const codeSamplesDisabled2 = codeSamplesDisabled(definition); + const disabledCorsProxy = corsProxyDisabled(definition); + const explorerDisabled2 = explorerDisabled(definition); + const staticHeaders2 = staticHeaders(definition); + const rawBody2 = rawBody(definition); + const analysis = { + general: { + mediaTypes: { + name: "Media Type", + found: mediaTypes(definition) + }, + operationTotal: { + name: "Operation", + found: totalOperations(definition) + }, + securityTypes: { + name: "Security Type", + found: securityTypes(definition) + } + }, + openapi: { + additionalProperties: { + present: !!additionalProperties2.length, + locations: additionalProperties2 + }, + callbacks: { + present: !!callbacks2.length, + locations: callbacks2 + }, + circularRefs: { + present: !!circularRefs2.length, + locations: circularRefs2 + }, + discriminators: { + present: !!discriminators2.length, + locations: discriminators2 + }, + links: { + present: !!links2.length, + locations: links2 + }, + style: { + present: !!parameterSerialization2.length, + locations: parameterSerialization2 + }, + polymorphism: { + present: !!polymorphism2.length, + locations: polymorphism2 + }, + serverVariables: { + present: !!serverVariables2.length, + locations: serverVariables2 + }, + webhooks: { + present: !!webhooks2.length, + locations: webhooks2 + }, + xml: { + present: !!xml2.length, + locations: xml2 + } + }, + readme: { + "x-default": { + present: !!authDefaults2.length, + locations: authDefaults2 + }, + "x-readme.code-samples": { + present: !!customCodeSamples2.length, + locations: customCodeSamples2 + }, + "x-readme.headers": { + present: !!staticHeaders2.length, + locations: staticHeaders2 + }, + "x-readme.explorer-enabled": { + present: !!explorerDisabled2.length, + locations: explorerDisabled2 + }, + "x-readme.proxy-enabled": { + present: !!disabledCorsProxy.length, + locations: disabledCorsProxy + }, + "x-readme.samples-languages": { + present: !!codeSampleLanguages2.length, + locations: codeSampleLanguages2 + } + } + }; + if (codeSamplesDisabled2.length) { + analysis.readme["x-readme.samples-enabled"] = { + present: !!codeSamplesDisabled2.length, + locations: codeSamplesDisabled2 + }; + } + if (rawBody2.length) { + analysis.readme.raw_body = { + present: !!rawBody2.length, + locations: rawBody2 + }; + } + return analysis; +} + +const OPENAPI_FEATURE_DOCS = { + additionalProperties: { + description: 'additionalProperties allows you to document dictionaries where the keys are user-supplied strings.', + url: { + '3.0': 'https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#schema-object', + '3.1': 'https://json-schema.org/understanding-json-schema/reference/object.html#additional-properties', + }, + }, + callbacks: { + description: 'Callbacks are asynchronous, out-of-band requests that your service will send to some other service in response to certain events.', + url: { + '3.0': 'https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#callback-object', + '3.1': 'https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#callback-object', + }, + }, + circularRefs: { + description: 'Circular references are $ref pointers that at some point in their lineage reference themselves.', + }, + discriminators: { + description: 'With schemas that can be, or contain, different shapes, discriminators help you assist your users in identifying and determining the kind of shape they can supply or receive.', + url: { + '3.0': 'https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#discriminator-object', + '3.1': 'https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#discriminator-object', + }, + }, + links: { + description: 'Links allow you to define at call-time relationships to other operations within your API.', + url: { + '3.0': 'https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#link-object', + '3.1': 'https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#link-object', + }, + }, + style: { + description: 'Parameter serialization (style) allows you to describe how the parameter should be sent to your API.', + url: { + '3.0': 'https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#parameter-style', + '3.1': 'https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameter-style', + }, + }, + polymorphism: { + description: 'Polymorphism (allOf, oneOf, and anyOf) allow you to describe schemas that may contain either many different shapes, or a single shape containing multiple different schemas.', + url: { + '3.0': 'https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#schema-object', + '3.1': 'https://json-schema.org/understanding-json-schema/reference/combining.html', + }, + }, + serverVariables: { + description: 'Server variables allow to do user-supplied variable subsitituions within your API server URL.', + url: { + '3.0': 'https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#server-variable-object', + '3.1': 'https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#server-variable-object', + }, + }, + webhooks: { + description: 'Webhooks allow you to describe out of band requests that may be initiated by your users.', + url: { + '3.1': 'https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#user-content-oaswebhooks', + }, + }, + xml: { + description: 'Any parameter and/or request body that accepts XML or responses that return XML payloads.', + url: { + '3.0': 'https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#xml-object', + '3.1': 'https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#xml-object', + }, + }, +}; +const README_FEATURE_DOCS = { + 'x-default': { + description: 'The x-default extension allows you to define static authentication credential defaults for OAuth 2 and API Key security types.', + url: 'https://docs.readme.com/main/docs/openapi-extensions#authentication-defaults', + }, + 'x-readme.code-samples': { + description: 'The x-readme.code-samples extension allows you to custom, create static code samples on your API documentation.', + url: 'https://docs.readme.com/main/docs/openapi-extensions#custom-code-samples', + }, + 'x-readme.headers': { + description: 'The x-readme.headers extension allows you define headers that should always be present on your API or a specific operation, as well as what its value should be.', + url: 'https://docs.readme.com/main/docs/openapi-extensions#static-headers', + }, + 'x-readme.explorer-enabled': { + description: 'The x-readme.explorer-enabled extension allows you to toggle your API documentation being interactive or not.', + url: 'https://docs.readme.com/main/docs/openapi-extensions#disable-the-api-explorer', + }, + 'x-readme.proxy-enabled': { + description: "The x-readme.proxy-enabled extension allows you to toggle if API requests from API documentation should be routed through ReadMe's CORS Proxy. You should only need to use this if your API does not support CORS.", + url: 'https://docs.readme.com/main/docs/openapi-extensions#cors-proxy-enabled', + }, + 'x-readme.samples-languages': { + description: 'The x-readme.samples-languages extension allows you to toggle what languages are shown by default for code snippets in your API documentation.', + url: 'https://docs.readme.com/main/docs/openapi-extensions#code-sample-languages', + }, + 'x-readme.samples-enabled': { + description: 'The x-readme.samples-enabled extension allowed you to disable code samples on specific endpoints. It is no longer supported and can be safely removed from your API definition.', + url: 'https://docs.readme.com/main/docs/openapi-extensions#disable-code-examples', + }, + raw_body: { + description: "The RAW_BODY property allows you to define that a request body should have its payload delivered as a raw string. This legacy feature is specific to our Manual API editor and we don't recommend you use it outside of that context, instead opting for a traditional `type: string, format: blob` schema definition.", + }, +}; +/** + * Analyze a given OpenAPI or Swagger definition for any OpenAPI, JSON Schema, and ReadMe-specific + * feature uses it may contain. + * + */ +async function analyzeOas(definition) { + return analyzer(definition).then((analysis) => { + if (analysis.openapi) { + Object.entries(OPENAPI_FEATURE_DOCS).forEach(([feature, docs]) => { + // eslint-disable-next-line no-param-reassign + analysis.openapi[feature] = { + ...analysis.openapi[feature], + ...docs, + }; + }); + } + if (analysis.readme) { + Object.entries(README_FEATURE_DOCS).forEach(([feature, docs]) => { + // If this ReadMe feature isn't in our resulted analysis result then it's a deprecated + // feature that this API definition doesn't contain so we don't need to inform the user of + // something they neither use, can't use anyways, nor should know about. + if (!(feature in analysis.readme)) { + return; + } + // eslint-disable-next-line no-param-reassign + analysis.readme[feature] = { + ...analysis.readme[feature], + ...docs, + }; + }); + } + return analysis; + }); +} +function getSupportedFeatures() { + return [ + // OpenAPI features + ...Object.keys(OPENAPI_FEATURE_DOCS), + 'readme', // A catch-all for ReadMe features and extensions. Will look for everything. + ]; +} + +/** + * A lightweight Error wrapper that we use for outputting errors that don't need aggressive red + * coloring or to be printed with `console.error()`. + * + */ +class SoftError extends Error { + constructor(output) { + super(output); + this.name = 'SoftError'; + } +} + +class OpenAPIInspectCommand extends Command { + constructor() { + super(); + this.command = 'openapi:inspect'; + this.usage = 'openapi:inspect [file|url] [options]'; + this.description = 'Analyze an OpenAPI/Swagger definition for various OpenAPI and ReadMe feature usage.'; + this.cmdCategory = CommandCategories.APIS; + this.hiddenArgs = ['spec']; + this.args = [ + { + name: 'spec', + type: String, + defaultOption: true, + }, + this.getWorkingDirArg(), + { + name: 'feature', + type: String, + description: `A specific OpenAPI or ReadMe feature you wish to see detailed information on (if it exists). If any features supplied do not exist within the API definition an exit(1) code will be returned alongside the report.\n\nAvailable options: ${new Intl.ListFormat('en', { style: 'narrow' }).format(getSupportedFeatures())}`, + multiple: true, + }, + ]; + this.tableBorder = Object.entries(src$2.getBorderCharacters('norc')) + .map(([border, char]) => ({ [border]: chalk$5.gray(char) })) + .reduce((prev, next) => Object.assign(prev, next)); + } + getFeatureDocsURL(feature) { + if (!feature.url) { + return undefined; + } + if (typeof feature.url === 'object') { + // We don't need to do any Swagger or Postman determination here because this command + // always converts their spec to OpenAPI 3.0. + if (this.definitionVersion.startsWith('3.0')) { + return feature.url?.['3.0'] || 'This feature is not available on OpenAPI v3.0.'; + } + else if (this.definitionVersion.startsWith('3.1')) { + return feature.url?.['3.1'] || 'This feature is not available on OpenAPI v3.1.'; + } + return ''; + } + return feature.url; + } + // eslint-disable-next-line class-methods-use-this + buildFeaturesReport(analysis, features) { + let hasUnusedFeature = false; + const report = [ + // Minor bit of padding between the top of our report and the "analyzing your spec" messaging. + '', + ]; + features.forEach(feature => { + if (feature in analysis.openapi) { + const info = analysis.openapi[feature]; + if (!info.present) { + // If our last report entry was an unused feature we should add an empty line in the + // report to give everything some room to breathe. + if (report.length && report[report.length - 1].length) { + report.push(''); + } + report.push(`${feature}: You do not use this.`); + hasUnusedFeature = true; + } + else { + report.push(''); + report.push(`${feature}:`); + report.push(...info.locations.map(loc => ` · ${chalk$5.yellow(loc)}`)); + } + } + }); + if (features.includes('readme')) { + // Add some spacing between our OpenAPI and ReadMe extension reports (but only if our last + // entry wasn't an empty line). + if (features.length > 1 && report[report.length - 1].length) { + report.push(''); + } + Object.entries(analysis.readme).forEach(([feature, info]) => { + if (!info.present) { + report.push(`${feature}: You do not use this.`); + hasUnusedFeature = true; + } + else { + report.push(`${feature}:`); + report.push(...info.locations.map(loc => ` · ${chalk$5.yellow(loc)}`)); + report.push(''); + } + }); + } + // Because we add a little bit of padding between our report and the "analyzing your spec" copy + // if this second entry in the report is an empty line then we can safely remove it so we don't + // end up with multiple empty lines at the top of our report. + if (!report[1].length) { + report.splice(0, 1); + } + // If the last entry in our report array is an empty string then we should remove it. + if (!report[report.length - 1].length) { + report.pop(); + } + return { + report: report.join('\n'), + hasUnusedFeature, + }; + } + buildFullReport(analysis) { + const report = ['Here are some interesting things we found in your API definition. 🕵️', '']; + // General API definition statistics + Object.entries(analysis.general).forEach(([, info]) => { + let msg; + if (Array.isArray(info.found)) { + if (!info.found.length) { + return; + } + const highlightedData = info.found.map(d => chalk$5.yellow(d)); + if (info.found.length > 1) { + msg = `You are using ${chalk$5.bold(info.found.length)} ${pluralize(info.name, info.found.length)} throughout your API: ${new Intl.ListFormat('en').format(highlightedData)}`; + } + else { + msg = `You are using a single ${info.name} throughout your API: ${highlightedData[0]}`; + } + } + else if (info.found > 1) { + msg = `You have a total of ${chalk$5.bold(info.found)} ${pluralize(info.name, info.found)} in your API.`; + if (info.found > 100) { + msg += ' Wow!'; + } + } + else { + msg = `You have a single ${info.name} in your API.`; + } + report.push(` · ${msg}`); + }); + // Build out a view of all OpenAPI and ReadMe features that we discovered. + [ + { component: 'openapi', header: 'OpenAPI Features' }, + { component: 'readme', header: 'ReadMe-Specific Features and Extensions' }, + ].forEach(({ component, header }) => { + const tableData = [ + [chalk$5.bold.green('Feature'), chalk$5.bold.green('Used?'), chalk$5.bold.green('Description')], + ]; + Object.entries(analysis[component]).forEach(([feature, info]) => { + const descriptions = []; + if (info.description) { + descriptions.push(info.description); + } + const url = this.getFeatureDocsURL(info); + if (url) { + descriptions.push(chalk$5.grey(url)); + } + tableData.push([feature, info.present ? '✅' : '', descriptions.join('\n\n')]); + }); + report.push(''); + report.push(header); + report.push(src$2.table(tableData, { + border: this.tableBorder, + columns: { + 2: { + width: 80, + wrapWord: true, + }, + }, + })); + }); + return report.join('\n'); + } + async run(opts) { + await super.run(opts); + const { spec, workingDirectory, feature: features } = opts; + // If we have features we should validate that they're supported. + if (features?.length) { + const invalidFeatures = features.filter(feature => !getSupportedFeatures().includes(feature)); + if (invalidFeatures.length) { + return Promise.reject(new Error(`Unknown features: ${invalidFeatures.join(', ')}. See \`${config.cli} help ${this.command}\` for help.`)); + } + } + if (workingDirectory) { + const previousWorkingDirectory = process.cwd(); + process.chdir(workingDirectory); + Command.debug(`switching working directory from ${previousWorkingDirectory} to ${process.cwd()}`); + } + const { preparedSpec, definitionVersion } = await prepareOas(spec, 'openapi:inspect', { convertToLatest: true }); + this.definitionVersion = definitionVersion.version; + const parsedPreparedSpec = JSON.parse(preparedSpec); + const spinner = ora({ ...oraOptions() }); + if (features?.length) { + spinner.start(`Analyzing your API definition for usage of ${new Intl.ListFormat('en').format(features.map(feature => (feature === 'readme' ? 'ReadMe extensions' : feature)))}...`); + } + else { + spinner.start('Analyzing your API definition for OpenAPI and ReadMe feature usage...'); + } + const analysis = await analyzeOas(parsedPreparedSpec).catch(err => { + Command.debug(`analyzer err: ${err.message}`); + spinner.fail(); + throw err; + }); + if (features?.length) { + spinner.succeed(`${spinner.text} done! ✅`); + const { report, hasUnusedFeature } = this.buildFeaturesReport(analysis, features); + if (hasUnusedFeature) { + // If we have any unused features we should reject the command with a soft error so we + // output the report as normal but return a `exit(1)` status code. + return Promise.reject(new SoftError(report)); + } + return Promise.resolve(report); + } + spinner.stop(); + return Promise.resolve(this.buildFullReport(analysis)); + } +} + +function isOpenAPI(schema) { + return !!schema.openapi; +} +function isPostman(schema) { + return !!schema.info && !!schema.item; +} +function isSwagger(schema) { + return !!schema.swagger; +} +function getAPIDefinitionType(schema) { + if (isOpenAPI(schema)) { + return "openapi"; + } else if (isPostman(schema)) { + return "postman"; + } else if (isSwagger(schema)) { + return "swagger"; + } + return "unknown"; +} + +var publicApi = {}; + +var URL$2 = {exports: {}}; + +var conversions$1 = {}; +var lib = conversions$1; + +function sign(x) { + return x < 0 ? -1 : 1; +} + +function evenRound(x) { + // Round x to the nearest integer, choosing the even integer if it lies halfway between two. + if ((x % 1) === 0.5 && (x & 1) === 0) { // [even number].5; round down (i.e. floor) + return Math.floor(x); + } else { + return Math.round(x); + } +} + +function createNumberConversion(bitLength, typeOpts) { + if (!typeOpts.unsigned) { + --bitLength; + } + const lowerBound = typeOpts.unsigned ? 0 : -Math.pow(2, bitLength); + const upperBound = Math.pow(2, bitLength) - 1; + + const moduloVal = typeOpts.moduloBitLength ? Math.pow(2, typeOpts.moduloBitLength) : Math.pow(2, bitLength); + const moduloBound = typeOpts.moduloBitLength ? Math.pow(2, typeOpts.moduloBitLength - 1) : Math.pow(2, bitLength - 1); + + return function(V, opts) { + if (!opts) opts = {}; + + let x = +V; + + if (opts.enforceRange) { + if (!Number.isFinite(x)) { + throw new TypeError("Argument is not a finite number"); + } + + x = sign(x) * Math.floor(Math.abs(x)); + if (x < lowerBound || x > upperBound) { + throw new TypeError("Argument is not in byte range"); + } + + return x; + } + + if (!isNaN(x) && opts.clamp) { + x = evenRound(x); + + if (x < lowerBound) x = lowerBound; + if (x > upperBound) x = upperBound; + return x; + } + + if (!Number.isFinite(x) || x === 0) { + return 0; + } + + x = sign(x) * Math.floor(Math.abs(x)); + x = x % moduloVal; + + if (!typeOpts.unsigned && x >= moduloBound) { + return x - moduloVal; + } else if (typeOpts.unsigned) { + if (x < 0) { + x += moduloVal; + } else if (x === -0) { // don't return negative zero + return 0; + } + } + + return x; + } +} + +conversions$1["void"] = function () { + return undefined; +}; + +conversions$1["boolean"] = function (val) { + return !!val; +}; + +conversions$1["byte"] = createNumberConversion(8, { unsigned: false }); +conversions$1["octet"] = createNumberConversion(8, { unsigned: true }); + +conversions$1["short"] = createNumberConversion(16, { unsigned: false }); +conversions$1["unsigned short"] = createNumberConversion(16, { unsigned: true }); + +conversions$1["long"] = createNumberConversion(32, { unsigned: false }); +conversions$1["unsigned long"] = createNumberConversion(32, { unsigned: true }); + +conversions$1["long long"] = createNumberConversion(32, { unsigned: false, moduloBitLength: 64 }); +conversions$1["unsigned long long"] = createNumberConversion(32, { unsigned: true, moduloBitLength: 64 }); + +conversions$1["double"] = function (V) { + const x = +V; + + if (!Number.isFinite(x)) { + throw new TypeError("Argument is not a finite floating-point value"); + } + + return x; +}; + +conversions$1["unrestricted double"] = function (V) { + const x = +V; + + if (isNaN(x)) { + throw new TypeError("Argument is NaN"); + } + + return x; +}; + +// not quite valid, but good enough for JS +conversions$1["float"] = conversions$1["double"]; +conversions$1["unrestricted float"] = conversions$1["unrestricted double"]; + +conversions$1["DOMString"] = function (V, opts) { + if (!opts) opts = {}; + + if (opts.treatNullAsEmptyString && V === null) { + return ""; + } + + return String(V); +}; + +conversions$1["ByteString"] = function (V, opts) { + const x = String(V); + let c = undefined; + for (let i = 0; (c = x.codePointAt(i)) !== undefined; ++i) { + if (c > 255) { + throw new TypeError("Argument is not a valid bytestring"); + } + } + + return x; +}; + +conversions$1["USVString"] = function (V) { + const S = String(V); + const n = S.length; + const U = []; + for (let i = 0; i < n; ++i) { + const c = S.charCodeAt(i); + if (c < 0xD800 || c > 0xDFFF) { + U.push(String.fromCodePoint(c)); + } else if (0xDC00 <= c && c <= 0xDFFF) { + U.push(String.fromCodePoint(0xFFFD)); + } else { + if (i === n - 1) { + U.push(String.fromCodePoint(0xFFFD)); + } else { + const d = S.charCodeAt(i + 1); + if (0xDC00 <= d && d <= 0xDFFF) { + const a = c & 0x3FF; + const b = d & 0x3FF; + U.push(String.fromCodePoint((2 << 15) + (2 << 9) * a + b)); + ++i; + } else { + U.push(String.fromCodePoint(0xFFFD)); + } + } + } + } + + return U.join(''); +}; + +conversions$1["Date"] = function (V, opts) { + if (!(V instanceof Date)) { + throw new TypeError("Argument is not a Date object"); + } + if (isNaN(V)) { + return undefined; + } + + return V; +}; + +conversions$1["RegExp"] = function (V, opts) { + if (!(V instanceof RegExp)) { + V = new RegExp(V); + } + + return V; +}; + +var utils = {exports: {}}; + +(function (module) { + + module.exports.mixin = function mixin(target, source) { + const keys = Object.getOwnPropertyNames(source); + for (let i = 0; i < keys.length; ++i) { + Object.defineProperty(target, keys[i], Object.getOwnPropertyDescriptor(source, keys[i])); + } + }; + + module.exports.wrapperSymbol = Symbol("wrapper"); + module.exports.implSymbol = Symbol("impl"); + + module.exports.wrapperForImpl = function (impl) { + return impl[module.exports.wrapperSymbol]; + }; + + module.exports.implForWrapper = function (wrapper) { + return wrapper[module.exports.implSymbol]; + }; +} (utils)); + +var utilsExports = utils.exports; + +var URLImpl = {}; + +var urlStateMachine = {exports: {}}; + +var tr46 = {}; + +var require$$1 = [ + [ + [ + 0, + 44 + ], + "disallowed_STD3_valid" + ], + [ + [ + 45, + 46 + ], + "valid" + ], + [ + [ + 47, + 47 + ], + "disallowed_STD3_valid" + ], + [ + [ + 48, + 57 + ], + "valid" + ], + [ + [ + 58, + 64 + ], + "disallowed_STD3_valid" + ], + [ + [ + 65, + 65 + ], + "mapped", + [ + 97 + ] + ], + [ + [ + 66, + 66 + ], + "mapped", + [ + 98 + ] + ], + [ + [ + 67, + 67 + ], + "mapped", + [ + 99 + ] + ], + [ + [ + 68, + 68 + ], + "mapped", + [ + 100 + ] + ], + [ + [ + 69, + 69 + ], + "mapped", + [ + 101 + ] + ], + [ + [ + 70, + 70 + ], + "mapped", + [ + 102 + ] + ], + [ + [ + 71, + 71 + ], + "mapped", + [ + 103 + ] + ], + [ + [ + 72, + 72 + ], + "mapped", + [ + 104 + ] + ], + [ + [ + 73, + 73 + ], + "mapped", + [ + 105 + ] + ], + [ + [ + 74, + 74 + ], + "mapped", + [ + 106 + ] + ], + [ + [ + 75, + 75 + ], + "mapped", + [ + 107 + ] + ], + [ + [ + 76, + 76 + ], + "mapped", + [ + 108 + ] + ], + [ + [ + 77, + 77 + ], + "mapped", + [ + 109 + ] + ], + [ + [ + 78, + 78 + ], + "mapped", + [ + 110 + ] + ], + [ + [ + 79, + 79 + ], + "mapped", + [ + 111 + ] + ], + [ + [ + 80, + 80 + ], + "mapped", + [ + 112 + ] + ], + [ + [ + 81, + 81 + ], + "mapped", + [ + 113 + ] + ], + [ + [ + 82, + 82 + ], + "mapped", + [ + 114 + ] + ], + [ + [ + 83, + 83 + ], + "mapped", + [ + 115 + ] + ], + [ + [ + 84, + 84 + ], + "mapped", + [ + 116 + ] + ], + [ + [ + 85, + 85 + ], + "mapped", + [ + 117 + ] + ], + [ + [ + 86, + 86 + ], + "mapped", + [ + 118 + ] + ], + [ + [ + 87, + 87 + ], + "mapped", + [ + 119 + ] + ], + [ + [ + 88, + 88 + ], + "mapped", + [ + 120 + ] + ], + [ + [ + 89, + 89 + ], + "mapped", + [ + 121 + ] + ], + [ + [ + 90, + 90 + ], + "mapped", + [ + 122 + ] + ], + [ + [ + 91, + 96 + ], + "disallowed_STD3_valid" + ], + [ + [ + 97, + 122 + ], + "valid" + ], + [ + [ + 123, + 127 + ], + "disallowed_STD3_valid" + ], + [ + [ + 128, + 159 + ], + "disallowed" + ], + [ + [ + 160, + 160 + ], + "disallowed_STD3_mapped", + [ + 32 + ] + ], + [ + [ + 161, + 167 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 168, + 168 + ], + "disallowed_STD3_mapped", + [ + 32, + 776 + ] + ], + [ + [ + 169, + 169 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 170, + 170 + ], + "mapped", + [ + 97 + ] + ], + [ + [ + 171, + 172 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 173, + 173 + ], + "ignored" + ], + [ + [ + 174, + 174 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 175, + 175 + ], + "disallowed_STD3_mapped", + [ + 32, + 772 + ] + ], + [ + [ + 176, + 177 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 178, + 178 + ], + "mapped", + [ + 50 + ] + ], + [ + [ + 179, + 179 + ], + "mapped", + [ + 51 + ] + ], + [ + [ + 180, + 180 + ], + "disallowed_STD3_mapped", + [ + 32, + 769 + ] + ], + [ + [ + 181, + 181 + ], + "mapped", + [ + 956 + ] + ], + [ + [ + 182, + 182 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 183, + 183 + ], + "valid" + ], + [ + [ + 184, + 184 + ], + "disallowed_STD3_mapped", + [ + 32, + 807 + ] + ], + [ + [ + 185, + 185 + ], + "mapped", + [ + 49 + ] + ], + [ + [ + 186, + 186 + ], + "mapped", + [ + 111 + ] + ], + [ + [ + 187, + 187 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 188, + 188 + ], + "mapped", + [ + 49, + 8260, + 52 + ] + ], + [ + [ + 189, + 189 + ], + "mapped", + [ + 49, + 8260, + 50 + ] + ], + [ + [ + 190, + 190 + ], + "mapped", + [ + 51, + 8260, + 52 + ] + ], + [ + [ + 191, + 191 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 192, + 192 + ], + "mapped", + [ + 224 + ] + ], + [ + [ + 193, + 193 + ], + "mapped", + [ + 225 + ] + ], + [ + [ + 194, + 194 + ], + "mapped", + [ + 226 + ] + ], + [ + [ + 195, + 195 + ], + "mapped", + [ + 227 + ] + ], + [ + [ + 196, + 196 + ], + "mapped", + [ + 228 + ] + ], + [ + [ + 197, + 197 + ], + "mapped", + [ + 229 + ] + ], + [ + [ + 198, + 198 + ], + "mapped", + [ + 230 + ] + ], + [ + [ + 199, + 199 + ], + "mapped", + [ + 231 + ] + ], + [ + [ + 200, + 200 + ], + "mapped", + [ + 232 + ] + ], + [ + [ + 201, + 201 + ], + "mapped", + [ + 233 + ] + ], + [ + [ + 202, + 202 + ], + "mapped", + [ + 234 + ] + ], + [ + [ + 203, + 203 + ], + "mapped", + [ + 235 + ] + ], + [ + [ + 204, + 204 + ], + "mapped", + [ + 236 + ] + ], + [ + [ + 205, + 205 + ], + "mapped", + [ + 237 + ] + ], + [ + [ + 206, + 206 + ], + "mapped", + [ + 238 + ] + ], + [ + [ + 207, + 207 + ], + "mapped", + [ + 239 + ] + ], + [ + [ + 208, + 208 + ], + "mapped", + [ + 240 + ] + ], + [ + [ + 209, + 209 + ], + "mapped", + [ + 241 + ] + ], + [ + [ + 210, + 210 + ], + "mapped", + [ + 242 + ] + ], + [ + [ + 211, + 211 + ], + "mapped", + [ + 243 + ] + ], + [ + [ + 212, + 212 + ], + "mapped", + [ + 244 + ] + ], + [ + [ + 213, + 213 + ], + "mapped", + [ + 245 + ] + ], + [ + [ + 214, + 214 + ], + "mapped", + [ + 246 + ] + ], + [ + [ + 215, + 215 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 216, + 216 + ], + "mapped", + [ + 248 + ] + ], + [ + [ + 217, + 217 + ], + "mapped", + [ + 249 + ] + ], + [ + [ + 218, + 218 + ], + "mapped", + [ + 250 + ] + ], + [ + [ + 219, + 219 + ], + "mapped", + [ + 251 + ] + ], + [ + [ + 220, + 220 + ], + "mapped", + [ + 252 + ] + ], + [ + [ + 221, + 221 + ], + "mapped", + [ + 253 + ] + ], + [ + [ + 222, + 222 + ], + "mapped", + [ + 254 + ] + ], + [ + [ + 223, + 223 + ], + "deviation", + [ + 115, + 115 + ] + ], + [ + [ + 224, + 246 + ], + "valid" + ], + [ + [ + 247, + 247 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 248, + 255 + ], + "valid" + ], + [ + [ + 256, + 256 + ], + "mapped", + [ + 257 + ] + ], + [ + [ + 257, + 257 + ], + "valid" + ], + [ + [ + 258, + 258 + ], + "mapped", + [ + 259 + ] + ], + [ + [ + 259, + 259 + ], + "valid" + ], + [ + [ + 260, + 260 + ], + "mapped", + [ + 261 + ] + ], + [ + [ + 261, + 261 + ], + "valid" + ], + [ + [ + 262, + 262 + ], + "mapped", + [ + 263 + ] + ], + [ + [ + 263, + 263 + ], + "valid" + ], + [ + [ + 264, + 264 + ], + "mapped", + [ + 265 + ] + ], + [ + [ + 265, + 265 + ], + "valid" + ], + [ + [ + 266, + 266 + ], + "mapped", + [ + 267 + ] + ], + [ + [ + 267, + 267 + ], + "valid" + ], + [ + [ + 268, + 268 + ], + "mapped", + [ + 269 + ] + ], + [ + [ + 269, + 269 + ], + "valid" + ], + [ + [ + 270, + 270 + ], + "mapped", + [ + 271 + ] + ], + [ + [ + 271, + 271 + ], + "valid" + ], + [ + [ + 272, + 272 + ], + "mapped", + [ + 273 + ] + ], + [ + [ + 273, + 273 + ], + "valid" + ], + [ + [ + 274, + 274 + ], + "mapped", + [ + 275 + ] + ], + [ + [ + 275, + 275 + ], + "valid" + ], + [ + [ + 276, + 276 + ], + "mapped", + [ + 277 + ] + ], + [ + [ + 277, + 277 + ], + "valid" + ], + [ + [ + 278, + 278 + ], + "mapped", + [ + 279 + ] + ], + [ + [ + 279, + 279 + ], + "valid" + ], + [ + [ + 280, + 280 + ], + "mapped", + [ + 281 + ] + ], + [ + [ + 281, + 281 + ], + "valid" + ], + [ + [ + 282, + 282 + ], + "mapped", + [ + 283 + ] + ], + [ + [ + 283, + 283 + ], + "valid" + ], + [ + [ + 284, + 284 + ], + "mapped", + [ + 285 + ] + ], + [ + [ + 285, + 285 + ], + "valid" + ], + [ + [ + 286, + 286 + ], + "mapped", + [ + 287 + ] + ], + [ + [ + 287, + 287 + ], + "valid" + ], + [ + [ + 288, + 288 + ], + "mapped", + [ + 289 + ] + ], + [ + [ + 289, + 289 + ], + "valid" + ], + [ + [ + 290, + 290 + ], + "mapped", + [ + 291 + ] + ], + [ + [ + 291, + 291 + ], + "valid" + ], + [ + [ + 292, + 292 + ], + "mapped", + [ + 293 + ] + ], + [ + [ + 293, + 293 + ], + "valid" + ], + [ + [ + 294, + 294 + ], + "mapped", + [ + 295 + ] + ], + [ + [ + 295, + 295 + ], + "valid" + ], + [ + [ + 296, + 296 + ], + "mapped", + [ + 297 + ] + ], + [ + [ + 297, + 297 + ], + "valid" + ], + [ + [ + 298, + 298 + ], + "mapped", + [ + 299 + ] + ], + [ + [ + 299, + 299 + ], + "valid" + ], + [ + [ + 300, + 300 + ], + "mapped", + [ + 301 + ] + ], + [ + [ + 301, + 301 + ], + "valid" + ], + [ + [ + 302, + 302 + ], + "mapped", + [ + 303 + ] + ], + [ + [ + 303, + 303 + ], + "valid" + ], + [ + [ + 304, + 304 + ], + "mapped", + [ + 105, + 775 + ] + ], + [ + [ + 305, + 305 + ], + "valid" + ], + [ + [ + 306, + 307 + ], + "mapped", + [ + 105, + 106 + ] + ], + [ + [ + 308, + 308 + ], + "mapped", + [ + 309 + ] + ], + [ + [ + 309, + 309 + ], + "valid" + ], + [ + [ + 310, + 310 + ], + "mapped", + [ + 311 + ] + ], + [ + [ + 311, + 312 + ], + "valid" + ], + [ + [ + 313, + 313 + ], + "mapped", + [ + 314 + ] + ], + [ + [ + 314, + 314 + ], + "valid" + ], + [ + [ + 315, + 315 + ], + "mapped", + [ + 316 + ] + ], + [ + [ + 316, + 316 + ], + "valid" + ], + [ + [ + 317, + 317 + ], + "mapped", + [ + 318 + ] + ], + [ + [ + 318, + 318 + ], + "valid" + ], + [ + [ + 319, + 320 + ], + "mapped", + [ + 108, + 183 + ] + ], + [ + [ + 321, + 321 + ], + "mapped", + [ + 322 + ] + ], + [ + [ + 322, + 322 + ], + "valid" + ], + [ + [ + 323, + 323 + ], + "mapped", + [ + 324 + ] + ], + [ + [ + 324, + 324 + ], + "valid" + ], + [ + [ + 325, + 325 + ], + "mapped", + [ + 326 + ] + ], + [ + [ + 326, + 326 + ], + "valid" + ], + [ + [ + 327, + 327 + ], + "mapped", + [ + 328 + ] + ], + [ + [ + 328, + 328 + ], + "valid" + ], + [ + [ + 329, + 329 + ], + "mapped", + [ + 700, + 110 + ] + ], + [ + [ + 330, + 330 + ], + "mapped", + [ + 331 + ] + ], + [ + [ + 331, + 331 + ], + "valid" + ], + [ + [ + 332, + 332 + ], + "mapped", + [ + 333 + ] + ], + [ + [ + 333, + 333 + ], + "valid" + ], + [ + [ + 334, + 334 + ], + "mapped", + [ + 335 + ] + ], + [ + [ + 335, + 335 + ], + "valid" + ], + [ + [ + 336, + 336 + ], + "mapped", + [ + 337 + ] + ], + [ + [ + 337, + 337 + ], + "valid" + ], + [ + [ + 338, + 338 + ], + "mapped", + [ + 339 + ] + ], + [ + [ + 339, + 339 + ], + "valid" + ], + [ + [ + 340, + 340 + ], + "mapped", + [ + 341 + ] + ], + [ + [ + 341, + 341 + ], + "valid" + ], + [ + [ + 342, + 342 + ], + "mapped", + [ + 343 + ] + ], + [ + [ + 343, + 343 + ], + "valid" + ], + [ + [ + 344, + 344 + ], + "mapped", + [ + 345 + ] + ], + [ + [ + 345, + 345 + ], + "valid" + ], + [ + [ + 346, + 346 + ], + "mapped", + [ + 347 + ] + ], + [ + [ + 347, + 347 + ], + "valid" + ], + [ + [ + 348, + 348 + ], + "mapped", + [ + 349 + ] + ], + [ + [ + 349, + 349 + ], + "valid" + ], + [ + [ + 350, + 350 + ], + "mapped", + [ + 351 + ] + ], + [ + [ + 351, + 351 + ], + "valid" + ], + [ + [ + 352, + 352 + ], + "mapped", + [ + 353 + ] + ], + [ + [ + 353, + 353 + ], + "valid" + ], + [ + [ + 354, + 354 + ], + "mapped", + [ + 355 + ] + ], + [ + [ + 355, + 355 + ], + "valid" + ], + [ + [ + 356, + 356 + ], + "mapped", + [ + 357 + ] + ], + [ + [ + 357, + 357 + ], + "valid" + ], + [ + [ + 358, + 358 + ], + "mapped", + [ + 359 + ] + ], + [ + [ + 359, + 359 + ], + "valid" + ], + [ + [ + 360, + 360 + ], + "mapped", + [ + 361 + ] + ], + [ + [ + 361, + 361 + ], + "valid" + ], + [ + [ + 362, + 362 + ], + "mapped", + [ + 363 + ] + ], + [ + [ + 363, + 363 + ], + "valid" + ], + [ + [ + 364, + 364 + ], + "mapped", + [ + 365 + ] + ], + [ + [ + 365, + 365 + ], + "valid" + ], + [ + [ + 366, + 366 + ], + "mapped", + [ + 367 + ] + ], + [ + [ + 367, + 367 + ], + "valid" + ], + [ + [ + 368, + 368 + ], + "mapped", + [ + 369 + ] + ], + [ + [ + 369, + 369 + ], + "valid" + ], + [ + [ + 370, + 370 + ], + "mapped", + [ + 371 + ] + ], + [ + [ + 371, + 371 + ], + "valid" + ], + [ + [ + 372, + 372 + ], + "mapped", + [ + 373 + ] + ], + [ + [ + 373, + 373 + ], + "valid" + ], + [ + [ + 374, + 374 + ], + "mapped", + [ + 375 + ] + ], + [ + [ + 375, + 375 + ], + "valid" + ], + [ + [ + 376, + 376 + ], + "mapped", + [ + 255 + ] + ], + [ + [ + 377, + 377 + ], + "mapped", + [ + 378 + ] + ], + [ + [ + 378, + 378 + ], + "valid" + ], + [ + [ + 379, + 379 + ], + "mapped", + [ + 380 + ] + ], + [ + [ + 380, + 380 + ], + "valid" + ], + [ + [ + 381, + 381 + ], + "mapped", + [ + 382 + ] + ], + [ + [ + 382, + 382 + ], + "valid" + ], + [ + [ + 383, + 383 + ], + "mapped", + [ + 115 + ] + ], + [ + [ + 384, + 384 + ], + "valid" + ], + [ + [ + 385, + 385 + ], + "mapped", + [ + 595 + ] + ], + [ + [ + 386, + 386 + ], + "mapped", + [ + 387 + ] + ], + [ + [ + 387, + 387 + ], + "valid" + ], + [ + [ + 388, + 388 + ], + "mapped", + [ + 389 + ] + ], + [ + [ + 389, + 389 + ], + "valid" + ], + [ + [ + 390, + 390 + ], + "mapped", + [ + 596 + ] + ], + [ + [ + 391, + 391 + ], + "mapped", + [ + 392 + ] + ], + [ + [ + 392, + 392 + ], + "valid" + ], + [ + [ + 393, + 393 + ], + "mapped", + [ + 598 + ] + ], + [ + [ + 394, + 394 + ], + "mapped", + [ + 599 + ] + ], + [ + [ + 395, + 395 + ], + "mapped", + [ + 396 + ] + ], + [ + [ + 396, + 397 + ], + "valid" + ], + [ + [ + 398, + 398 + ], + "mapped", + [ + 477 + ] + ], + [ + [ + 399, + 399 + ], + "mapped", + [ + 601 + ] + ], + [ + [ + 400, + 400 + ], + "mapped", + [ + 603 + ] + ], + [ + [ + 401, + 401 + ], + "mapped", + [ + 402 + ] + ], + [ + [ + 402, + 402 + ], + "valid" + ], + [ + [ + 403, + 403 + ], + "mapped", + [ + 608 + ] + ], + [ + [ + 404, + 404 + ], + "mapped", + [ + 611 + ] + ], + [ + [ + 405, + 405 + ], + "valid" + ], + [ + [ + 406, + 406 + ], + "mapped", + [ + 617 + ] + ], + [ + [ + 407, + 407 + ], + "mapped", + [ + 616 + ] + ], + [ + [ + 408, + 408 + ], + "mapped", + [ + 409 + ] + ], + [ + [ + 409, + 411 + ], + "valid" + ], + [ + [ + 412, + 412 + ], + "mapped", + [ + 623 + ] + ], + [ + [ + 413, + 413 + ], + "mapped", + [ + 626 + ] + ], + [ + [ + 414, + 414 + ], + "valid" + ], + [ + [ + 415, + 415 + ], + "mapped", + [ + 629 + ] + ], + [ + [ + 416, + 416 + ], + "mapped", + [ + 417 + ] + ], + [ + [ + 417, + 417 + ], + "valid" + ], + [ + [ + 418, + 418 + ], + "mapped", + [ + 419 + ] + ], + [ + [ + 419, + 419 + ], + "valid" + ], + [ + [ + 420, + 420 + ], + "mapped", + [ + 421 + ] + ], + [ + [ + 421, + 421 + ], + "valid" + ], + [ + [ + 422, + 422 + ], + "mapped", + [ + 640 + ] + ], + [ + [ + 423, + 423 + ], + "mapped", + [ + 424 + ] + ], + [ + [ + 424, + 424 + ], + "valid" + ], + [ + [ + 425, + 425 + ], + "mapped", + [ + 643 + ] + ], + [ + [ + 426, + 427 + ], + "valid" + ], + [ + [ + 428, + 428 + ], + "mapped", + [ + 429 + ] + ], + [ + [ + 429, + 429 + ], + "valid" + ], + [ + [ + 430, + 430 + ], + "mapped", + [ + 648 + ] + ], + [ + [ + 431, + 431 + ], + "mapped", + [ + 432 + ] + ], + [ + [ + 432, + 432 + ], + "valid" + ], + [ + [ + 433, + 433 + ], + "mapped", + [ + 650 + ] + ], + [ + [ + 434, + 434 + ], + "mapped", + [ + 651 + ] + ], + [ + [ + 435, + 435 + ], + "mapped", + [ + 436 + ] + ], + [ + [ + 436, + 436 + ], + "valid" + ], + [ + [ + 437, + 437 + ], + "mapped", + [ + 438 + ] + ], + [ + [ + 438, + 438 + ], + "valid" + ], + [ + [ + 439, + 439 + ], + "mapped", + [ + 658 + ] + ], + [ + [ + 440, + 440 + ], + "mapped", + [ + 441 + ] + ], + [ + [ + 441, + 443 + ], + "valid" + ], + [ + [ + 444, + 444 + ], + "mapped", + [ + 445 + ] + ], + [ + [ + 445, + 451 + ], + "valid" + ], + [ + [ + 452, + 454 + ], + "mapped", + [ + 100, + 382 + ] + ], + [ + [ + 455, + 457 + ], + "mapped", + [ + 108, + 106 + ] + ], + [ + [ + 458, + 460 + ], + "mapped", + [ + 110, + 106 + ] + ], + [ + [ + 461, + 461 + ], + "mapped", + [ + 462 + ] + ], + [ + [ + 462, + 462 + ], + "valid" + ], + [ + [ + 463, + 463 + ], + "mapped", + [ + 464 + ] + ], + [ + [ + 464, + 464 + ], + "valid" + ], + [ + [ + 465, + 465 + ], + "mapped", + [ + 466 + ] + ], + [ + [ + 466, + 466 + ], + "valid" + ], + [ + [ + 467, + 467 + ], + "mapped", + [ + 468 + ] + ], + [ + [ + 468, + 468 + ], + "valid" + ], + [ + [ + 469, + 469 + ], + "mapped", + [ + 470 + ] + ], + [ + [ + 470, + 470 + ], + "valid" + ], + [ + [ + 471, + 471 + ], + "mapped", + [ + 472 + ] + ], + [ + [ + 472, + 472 + ], + "valid" + ], + [ + [ + 473, + 473 + ], + "mapped", + [ + 474 + ] + ], + [ + [ + 474, + 474 + ], + "valid" + ], + [ + [ + 475, + 475 + ], + "mapped", + [ + 476 + ] + ], + [ + [ + 476, + 477 + ], + "valid" + ], + [ + [ + 478, + 478 + ], + "mapped", + [ + 479 + ] + ], + [ + [ + 479, + 479 + ], + "valid" + ], + [ + [ + 480, + 480 + ], + "mapped", + [ + 481 + ] + ], + [ + [ + 481, + 481 + ], + "valid" + ], + [ + [ + 482, + 482 + ], + "mapped", + [ + 483 + ] + ], + [ + [ + 483, + 483 + ], + "valid" + ], + [ + [ + 484, + 484 + ], + "mapped", + [ + 485 + ] + ], + [ + [ + 485, + 485 + ], + "valid" + ], + [ + [ + 486, + 486 + ], + "mapped", + [ + 487 + ] + ], + [ + [ + 487, + 487 + ], + "valid" + ], + [ + [ + 488, + 488 + ], + "mapped", + [ + 489 + ] + ], + [ + [ + 489, + 489 + ], + "valid" + ], + [ + [ + 490, + 490 + ], + "mapped", + [ + 491 + ] + ], + [ + [ + 491, + 491 + ], + "valid" + ], + [ + [ + 492, + 492 + ], + "mapped", + [ + 493 + ] + ], + [ + [ + 493, + 493 + ], + "valid" + ], + [ + [ + 494, + 494 + ], + "mapped", + [ + 495 + ] + ], + [ + [ + 495, + 496 + ], + "valid" + ], + [ + [ + 497, + 499 + ], + "mapped", + [ + 100, + 122 + ] + ], + [ + [ + 500, + 500 + ], + "mapped", + [ + 501 + ] + ], + [ + [ + 501, + 501 + ], + "valid" + ], + [ + [ + 502, + 502 + ], + "mapped", + [ + 405 + ] + ], + [ + [ + 503, + 503 + ], + "mapped", + [ + 447 + ] + ], + [ + [ + 504, + 504 + ], + "mapped", + [ + 505 + ] + ], + [ + [ + 505, + 505 + ], + "valid" + ], + [ + [ + 506, + 506 + ], + "mapped", + [ + 507 + ] + ], + [ + [ + 507, + 507 + ], + "valid" + ], + [ + [ + 508, + 508 + ], + "mapped", + [ + 509 + ] + ], + [ + [ + 509, + 509 + ], + "valid" + ], + [ + [ + 510, + 510 + ], + "mapped", + [ + 511 + ] + ], + [ + [ + 511, + 511 + ], + "valid" + ], + [ + [ + 512, + 512 + ], + "mapped", + [ + 513 + ] + ], + [ + [ + 513, + 513 + ], + "valid" + ], + [ + [ + 514, + 514 + ], + "mapped", + [ + 515 + ] + ], + [ + [ + 515, + 515 + ], + "valid" + ], + [ + [ + 516, + 516 + ], + "mapped", + [ + 517 + ] + ], + [ + [ + 517, + 517 + ], + "valid" + ], + [ + [ + 518, + 518 + ], + "mapped", + [ + 519 + ] + ], + [ + [ + 519, + 519 + ], + "valid" + ], + [ + [ + 520, + 520 + ], + "mapped", + [ + 521 + ] + ], + [ + [ + 521, + 521 + ], + "valid" + ], + [ + [ + 522, + 522 + ], + "mapped", + [ + 523 + ] + ], + [ + [ + 523, + 523 + ], + "valid" + ], + [ + [ + 524, + 524 + ], + "mapped", + [ + 525 + ] + ], + [ + [ + 525, + 525 + ], + "valid" + ], + [ + [ + 526, + 526 + ], + "mapped", + [ + 527 + ] + ], + [ + [ + 527, + 527 + ], + "valid" + ], + [ + [ + 528, + 528 + ], + "mapped", + [ + 529 + ] + ], + [ + [ + 529, + 529 + ], + "valid" + ], + [ + [ + 530, + 530 + ], + "mapped", + [ + 531 + ] + ], + [ + [ + 531, + 531 + ], + "valid" + ], + [ + [ + 532, + 532 + ], + "mapped", + [ + 533 + ] + ], + [ + [ + 533, + 533 + ], + "valid" + ], + [ + [ + 534, + 534 + ], + "mapped", + [ + 535 + ] + ], + [ + [ + 535, + 535 + ], + "valid" + ], + [ + [ + 536, + 536 + ], + "mapped", + [ + 537 + ] + ], + [ + [ + 537, + 537 + ], + "valid" + ], + [ + [ + 538, + 538 + ], + "mapped", + [ + 539 + ] + ], + [ + [ + 539, + 539 + ], + "valid" + ], + [ + [ + 540, + 540 + ], + "mapped", + [ + 541 + ] + ], + [ + [ + 541, + 541 + ], + "valid" + ], + [ + [ + 542, + 542 + ], + "mapped", + [ + 543 + ] + ], + [ + [ + 543, + 543 + ], + "valid" + ], + [ + [ + 544, + 544 + ], + "mapped", + [ + 414 + ] + ], + [ + [ + 545, + 545 + ], + "valid" + ], + [ + [ + 546, + 546 + ], + "mapped", + [ + 547 + ] + ], + [ + [ + 547, + 547 + ], + "valid" + ], + [ + [ + 548, + 548 + ], + "mapped", + [ + 549 + ] + ], + [ + [ + 549, + 549 + ], + "valid" + ], + [ + [ + 550, + 550 + ], + "mapped", + [ + 551 + ] + ], + [ + [ + 551, + 551 + ], + "valid" + ], + [ + [ + 552, + 552 + ], + "mapped", + [ + 553 + ] + ], + [ + [ + 553, + 553 + ], + "valid" + ], + [ + [ + 554, + 554 + ], + "mapped", + [ + 555 + ] + ], + [ + [ + 555, + 555 + ], + "valid" + ], + [ + [ + 556, + 556 + ], + "mapped", + [ + 557 + ] + ], + [ + [ + 557, + 557 + ], + "valid" + ], + [ + [ + 558, + 558 + ], + "mapped", + [ + 559 + ] + ], + [ + [ + 559, + 559 + ], + "valid" + ], + [ + [ + 560, + 560 + ], + "mapped", + [ + 561 + ] + ], + [ + [ + 561, + 561 + ], + "valid" + ], + [ + [ + 562, + 562 + ], + "mapped", + [ + 563 + ] + ], + [ + [ + 563, + 563 + ], + "valid" + ], + [ + [ + 564, + 566 + ], + "valid" + ], + [ + [ + 567, + 569 + ], + "valid" + ], + [ + [ + 570, + 570 + ], + "mapped", + [ + 11365 + ] + ], + [ + [ + 571, + 571 + ], + "mapped", + [ + 572 + ] + ], + [ + [ + 572, + 572 + ], + "valid" + ], + [ + [ + 573, + 573 + ], + "mapped", + [ + 410 + ] + ], + [ + [ + 574, + 574 + ], + "mapped", + [ + 11366 + ] + ], + [ + [ + 575, + 576 + ], + "valid" + ], + [ + [ + 577, + 577 + ], + "mapped", + [ + 578 + ] + ], + [ + [ + 578, + 578 + ], + "valid" + ], + [ + [ + 579, + 579 + ], + "mapped", + [ + 384 + ] + ], + [ + [ + 580, + 580 + ], + "mapped", + [ + 649 + ] + ], + [ + [ + 581, + 581 + ], + "mapped", + [ + 652 + ] + ], + [ + [ + 582, + 582 + ], + "mapped", + [ + 583 + ] + ], + [ + [ + 583, + 583 + ], + "valid" + ], + [ + [ + 584, + 584 + ], + "mapped", + [ + 585 + ] + ], + [ + [ + 585, + 585 + ], + "valid" + ], + [ + [ + 586, + 586 + ], + "mapped", + [ + 587 + ] + ], + [ + [ + 587, + 587 + ], + "valid" + ], + [ + [ + 588, + 588 + ], + "mapped", + [ + 589 + ] + ], + [ + [ + 589, + 589 + ], + "valid" + ], + [ + [ + 590, + 590 + ], + "mapped", + [ + 591 + ] + ], + [ + [ + 591, + 591 + ], + "valid" + ], + [ + [ + 592, + 680 + ], + "valid" + ], + [ + [ + 681, + 685 + ], + "valid" + ], + [ + [ + 686, + 687 + ], + "valid" + ], + [ + [ + 688, + 688 + ], + "mapped", + [ + 104 + ] + ], + [ + [ + 689, + 689 + ], + "mapped", + [ + 614 + ] + ], + [ + [ + 690, + 690 + ], + "mapped", + [ + 106 + ] + ], + [ + [ + 691, + 691 + ], + "mapped", + [ + 114 + ] + ], + [ + [ + 692, + 692 + ], + "mapped", + [ + 633 + ] + ], + [ + [ + 693, + 693 + ], + "mapped", + [ + 635 + ] + ], + [ + [ + 694, + 694 + ], + "mapped", + [ + 641 + ] + ], + [ + [ + 695, + 695 + ], + "mapped", + [ + 119 + ] + ], + [ + [ + 696, + 696 + ], + "mapped", + [ + 121 + ] + ], + [ + [ + 697, + 705 + ], + "valid" + ], + [ + [ + 706, + 709 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 710, + 721 + ], + "valid" + ], + [ + [ + 722, + 727 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 728, + 728 + ], + "disallowed_STD3_mapped", + [ + 32, + 774 + ] + ], + [ + [ + 729, + 729 + ], + "disallowed_STD3_mapped", + [ + 32, + 775 + ] + ], + [ + [ + 730, + 730 + ], + "disallowed_STD3_mapped", + [ + 32, + 778 + ] + ], + [ + [ + 731, + 731 + ], + "disallowed_STD3_mapped", + [ + 32, + 808 + ] + ], + [ + [ + 732, + 732 + ], + "disallowed_STD3_mapped", + [ + 32, + 771 + ] + ], + [ + [ + 733, + 733 + ], + "disallowed_STD3_mapped", + [ + 32, + 779 + ] + ], + [ + [ + 734, + 734 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 735, + 735 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 736, + 736 + ], + "mapped", + [ + 611 + ] + ], + [ + [ + 737, + 737 + ], + "mapped", + [ + 108 + ] + ], + [ + [ + 738, + 738 + ], + "mapped", + [ + 115 + ] + ], + [ + [ + 739, + 739 + ], + "mapped", + [ + 120 + ] + ], + [ + [ + 740, + 740 + ], + "mapped", + [ + 661 + ] + ], + [ + [ + 741, + 745 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 746, + 747 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 748, + 748 + ], + "valid" + ], + [ + [ + 749, + 749 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 750, + 750 + ], + "valid" + ], + [ + [ + 751, + 767 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 768, + 831 + ], + "valid" + ], + [ + [ + 832, + 832 + ], + "mapped", + [ + 768 + ] + ], + [ + [ + 833, + 833 + ], + "mapped", + [ + 769 + ] + ], + [ + [ + 834, + 834 + ], + "valid" + ], + [ + [ + 835, + 835 + ], + "mapped", + [ + 787 + ] + ], + [ + [ + 836, + 836 + ], + "mapped", + [ + 776, + 769 + ] + ], + [ + [ + 837, + 837 + ], + "mapped", + [ + 953 + ] + ], + [ + [ + 838, + 846 + ], + "valid" + ], + [ + [ + 847, + 847 + ], + "ignored" + ], + [ + [ + 848, + 855 + ], + "valid" + ], + [ + [ + 856, + 860 + ], + "valid" + ], + [ + [ + 861, + 863 + ], + "valid" + ], + [ + [ + 864, + 865 + ], + "valid" + ], + [ + [ + 866, + 866 + ], + "valid" + ], + [ + [ + 867, + 879 + ], + "valid" + ], + [ + [ + 880, + 880 + ], + "mapped", + [ + 881 + ] + ], + [ + [ + 881, + 881 + ], + "valid" + ], + [ + [ + 882, + 882 + ], + "mapped", + [ + 883 + ] + ], + [ + [ + 883, + 883 + ], + "valid" + ], + [ + [ + 884, + 884 + ], + "mapped", + [ + 697 + ] + ], + [ + [ + 885, + 885 + ], + "valid" + ], + [ + [ + 886, + 886 + ], + "mapped", + [ + 887 + ] + ], + [ + [ + 887, + 887 + ], + "valid" + ], + [ + [ + 888, + 889 + ], + "disallowed" + ], + [ + [ + 890, + 890 + ], + "disallowed_STD3_mapped", + [ + 32, + 953 + ] + ], + [ + [ + 891, + 893 + ], + "valid" + ], + [ + [ + 894, + 894 + ], + "disallowed_STD3_mapped", + [ + 59 + ] + ], + [ + [ + 895, + 895 + ], + "mapped", + [ + 1011 + ] + ], + [ + [ + 896, + 899 + ], + "disallowed" + ], + [ + [ + 900, + 900 + ], + "disallowed_STD3_mapped", + [ + 32, + 769 + ] + ], + [ + [ + 901, + 901 + ], + "disallowed_STD3_mapped", + [ + 32, + 776, + 769 + ] + ], + [ + [ + 902, + 902 + ], + "mapped", + [ + 940 + ] + ], + [ + [ + 903, + 903 + ], + "mapped", + [ + 183 + ] + ], + [ + [ + 904, + 904 + ], + "mapped", + [ + 941 + ] + ], + [ + [ + 905, + 905 + ], + "mapped", + [ + 942 + ] + ], + [ + [ + 906, + 906 + ], + "mapped", + [ + 943 + ] + ], + [ + [ + 907, + 907 + ], + "disallowed" + ], + [ + [ + 908, + 908 + ], + "mapped", + [ + 972 + ] + ], + [ + [ + 909, + 909 + ], + "disallowed" + ], + [ + [ + 910, + 910 + ], + "mapped", + [ + 973 + ] + ], + [ + [ + 911, + 911 + ], + "mapped", + [ + 974 + ] + ], + [ + [ + 912, + 912 + ], + "valid" + ], + [ + [ + 913, + 913 + ], + "mapped", + [ + 945 + ] + ], + [ + [ + 914, + 914 + ], + "mapped", + [ + 946 + ] + ], + [ + [ + 915, + 915 + ], + "mapped", + [ + 947 + ] + ], + [ + [ + 916, + 916 + ], + "mapped", + [ + 948 + ] + ], + [ + [ + 917, + 917 + ], + "mapped", + [ + 949 + ] + ], + [ + [ + 918, + 918 + ], + "mapped", + [ + 950 + ] + ], + [ + [ + 919, + 919 + ], + "mapped", + [ + 951 + ] + ], + [ + [ + 920, + 920 + ], + "mapped", + [ + 952 + ] + ], + [ + [ + 921, + 921 + ], + "mapped", + [ + 953 + ] + ], + [ + [ + 922, + 922 + ], + "mapped", + [ + 954 + ] + ], + [ + [ + 923, + 923 + ], + "mapped", + [ + 955 + ] + ], + [ + [ + 924, + 924 + ], + "mapped", + [ + 956 + ] + ], + [ + [ + 925, + 925 + ], + "mapped", + [ + 957 + ] + ], + [ + [ + 926, + 926 + ], + "mapped", + [ + 958 + ] + ], + [ + [ + 927, + 927 + ], + "mapped", + [ + 959 + ] + ], + [ + [ + 928, + 928 + ], + "mapped", + [ + 960 + ] + ], + [ + [ + 929, + 929 + ], + "mapped", + [ + 961 + ] + ], + [ + [ + 930, + 930 + ], + "disallowed" + ], + [ + [ + 931, + 931 + ], + "mapped", + [ + 963 + ] + ], + [ + [ + 932, + 932 + ], + "mapped", + [ + 964 + ] + ], + [ + [ + 933, + 933 + ], + "mapped", + [ + 965 + ] + ], + [ + [ + 934, + 934 + ], + "mapped", + [ + 966 + ] + ], + [ + [ + 935, + 935 + ], + "mapped", + [ + 967 + ] + ], + [ + [ + 936, + 936 + ], + "mapped", + [ + 968 + ] + ], + [ + [ + 937, + 937 + ], + "mapped", + [ + 969 + ] + ], + [ + [ + 938, + 938 + ], + "mapped", + [ + 970 + ] + ], + [ + [ + 939, + 939 + ], + "mapped", + [ + 971 + ] + ], + [ + [ + 940, + 961 + ], + "valid" + ], + [ + [ + 962, + 962 + ], + "deviation", + [ + 963 + ] + ], + [ + [ + 963, + 974 + ], + "valid" + ], + [ + [ + 975, + 975 + ], + "mapped", + [ + 983 + ] + ], + [ + [ + 976, + 976 + ], + "mapped", + [ + 946 + ] + ], + [ + [ + 977, + 977 + ], + "mapped", + [ + 952 + ] + ], + [ + [ + 978, + 978 + ], + "mapped", + [ + 965 + ] + ], + [ + [ + 979, + 979 + ], + "mapped", + [ + 973 + ] + ], + [ + [ + 980, + 980 + ], + "mapped", + [ + 971 + ] + ], + [ + [ + 981, + 981 + ], + "mapped", + [ + 966 + ] + ], + [ + [ + 982, + 982 + ], + "mapped", + [ + 960 + ] + ], + [ + [ + 983, + 983 + ], + "valid" + ], + [ + [ + 984, + 984 + ], + "mapped", + [ + 985 + ] + ], + [ + [ + 985, + 985 + ], + "valid" + ], + [ + [ + 986, + 986 + ], + "mapped", + [ + 987 + ] + ], + [ + [ + 987, + 987 + ], + "valid" + ], + [ + [ + 988, + 988 + ], + "mapped", + [ + 989 + ] + ], + [ + [ + 989, + 989 + ], + "valid" + ], + [ + [ + 990, + 990 + ], + "mapped", + [ + 991 + ] + ], + [ + [ + 991, + 991 + ], + "valid" + ], + [ + [ + 992, + 992 + ], + "mapped", + [ + 993 + ] + ], + [ + [ + 993, + 993 + ], + "valid" + ], + [ + [ + 994, + 994 + ], + "mapped", + [ + 995 + ] + ], + [ + [ + 995, + 995 + ], + "valid" + ], + [ + [ + 996, + 996 + ], + "mapped", + [ + 997 + ] + ], + [ + [ + 997, + 997 + ], + "valid" + ], + [ + [ + 998, + 998 + ], + "mapped", + [ + 999 + ] + ], + [ + [ + 999, + 999 + ], + "valid" + ], + [ + [ + 1000, + 1000 + ], + "mapped", + [ + 1001 + ] + ], + [ + [ + 1001, + 1001 + ], + "valid" + ], + [ + [ + 1002, + 1002 + ], + "mapped", + [ + 1003 + ] + ], + [ + [ + 1003, + 1003 + ], + "valid" + ], + [ + [ + 1004, + 1004 + ], + "mapped", + [ + 1005 + ] + ], + [ + [ + 1005, + 1005 + ], + "valid" + ], + [ + [ + 1006, + 1006 + ], + "mapped", + [ + 1007 + ] + ], + [ + [ + 1007, + 1007 + ], + "valid" + ], + [ + [ + 1008, + 1008 + ], + "mapped", + [ + 954 + ] + ], + [ + [ + 1009, + 1009 + ], + "mapped", + [ + 961 + ] + ], + [ + [ + 1010, + 1010 + ], + "mapped", + [ + 963 + ] + ], + [ + [ + 1011, + 1011 + ], + "valid" + ], + [ + [ + 1012, + 1012 + ], + "mapped", + [ + 952 + ] + ], + [ + [ + 1013, + 1013 + ], + "mapped", + [ + 949 + ] + ], + [ + [ + 1014, + 1014 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 1015, + 1015 + ], + "mapped", + [ + 1016 + ] + ], + [ + [ + 1016, + 1016 + ], + "valid" + ], + [ + [ + 1017, + 1017 + ], + "mapped", + [ + 963 + ] + ], + [ + [ + 1018, + 1018 + ], + "mapped", + [ + 1019 + ] + ], + [ + [ + 1019, + 1019 + ], + "valid" + ], + [ + [ + 1020, + 1020 + ], + "valid" + ], + [ + [ + 1021, + 1021 + ], + "mapped", + [ + 891 + ] + ], + [ + [ + 1022, + 1022 + ], + "mapped", + [ + 892 + ] + ], + [ + [ + 1023, + 1023 + ], + "mapped", + [ + 893 + ] + ], + [ + [ + 1024, + 1024 + ], + "mapped", + [ + 1104 + ] + ], + [ + [ + 1025, + 1025 + ], + "mapped", + [ + 1105 + ] + ], + [ + [ + 1026, + 1026 + ], + "mapped", + [ + 1106 + ] + ], + [ + [ + 1027, + 1027 + ], + "mapped", + [ + 1107 + ] + ], + [ + [ + 1028, + 1028 + ], + "mapped", + [ + 1108 + ] + ], + [ + [ + 1029, + 1029 + ], + "mapped", + [ + 1109 + ] + ], + [ + [ + 1030, + 1030 + ], + "mapped", + [ + 1110 + ] + ], + [ + [ + 1031, + 1031 + ], + "mapped", + [ + 1111 + ] + ], + [ + [ + 1032, + 1032 + ], + "mapped", + [ + 1112 + ] + ], + [ + [ + 1033, + 1033 + ], + "mapped", + [ + 1113 + ] + ], + [ + [ + 1034, + 1034 + ], + "mapped", + [ + 1114 + ] + ], + [ + [ + 1035, + 1035 + ], + "mapped", + [ + 1115 + ] + ], + [ + [ + 1036, + 1036 + ], + "mapped", + [ + 1116 + ] + ], + [ + [ + 1037, + 1037 + ], + "mapped", + [ + 1117 + ] + ], + [ + [ + 1038, + 1038 + ], + "mapped", + [ + 1118 + ] + ], + [ + [ + 1039, + 1039 + ], + "mapped", + [ + 1119 + ] + ], + [ + [ + 1040, + 1040 + ], + "mapped", + [ + 1072 + ] + ], + [ + [ + 1041, + 1041 + ], + "mapped", + [ + 1073 + ] + ], + [ + [ + 1042, + 1042 + ], + "mapped", + [ + 1074 + ] + ], + [ + [ + 1043, + 1043 + ], + "mapped", + [ + 1075 + ] + ], + [ + [ + 1044, + 1044 + ], + "mapped", + [ + 1076 + ] + ], + [ + [ + 1045, + 1045 + ], + "mapped", + [ + 1077 + ] + ], + [ + [ + 1046, + 1046 + ], + "mapped", + [ + 1078 + ] + ], + [ + [ + 1047, + 1047 + ], + "mapped", + [ + 1079 + ] + ], + [ + [ + 1048, + 1048 + ], + "mapped", + [ + 1080 + ] + ], + [ + [ + 1049, + 1049 + ], + "mapped", + [ + 1081 + ] + ], + [ + [ + 1050, + 1050 + ], + "mapped", + [ + 1082 + ] + ], + [ + [ + 1051, + 1051 + ], + "mapped", + [ + 1083 + ] + ], + [ + [ + 1052, + 1052 + ], + "mapped", + [ + 1084 + ] + ], + [ + [ + 1053, + 1053 + ], + "mapped", + [ + 1085 + ] + ], + [ + [ + 1054, + 1054 + ], + "mapped", + [ + 1086 + ] + ], + [ + [ + 1055, + 1055 + ], + "mapped", + [ + 1087 + ] + ], + [ + [ + 1056, + 1056 + ], + "mapped", + [ + 1088 + ] + ], + [ + [ + 1057, + 1057 + ], + "mapped", + [ + 1089 + ] + ], + [ + [ + 1058, + 1058 + ], + "mapped", + [ + 1090 + ] + ], + [ + [ + 1059, + 1059 + ], + "mapped", + [ + 1091 + ] + ], + [ + [ + 1060, + 1060 + ], + "mapped", + [ + 1092 + ] + ], + [ + [ + 1061, + 1061 + ], + "mapped", + [ + 1093 + ] + ], + [ + [ + 1062, + 1062 + ], + "mapped", + [ + 1094 + ] + ], + [ + [ + 1063, + 1063 + ], + "mapped", + [ + 1095 + ] + ], + [ + [ + 1064, + 1064 + ], + "mapped", + [ + 1096 + ] + ], + [ + [ + 1065, + 1065 + ], + "mapped", + [ + 1097 + ] + ], + [ + [ + 1066, + 1066 + ], + "mapped", + [ + 1098 + ] + ], + [ + [ + 1067, + 1067 + ], + "mapped", + [ + 1099 + ] + ], + [ + [ + 1068, + 1068 + ], + "mapped", + [ + 1100 + ] + ], + [ + [ + 1069, + 1069 + ], + "mapped", + [ + 1101 + ] + ], + [ + [ + 1070, + 1070 + ], + "mapped", + [ + 1102 + ] + ], + [ + [ + 1071, + 1071 + ], + "mapped", + [ + 1103 + ] + ], + [ + [ + 1072, + 1103 + ], + "valid" + ], + [ + [ + 1104, + 1104 + ], + "valid" + ], + [ + [ + 1105, + 1116 + ], + "valid" + ], + [ + [ + 1117, + 1117 + ], + "valid" + ], + [ + [ + 1118, + 1119 + ], + "valid" + ], + [ + [ + 1120, + 1120 + ], + "mapped", + [ + 1121 + ] + ], + [ + [ + 1121, + 1121 + ], + "valid" + ], + [ + [ + 1122, + 1122 + ], + "mapped", + [ + 1123 + ] + ], + [ + [ + 1123, + 1123 + ], + "valid" + ], + [ + [ + 1124, + 1124 + ], + "mapped", + [ + 1125 + ] + ], + [ + [ + 1125, + 1125 + ], + "valid" + ], + [ + [ + 1126, + 1126 + ], + "mapped", + [ + 1127 + ] + ], + [ + [ + 1127, + 1127 + ], + "valid" + ], + [ + [ + 1128, + 1128 + ], + "mapped", + [ + 1129 + ] + ], + [ + [ + 1129, + 1129 + ], + "valid" + ], + [ + [ + 1130, + 1130 + ], + "mapped", + [ + 1131 + ] + ], + [ + [ + 1131, + 1131 + ], + "valid" + ], + [ + [ + 1132, + 1132 + ], + "mapped", + [ + 1133 + ] + ], + [ + [ + 1133, + 1133 + ], + "valid" + ], + [ + [ + 1134, + 1134 + ], + "mapped", + [ + 1135 + ] + ], + [ + [ + 1135, + 1135 + ], + "valid" + ], + [ + [ + 1136, + 1136 + ], + "mapped", + [ + 1137 + ] + ], + [ + [ + 1137, + 1137 + ], + "valid" + ], + [ + [ + 1138, + 1138 + ], + "mapped", + [ + 1139 + ] + ], + [ + [ + 1139, + 1139 + ], + "valid" + ], + [ + [ + 1140, + 1140 + ], + "mapped", + [ + 1141 + ] + ], + [ + [ + 1141, + 1141 + ], + "valid" + ], + [ + [ + 1142, + 1142 + ], + "mapped", + [ + 1143 + ] + ], + [ + [ + 1143, + 1143 + ], + "valid" + ], + [ + [ + 1144, + 1144 + ], + "mapped", + [ + 1145 + ] + ], + [ + [ + 1145, + 1145 + ], + "valid" + ], + [ + [ + 1146, + 1146 + ], + "mapped", + [ + 1147 + ] + ], + [ + [ + 1147, + 1147 + ], + "valid" + ], + [ + [ + 1148, + 1148 + ], + "mapped", + [ + 1149 + ] + ], + [ + [ + 1149, + 1149 + ], + "valid" + ], + [ + [ + 1150, + 1150 + ], + "mapped", + [ + 1151 + ] + ], + [ + [ + 1151, + 1151 + ], + "valid" + ], + [ + [ + 1152, + 1152 + ], + "mapped", + [ + 1153 + ] + ], + [ + [ + 1153, + 1153 + ], + "valid" + ], + [ + [ + 1154, + 1154 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 1155, + 1158 + ], + "valid" + ], + [ + [ + 1159, + 1159 + ], + "valid" + ], + [ + [ + 1160, + 1161 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 1162, + 1162 + ], + "mapped", + [ + 1163 + ] + ], + [ + [ + 1163, + 1163 + ], + "valid" + ], + [ + [ + 1164, + 1164 + ], + "mapped", + [ + 1165 + ] + ], + [ + [ + 1165, + 1165 + ], + "valid" + ], + [ + [ + 1166, + 1166 + ], + "mapped", + [ + 1167 + ] + ], + [ + [ + 1167, + 1167 + ], + "valid" + ], + [ + [ + 1168, + 1168 + ], + "mapped", + [ + 1169 + ] + ], + [ + [ + 1169, + 1169 + ], + "valid" + ], + [ + [ + 1170, + 1170 + ], + "mapped", + [ + 1171 + ] + ], + [ + [ + 1171, + 1171 + ], + "valid" + ], + [ + [ + 1172, + 1172 + ], + "mapped", + [ + 1173 + ] + ], + [ + [ + 1173, + 1173 + ], + "valid" + ], + [ + [ + 1174, + 1174 + ], + "mapped", + [ + 1175 + ] + ], + [ + [ + 1175, + 1175 + ], + "valid" + ], + [ + [ + 1176, + 1176 + ], + "mapped", + [ + 1177 + ] + ], + [ + [ + 1177, + 1177 + ], + "valid" + ], + [ + [ + 1178, + 1178 + ], + "mapped", + [ + 1179 + ] + ], + [ + [ + 1179, + 1179 + ], + "valid" + ], + [ + [ + 1180, + 1180 + ], + "mapped", + [ + 1181 + ] + ], + [ + [ + 1181, + 1181 + ], + "valid" + ], + [ + [ + 1182, + 1182 + ], + "mapped", + [ + 1183 + ] + ], + [ + [ + 1183, + 1183 + ], + "valid" + ], + [ + [ + 1184, + 1184 + ], + "mapped", + [ + 1185 + ] + ], + [ + [ + 1185, + 1185 + ], + "valid" + ], + [ + [ + 1186, + 1186 + ], + "mapped", + [ + 1187 + ] + ], + [ + [ + 1187, + 1187 + ], + "valid" + ], + [ + [ + 1188, + 1188 + ], + "mapped", + [ + 1189 + ] + ], + [ + [ + 1189, + 1189 + ], + "valid" + ], + [ + [ + 1190, + 1190 + ], + "mapped", + [ + 1191 + ] + ], + [ + [ + 1191, + 1191 + ], + "valid" + ], + [ + [ + 1192, + 1192 + ], + "mapped", + [ + 1193 + ] + ], + [ + [ + 1193, + 1193 + ], + "valid" + ], + [ + [ + 1194, + 1194 + ], + "mapped", + [ + 1195 + ] + ], + [ + [ + 1195, + 1195 + ], + "valid" + ], + [ + [ + 1196, + 1196 + ], + "mapped", + [ + 1197 + ] + ], + [ + [ + 1197, + 1197 + ], + "valid" + ], + [ + [ + 1198, + 1198 + ], + "mapped", + [ + 1199 + ] + ], + [ + [ + 1199, + 1199 + ], + "valid" + ], + [ + [ + 1200, + 1200 + ], + "mapped", + [ + 1201 + ] + ], + [ + [ + 1201, + 1201 + ], + "valid" + ], + [ + [ + 1202, + 1202 + ], + "mapped", + [ + 1203 + ] + ], + [ + [ + 1203, + 1203 + ], + "valid" + ], + [ + [ + 1204, + 1204 + ], + "mapped", + [ + 1205 + ] + ], + [ + [ + 1205, + 1205 + ], + "valid" + ], + [ + [ + 1206, + 1206 + ], + "mapped", + [ + 1207 + ] + ], + [ + [ + 1207, + 1207 + ], + "valid" + ], + [ + [ + 1208, + 1208 + ], + "mapped", + [ + 1209 + ] + ], + [ + [ + 1209, + 1209 + ], + "valid" + ], + [ + [ + 1210, + 1210 + ], + "mapped", + [ + 1211 + ] + ], + [ + [ + 1211, + 1211 + ], + "valid" + ], + [ + [ + 1212, + 1212 + ], + "mapped", + [ + 1213 + ] + ], + [ + [ + 1213, + 1213 + ], + "valid" + ], + [ + [ + 1214, + 1214 + ], + "mapped", + [ + 1215 + ] + ], + [ + [ + 1215, + 1215 + ], + "valid" + ], + [ + [ + 1216, + 1216 + ], + "disallowed" + ], + [ + [ + 1217, + 1217 + ], + "mapped", + [ + 1218 + ] + ], + [ + [ + 1218, + 1218 + ], + "valid" + ], + [ + [ + 1219, + 1219 + ], + "mapped", + [ + 1220 + ] + ], + [ + [ + 1220, + 1220 + ], + "valid" + ], + [ + [ + 1221, + 1221 + ], + "mapped", + [ + 1222 + ] + ], + [ + [ + 1222, + 1222 + ], + "valid" + ], + [ + [ + 1223, + 1223 + ], + "mapped", + [ + 1224 + ] + ], + [ + [ + 1224, + 1224 + ], + "valid" + ], + [ + [ + 1225, + 1225 + ], + "mapped", + [ + 1226 + ] + ], + [ + [ + 1226, + 1226 + ], + "valid" + ], + [ + [ + 1227, + 1227 + ], + "mapped", + [ + 1228 + ] + ], + [ + [ + 1228, + 1228 + ], + "valid" + ], + [ + [ + 1229, + 1229 + ], + "mapped", + [ + 1230 + ] + ], + [ + [ + 1230, + 1230 + ], + "valid" + ], + [ + [ + 1231, + 1231 + ], + "valid" + ], + [ + [ + 1232, + 1232 + ], + "mapped", + [ + 1233 + ] + ], + [ + [ + 1233, + 1233 + ], + "valid" + ], + [ + [ + 1234, + 1234 + ], + "mapped", + [ + 1235 + ] + ], + [ + [ + 1235, + 1235 + ], + "valid" + ], + [ + [ + 1236, + 1236 + ], + "mapped", + [ + 1237 + ] + ], + [ + [ + 1237, + 1237 + ], + "valid" + ], + [ + [ + 1238, + 1238 + ], + "mapped", + [ + 1239 + ] + ], + [ + [ + 1239, + 1239 + ], + "valid" + ], + [ + [ + 1240, + 1240 + ], + "mapped", + [ + 1241 + ] + ], + [ + [ + 1241, + 1241 + ], + "valid" + ], + [ + [ + 1242, + 1242 + ], + "mapped", + [ + 1243 + ] + ], + [ + [ + 1243, + 1243 + ], + "valid" + ], + [ + [ + 1244, + 1244 + ], + "mapped", + [ + 1245 + ] + ], + [ + [ + 1245, + 1245 + ], + "valid" + ], + [ + [ + 1246, + 1246 + ], + "mapped", + [ + 1247 + ] + ], + [ + [ + 1247, + 1247 + ], + "valid" + ], + [ + [ + 1248, + 1248 + ], + "mapped", + [ + 1249 + ] + ], + [ + [ + 1249, + 1249 + ], + "valid" + ], + [ + [ + 1250, + 1250 + ], + "mapped", + [ + 1251 + ] + ], + [ + [ + 1251, + 1251 + ], + "valid" + ], + [ + [ + 1252, + 1252 + ], + "mapped", + [ + 1253 + ] + ], + [ + [ + 1253, + 1253 + ], + "valid" + ], + [ + [ + 1254, + 1254 + ], + "mapped", + [ + 1255 + ] + ], + [ + [ + 1255, + 1255 + ], + "valid" + ], + [ + [ + 1256, + 1256 + ], + "mapped", + [ + 1257 + ] + ], + [ + [ + 1257, + 1257 + ], + "valid" + ], + [ + [ + 1258, + 1258 + ], + "mapped", + [ + 1259 + ] + ], + [ + [ + 1259, + 1259 + ], + "valid" + ], + [ + [ + 1260, + 1260 + ], + "mapped", + [ + 1261 + ] + ], + [ + [ + 1261, + 1261 + ], + "valid" + ], + [ + [ + 1262, + 1262 + ], + "mapped", + [ + 1263 + ] + ], + [ + [ + 1263, + 1263 + ], + "valid" + ], + [ + [ + 1264, + 1264 + ], + "mapped", + [ + 1265 + ] + ], + [ + [ + 1265, + 1265 + ], + "valid" + ], + [ + [ + 1266, + 1266 + ], + "mapped", + [ + 1267 + ] + ], + [ + [ + 1267, + 1267 + ], + "valid" + ], + [ + [ + 1268, + 1268 + ], + "mapped", + [ + 1269 + ] + ], + [ + [ + 1269, + 1269 + ], + "valid" + ], + [ + [ + 1270, + 1270 + ], + "mapped", + [ + 1271 + ] + ], + [ + [ + 1271, + 1271 + ], + "valid" + ], + [ + [ + 1272, + 1272 + ], + "mapped", + [ + 1273 + ] + ], + [ + [ + 1273, + 1273 + ], + "valid" + ], + [ + [ + 1274, + 1274 + ], + "mapped", + [ + 1275 + ] + ], + [ + [ + 1275, + 1275 + ], + "valid" + ], + [ + [ + 1276, + 1276 + ], + "mapped", + [ + 1277 + ] + ], + [ + [ + 1277, + 1277 + ], + "valid" + ], + [ + [ + 1278, + 1278 + ], + "mapped", + [ + 1279 + ] + ], + [ + [ + 1279, + 1279 + ], + "valid" + ], + [ + [ + 1280, + 1280 + ], + "mapped", + [ + 1281 + ] + ], + [ + [ + 1281, + 1281 + ], + "valid" + ], + [ + [ + 1282, + 1282 + ], + "mapped", + [ + 1283 + ] + ], + [ + [ + 1283, + 1283 + ], + "valid" + ], + [ + [ + 1284, + 1284 + ], + "mapped", + [ + 1285 + ] + ], + [ + [ + 1285, + 1285 + ], + "valid" + ], + [ + [ + 1286, + 1286 + ], + "mapped", + [ + 1287 + ] + ], + [ + [ + 1287, + 1287 + ], + "valid" + ], + [ + [ + 1288, + 1288 + ], + "mapped", + [ + 1289 + ] + ], + [ + [ + 1289, + 1289 + ], + "valid" + ], + [ + [ + 1290, + 1290 + ], + "mapped", + [ + 1291 + ] + ], + [ + [ + 1291, + 1291 + ], + "valid" + ], + [ + [ + 1292, + 1292 + ], + "mapped", + [ + 1293 + ] + ], + [ + [ + 1293, + 1293 + ], + "valid" + ], + [ + [ + 1294, + 1294 + ], + "mapped", + [ + 1295 + ] + ], + [ + [ + 1295, + 1295 + ], + "valid" + ], + [ + [ + 1296, + 1296 + ], + "mapped", + [ + 1297 + ] + ], + [ + [ + 1297, + 1297 + ], + "valid" + ], + [ + [ + 1298, + 1298 + ], + "mapped", + [ + 1299 + ] + ], + [ + [ + 1299, + 1299 + ], + "valid" + ], + [ + [ + 1300, + 1300 + ], + "mapped", + [ + 1301 + ] + ], + [ + [ + 1301, + 1301 + ], + "valid" + ], + [ + [ + 1302, + 1302 + ], + "mapped", + [ + 1303 + ] + ], + [ + [ + 1303, + 1303 + ], + "valid" + ], + [ + [ + 1304, + 1304 + ], + "mapped", + [ + 1305 + ] + ], + [ + [ + 1305, + 1305 + ], + "valid" + ], + [ + [ + 1306, + 1306 + ], + "mapped", + [ + 1307 + ] + ], + [ + [ + 1307, + 1307 + ], + "valid" + ], + [ + [ + 1308, + 1308 + ], + "mapped", + [ + 1309 + ] + ], + [ + [ + 1309, + 1309 + ], + "valid" + ], + [ + [ + 1310, + 1310 + ], + "mapped", + [ + 1311 + ] + ], + [ + [ + 1311, + 1311 + ], + "valid" + ], + [ + [ + 1312, + 1312 + ], + "mapped", + [ + 1313 + ] + ], + [ + [ + 1313, + 1313 + ], + "valid" + ], + [ + [ + 1314, + 1314 + ], + "mapped", + [ + 1315 + ] + ], + [ + [ + 1315, + 1315 + ], + "valid" + ], + [ + [ + 1316, + 1316 + ], + "mapped", + [ + 1317 + ] + ], + [ + [ + 1317, + 1317 + ], + "valid" + ], + [ + [ + 1318, + 1318 + ], + "mapped", + [ + 1319 + ] + ], + [ + [ + 1319, + 1319 + ], + "valid" + ], + [ + [ + 1320, + 1320 + ], + "mapped", + [ + 1321 + ] + ], + [ + [ + 1321, + 1321 + ], + "valid" + ], + [ + [ + 1322, + 1322 + ], + "mapped", + [ + 1323 + ] + ], + [ + [ + 1323, + 1323 + ], + "valid" + ], + [ + [ + 1324, + 1324 + ], + "mapped", + [ + 1325 + ] + ], + [ + [ + 1325, + 1325 + ], + "valid" + ], + [ + [ + 1326, + 1326 + ], + "mapped", + [ + 1327 + ] + ], + [ + [ + 1327, + 1327 + ], + "valid" + ], + [ + [ + 1328, + 1328 + ], + "disallowed" + ], + [ + [ + 1329, + 1329 + ], + "mapped", + [ + 1377 + ] + ], + [ + [ + 1330, + 1330 + ], + "mapped", + [ + 1378 + ] + ], + [ + [ + 1331, + 1331 + ], + "mapped", + [ + 1379 + ] + ], + [ + [ + 1332, + 1332 + ], + "mapped", + [ + 1380 + ] + ], + [ + [ + 1333, + 1333 + ], + "mapped", + [ + 1381 + ] + ], + [ + [ + 1334, + 1334 + ], + "mapped", + [ + 1382 + ] + ], + [ + [ + 1335, + 1335 + ], + "mapped", + [ + 1383 + ] + ], + [ + [ + 1336, + 1336 + ], + "mapped", + [ + 1384 + ] + ], + [ + [ + 1337, + 1337 + ], + "mapped", + [ + 1385 + ] + ], + [ + [ + 1338, + 1338 + ], + "mapped", + [ + 1386 + ] + ], + [ + [ + 1339, + 1339 + ], + "mapped", + [ + 1387 + ] + ], + [ + [ + 1340, + 1340 + ], + "mapped", + [ + 1388 + ] + ], + [ + [ + 1341, + 1341 + ], + "mapped", + [ + 1389 + ] + ], + [ + [ + 1342, + 1342 + ], + "mapped", + [ + 1390 + ] + ], + [ + [ + 1343, + 1343 + ], + "mapped", + [ + 1391 + ] + ], + [ + [ + 1344, + 1344 + ], + "mapped", + [ + 1392 + ] + ], + [ + [ + 1345, + 1345 + ], + "mapped", + [ + 1393 + ] + ], + [ + [ + 1346, + 1346 + ], + "mapped", + [ + 1394 + ] + ], + [ + [ + 1347, + 1347 + ], + "mapped", + [ + 1395 + ] + ], + [ + [ + 1348, + 1348 + ], + "mapped", + [ + 1396 + ] + ], + [ + [ + 1349, + 1349 + ], + "mapped", + [ + 1397 + ] + ], + [ + [ + 1350, + 1350 + ], + "mapped", + [ + 1398 + ] + ], + [ + [ + 1351, + 1351 + ], + "mapped", + [ + 1399 + ] + ], + [ + [ + 1352, + 1352 + ], + "mapped", + [ + 1400 + ] + ], + [ + [ + 1353, + 1353 + ], + "mapped", + [ + 1401 + ] + ], + [ + [ + 1354, + 1354 + ], + "mapped", + [ + 1402 + ] + ], + [ + [ + 1355, + 1355 + ], + "mapped", + [ + 1403 + ] + ], + [ + [ + 1356, + 1356 + ], + "mapped", + [ + 1404 + ] + ], + [ + [ + 1357, + 1357 + ], + "mapped", + [ + 1405 + ] + ], + [ + [ + 1358, + 1358 + ], + "mapped", + [ + 1406 + ] + ], + [ + [ + 1359, + 1359 + ], + "mapped", + [ + 1407 + ] + ], + [ + [ + 1360, + 1360 + ], + "mapped", + [ + 1408 + ] + ], + [ + [ + 1361, + 1361 + ], + "mapped", + [ + 1409 + ] + ], + [ + [ + 1362, + 1362 + ], + "mapped", + [ + 1410 + ] + ], + [ + [ + 1363, + 1363 + ], + "mapped", + [ + 1411 + ] + ], + [ + [ + 1364, + 1364 + ], + "mapped", + [ + 1412 + ] + ], + [ + [ + 1365, + 1365 + ], + "mapped", + [ + 1413 + ] + ], + [ + [ + 1366, + 1366 + ], + "mapped", + [ + 1414 + ] + ], + [ + [ + 1367, + 1368 + ], + "disallowed" + ], + [ + [ + 1369, + 1369 + ], + "valid" + ], + [ + [ + 1370, + 1375 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 1376, + 1376 + ], + "disallowed" + ], + [ + [ + 1377, + 1414 + ], + "valid" + ], + [ + [ + 1415, + 1415 + ], + "mapped", + [ + 1381, + 1410 + ] + ], + [ + [ + 1416, + 1416 + ], + "disallowed" + ], + [ + [ + 1417, + 1417 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 1418, + 1418 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 1419, + 1420 + ], + "disallowed" + ], + [ + [ + 1421, + 1422 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 1423, + 1423 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 1424, + 1424 + ], + "disallowed" + ], + [ + [ + 1425, + 1441 + ], + "valid" + ], + [ + [ + 1442, + 1442 + ], + "valid" + ], + [ + [ + 1443, + 1455 + ], + "valid" + ], + [ + [ + 1456, + 1465 + ], + "valid" + ], + [ + [ + 1466, + 1466 + ], + "valid" + ], + [ + [ + 1467, + 1469 + ], + "valid" + ], + [ + [ + 1470, + 1470 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 1471, + 1471 + ], + "valid" + ], + [ + [ + 1472, + 1472 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 1473, + 1474 + ], + "valid" + ], + [ + [ + 1475, + 1475 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 1476, + 1476 + ], + "valid" + ], + [ + [ + 1477, + 1477 + ], + "valid" + ], + [ + [ + 1478, + 1478 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 1479, + 1479 + ], + "valid" + ], + [ + [ + 1480, + 1487 + ], + "disallowed" + ], + [ + [ + 1488, + 1514 + ], + "valid" + ], + [ + [ + 1515, + 1519 + ], + "disallowed" + ], + [ + [ + 1520, + 1524 + ], + "valid" + ], + [ + [ + 1525, + 1535 + ], + "disallowed" + ], + [ + [ + 1536, + 1539 + ], + "disallowed" + ], + [ + [ + 1540, + 1540 + ], + "disallowed" + ], + [ + [ + 1541, + 1541 + ], + "disallowed" + ], + [ + [ + 1542, + 1546 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 1547, + 1547 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 1548, + 1548 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 1549, + 1551 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 1552, + 1557 + ], + "valid" + ], + [ + [ + 1558, + 1562 + ], + "valid" + ], + [ + [ + 1563, + 1563 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 1564, + 1564 + ], + "disallowed" + ], + [ + [ + 1565, + 1565 + ], + "disallowed" + ], + [ + [ + 1566, + 1566 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 1567, + 1567 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 1568, + 1568 + ], + "valid" + ], + [ + [ + 1569, + 1594 + ], + "valid" + ], + [ + [ + 1595, + 1599 + ], + "valid" + ], + [ + [ + 1600, + 1600 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 1601, + 1618 + ], + "valid" + ], + [ + [ + 1619, + 1621 + ], + "valid" + ], + [ + [ + 1622, + 1624 + ], + "valid" + ], + [ + [ + 1625, + 1630 + ], + "valid" + ], + [ + [ + 1631, + 1631 + ], + "valid" + ], + [ + [ + 1632, + 1641 + ], + "valid" + ], + [ + [ + 1642, + 1645 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 1646, + 1647 + ], + "valid" + ], + [ + [ + 1648, + 1652 + ], + "valid" + ], + [ + [ + 1653, + 1653 + ], + "mapped", + [ + 1575, + 1652 + ] + ], + [ + [ + 1654, + 1654 + ], + "mapped", + [ + 1608, + 1652 + ] + ], + [ + [ + 1655, + 1655 + ], + "mapped", + [ + 1735, + 1652 + ] + ], + [ + [ + 1656, + 1656 + ], + "mapped", + [ + 1610, + 1652 + ] + ], + [ + [ + 1657, + 1719 + ], + "valid" + ], + [ + [ + 1720, + 1721 + ], + "valid" + ], + [ + [ + 1722, + 1726 + ], + "valid" + ], + [ + [ + 1727, + 1727 + ], + "valid" + ], + [ + [ + 1728, + 1742 + ], + "valid" + ], + [ + [ + 1743, + 1743 + ], + "valid" + ], + [ + [ + 1744, + 1747 + ], + "valid" + ], + [ + [ + 1748, + 1748 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 1749, + 1756 + ], + "valid" + ], + [ + [ + 1757, + 1757 + ], + "disallowed" + ], + [ + [ + 1758, + 1758 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 1759, + 1768 + ], + "valid" + ], + [ + [ + 1769, + 1769 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 1770, + 1773 + ], + "valid" + ], + [ + [ + 1774, + 1775 + ], + "valid" + ], + [ + [ + 1776, + 1785 + ], + "valid" + ], + [ + [ + 1786, + 1790 + ], + "valid" + ], + [ + [ + 1791, + 1791 + ], + "valid" + ], + [ + [ + 1792, + 1805 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 1806, + 1806 + ], + "disallowed" + ], + [ + [ + 1807, + 1807 + ], + "disallowed" + ], + [ + [ + 1808, + 1836 + ], + "valid" + ], + [ + [ + 1837, + 1839 + ], + "valid" + ], + [ + [ + 1840, + 1866 + ], + "valid" + ], + [ + [ + 1867, + 1868 + ], + "disallowed" + ], + [ + [ + 1869, + 1871 + ], + "valid" + ], + [ + [ + 1872, + 1901 + ], + "valid" + ], + [ + [ + 1902, + 1919 + ], + "valid" + ], + [ + [ + 1920, + 1968 + ], + "valid" + ], + [ + [ + 1969, + 1969 + ], + "valid" + ], + [ + [ + 1970, + 1983 + ], + "disallowed" + ], + [ + [ + 1984, + 2037 + ], + "valid" + ], + [ + [ + 2038, + 2042 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 2043, + 2047 + ], + "disallowed" + ], + [ + [ + 2048, + 2093 + ], + "valid" + ], + [ + [ + 2094, + 2095 + ], + "disallowed" + ], + [ + [ + 2096, + 2110 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 2111, + 2111 + ], + "disallowed" + ], + [ + [ + 2112, + 2139 + ], + "valid" + ], + [ + [ + 2140, + 2141 + ], + "disallowed" + ], + [ + [ + 2142, + 2142 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 2143, + 2207 + ], + "disallowed" + ], + [ + [ + 2208, + 2208 + ], + "valid" + ], + [ + [ + 2209, + 2209 + ], + "valid" + ], + [ + [ + 2210, + 2220 + ], + "valid" + ], + [ + [ + 2221, + 2226 + ], + "valid" + ], + [ + [ + 2227, + 2228 + ], + "valid" + ], + [ + [ + 2229, + 2274 + ], + "disallowed" + ], + [ + [ + 2275, + 2275 + ], + "valid" + ], + [ + [ + 2276, + 2302 + ], + "valid" + ], + [ + [ + 2303, + 2303 + ], + "valid" + ], + [ + [ + 2304, + 2304 + ], + "valid" + ], + [ + [ + 2305, + 2307 + ], + "valid" + ], + [ + [ + 2308, + 2308 + ], + "valid" + ], + [ + [ + 2309, + 2361 + ], + "valid" + ], + [ + [ + 2362, + 2363 + ], + "valid" + ], + [ + [ + 2364, + 2381 + ], + "valid" + ], + [ + [ + 2382, + 2382 + ], + "valid" + ], + [ + [ + 2383, + 2383 + ], + "valid" + ], + [ + [ + 2384, + 2388 + ], + "valid" + ], + [ + [ + 2389, + 2389 + ], + "valid" + ], + [ + [ + 2390, + 2391 + ], + "valid" + ], + [ + [ + 2392, + 2392 + ], + "mapped", + [ + 2325, + 2364 + ] + ], + [ + [ + 2393, + 2393 + ], + "mapped", + [ + 2326, + 2364 + ] + ], + [ + [ + 2394, + 2394 + ], + "mapped", + [ + 2327, + 2364 + ] + ], + [ + [ + 2395, + 2395 + ], + "mapped", + [ + 2332, + 2364 + ] + ], + [ + [ + 2396, + 2396 + ], + "mapped", + [ + 2337, + 2364 + ] + ], + [ + [ + 2397, + 2397 + ], + "mapped", + [ + 2338, + 2364 + ] + ], + [ + [ + 2398, + 2398 + ], + "mapped", + [ + 2347, + 2364 + ] + ], + [ + [ + 2399, + 2399 + ], + "mapped", + [ + 2351, + 2364 + ] + ], + [ + [ + 2400, + 2403 + ], + "valid" + ], + [ + [ + 2404, + 2405 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 2406, + 2415 + ], + "valid" + ], + [ + [ + 2416, + 2416 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 2417, + 2418 + ], + "valid" + ], + [ + [ + 2419, + 2423 + ], + "valid" + ], + [ + [ + 2424, + 2424 + ], + "valid" + ], + [ + [ + 2425, + 2426 + ], + "valid" + ], + [ + [ + 2427, + 2428 + ], + "valid" + ], + [ + [ + 2429, + 2429 + ], + "valid" + ], + [ + [ + 2430, + 2431 + ], + "valid" + ], + [ + [ + 2432, + 2432 + ], + "valid" + ], + [ + [ + 2433, + 2435 + ], + "valid" + ], + [ + [ + 2436, + 2436 + ], + "disallowed" + ], + [ + [ + 2437, + 2444 + ], + "valid" + ], + [ + [ + 2445, + 2446 + ], + "disallowed" + ], + [ + [ + 2447, + 2448 + ], + "valid" + ], + [ + [ + 2449, + 2450 + ], + "disallowed" + ], + [ + [ + 2451, + 2472 + ], + "valid" + ], + [ + [ + 2473, + 2473 + ], + "disallowed" + ], + [ + [ + 2474, + 2480 + ], + "valid" + ], + [ + [ + 2481, + 2481 + ], + "disallowed" + ], + [ + [ + 2482, + 2482 + ], + "valid" + ], + [ + [ + 2483, + 2485 + ], + "disallowed" + ], + [ + [ + 2486, + 2489 + ], + "valid" + ], + [ + [ + 2490, + 2491 + ], + "disallowed" + ], + [ + [ + 2492, + 2492 + ], + "valid" + ], + [ + [ + 2493, + 2493 + ], + "valid" + ], + [ + [ + 2494, + 2500 + ], + "valid" + ], + [ + [ + 2501, + 2502 + ], + "disallowed" + ], + [ + [ + 2503, + 2504 + ], + "valid" + ], + [ + [ + 2505, + 2506 + ], + "disallowed" + ], + [ + [ + 2507, + 2509 + ], + "valid" + ], + [ + [ + 2510, + 2510 + ], + "valid" + ], + [ + [ + 2511, + 2518 + ], + "disallowed" + ], + [ + [ + 2519, + 2519 + ], + "valid" + ], + [ + [ + 2520, + 2523 + ], + "disallowed" + ], + [ + [ + 2524, + 2524 + ], + "mapped", + [ + 2465, + 2492 + ] + ], + [ + [ + 2525, + 2525 + ], + "mapped", + [ + 2466, + 2492 + ] + ], + [ + [ + 2526, + 2526 + ], + "disallowed" + ], + [ + [ + 2527, + 2527 + ], + "mapped", + [ + 2479, + 2492 + ] + ], + [ + [ + 2528, + 2531 + ], + "valid" + ], + [ + [ + 2532, + 2533 + ], + "disallowed" + ], + [ + [ + 2534, + 2545 + ], + "valid" + ], + [ + [ + 2546, + 2554 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 2555, + 2555 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 2556, + 2560 + ], + "disallowed" + ], + [ + [ + 2561, + 2561 + ], + "valid" + ], + [ + [ + 2562, + 2562 + ], + "valid" + ], + [ + [ + 2563, + 2563 + ], + "valid" + ], + [ + [ + 2564, + 2564 + ], + "disallowed" + ], + [ + [ + 2565, + 2570 + ], + "valid" + ], + [ + [ + 2571, + 2574 + ], + "disallowed" + ], + [ + [ + 2575, + 2576 + ], + "valid" + ], + [ + [ + 2577, + 2578 + ], + "disallowed" + ], + [ + [ + 2579, + 2600 + ], + "valid" + ], + [ + [ + 2601, + 2601 + ], + "disallowed" + ], + [ + [ + 2602, + 2608 + ], + "valid" + ], + [ + [ + 2609, + 2609 + ], + "disallowed" + ], + [ + [ + 2610, + 2610 + ], + "valid" + ], + [ + [ + 2611, + 2611 + ], + "mapped", + [ + 2610, + 2620 + ] + ], + [ + [ + 2612, + 2612 + ], + "disallowed" + ], + [ + [ + 2613, + 2613 + ], + "valid" + ], + [ + [ + 2614, + 2614 + ], + "mapped", + [ + 2616, + 2620 + ] + ], + [ + [ + 2615, + 2615 + ], + "disallowed" + ], + [ + [ + 2616, + 2617 + ], + "valid" + ], + [ + [ + 2618, + 2619 + ], + "disallowed" + ], + [ + [ + 2620, + 2620 + ], + "valid" + ], + [ + [ + 2621, + 2621 + ], + "disallowed" + ], + [ + [ + 2622, + 2626 + ], + "valid" + ], + [ + [ + 2627, + 2630 + ], + "disallowed" + ], + [ + [ + 2631, + 2632 + ], + "valid" + ], + [ + [ + 2633, + 2634 + ], + "disallowed" + ], + [ + [ + 2635, + 2637 + ], + "valid" + ], + [ + [ + 2638, + 2640 + ], + "disallowed" + ], + [ + [ + 2641, + 2641 + ], + "valid" + ], + [ + [ + 2642, + 2648 + ], + "disallowed" + ], + [ + [ + 2649, + 2649 + ], + "mapped", + [ + 2582, + 2620 + ] + ], + [ + [ + 2650, + 2650 + ], + "mapped", + [ + 2583, + 2620 + ] + ], + [ + [ + 2651, + 2651 + ], + "mapped", + [ + 2588, + 2620 + ] + ], + [ + [ + 2652, + 2652 + ], + "valid" + ], + [ + [ + 2653, + 2653 + ], + "disallowed" + ], + [ + [ + 2654, + 2654 + ], + "mapped", + [ + 2603, + 2620 + ] + ], + [ + [ + 2655, + 2661 + ], + "disallowed" + ], + [ + [ + 2662, + 2676 + ], + "valid" + ], + [ + [ + 2677, + 2677 + ], + "valid" + ], + [ + [ + 2678, + 2688 + ], + "disallowed" + ], + [ + [ + 2689, + 2691 + ], + "valid" + ], + [ + [ + 2692, + 2692 + ], + "disallowed" + ], + [ + [ + 2693, + 2699 + ], + "valid" + ], + [ + [ + 2700, + 2700 + ], + "valid" + ], + [ + [ + 2701, + 2701 + ], + "valid" + ], + [ + [ + 2702, + 2702 + ], + "disallowed" + ], + [ + [ + 2703, + 2705 + ], + "valid" + ], + [ + [ + 2706, + 2706 + ], + "disallowed" + ], + [ + [ + 2707, + 2728 + ], + "valid" + ], + [ + [ + 2729, + 2729 + ], + "disallowed" + ], + [ + [ + 2730, + 2736 + ], + "valid" + ], + [ + [ + 2737, + 2737 + ], + "disallowed" + ], + [ + [ + 2738, + 2739 + ], + "valid" + ], + [ + [ + 2740, + 2740 + ], + "disallowed" + ], + [ + [ + 2741, + 2745 + ], + "valid" + ], + [ + [ + 2746, + 2747 + ], + "disallowed" + ], + [ + [ + 2748, + 2757 + ], + "valid" + ], + [ + [ + 2758, + 2758 + ], + "disallowed" + ], + [ + [ + 2759, + 2761 + ], + "valid" + ], + [ + [ + 2762, + 2762 + ], + "disallowed" + ], + [ + [ + 2763, + 2765 + ], + "valid" + ], + [ + [ + 2766, + 2767 + ], + "disallowed" + ], + [ + [ + 2768, + 2768 + ], + "valid" + ], + [ + [ + 2769, + 2783 + ], + "disallowed" + ], + [ + [ + 2784, + 2784 + ], + "valid" + ], + [ + [ + 2785, + 2787 + ], + "valid" + ], + [ + [ + 2788, + 2789 + ], + "disallowed" + ], + [ + [ + 2790, + 2799 + ], + "valid" + ], + [ + [ + 2800, + 2800 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 2801, + 2801 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 2802, + 2808 + ], + "disallowed" + ], + [ + [ + 2809, + 2809 + ], + "valid" + ], + [ + [ + 2810, + 2816 + ], + "disallowed" + ], + [ + [ + 2817, + 2819 + ], + "valid" + ], + [ + [ + 2820, + 2820 + ], + "disallowed" + ], + [ + [ + 2821, + 2828 + ], + "valid" + ], + [ + [ + 2829, + 2830 + ], + "disallowed" + ], + [ + [ + 2831, + 2832 + ], + "valid" + ], + [ + [ + 2833, + 2834 + ], + "disallowed" + ], + [ + [ + 2835, + 2856 + ], + "valid" + ], + [ + [ + 2857, + 2857 + ], + "disallowed" + ], + [ + [ + 2858, + 2864 + ], + "valid" + ], + [ + [ + 2865, + 2865 + ], + "disallowed" + ], + [ + [ + 2866, + 2867 + ], + "valid" + ], + [ + [ + 2868, + 2868 + ], + "disallowed" + ], + [ + [ + 2869, + 2869 + ], + "valid" + ], + [ + [ + 2870, + 2873 + ], + "valid" + ], + [ + [ + 2874, + 2875 + ], + "disallowed" + ], + [ + [ + 2876, + 2883 + ], + "valid" + ], + [ + [ + 2884, + 2884 + ], + "valid" + ], + [ + [ + 2885, + 2886 + ], + "disallowed" + ], + [ + [ + 2887, + 2888 + ], + "valid" + ], + [ + [ + 2889, + 2890 + ], + "disallowed" + ], + [ + [ + 2891, + 2893 + ], + "valid" + ], + [ + [ + 2894, + 2901 + ], + "disallowed" + ], + [ + [ + 2902, + 2903 + ], + "valid" + ], + [ + [ + 2904, + 2907 + ], + "disallowed" + ], + [ + [ + 2908, + 2908 + ], + "mapped", + [ + 2849, + 2876 + ] + ], + [ + [ + 2909, + 2909 + ], + "mapped", + [ + 2850, + 2876 + ] + ], + [ + [ + 2910, + 2910 + ], + "disallowed" + ], + [ + [ + 2911, + 2913 + ], + "valid" + ], + [ + [ + 2914, + 2915 + ], + "valid" + ], + [ + [ + 2916, + 2917 + ], + "disallowed" + ], + [ + [ + 2918, + 2927 + ], + "valid" + ], + [ + [ + 2928, + 2928 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 2929, + 2929 + ], + "valid" + ], + [ + [ + 2930, + 2935 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 2936, + 2945 + ], + "disallowed" + ], + [ + [ + 2946, + 2947 + ], + "valid" + ], + [ + [ + 2948, + 2948 + ], + "disallowed" + ], + [ + [ + 2949, + 2954 + ], + "valid" + ], + [ + [ + 2955, + 2957 + ], + "disallowed" + ], + [ + [ + 2958, + 2960 + ], + "valid" + ], + [ + [ + 2961, + 2961 + ], + "disallowed" + ], + [ + [ + 2962, + 2965 + ], + "valid" + ], + [ + [ + 2966, + 2968 + ], + "disallowed" + ], + [ + [ + 2969, + 2970 + ], + "valid" + ], + [ + [ + 2971, + 2971 + ], + "disallowed" + ], + [ + [ + 2972, + 2972 + ], + "valid" + ], + [ + [ + 2973, + 2973 + ], + "disallowed" + ], + [ + [ + 2974, + 2975 + ], + "valid" + ], + [ + [ + 2976, + 2978 + ], + "disallowed" + ], + [ + [ + 2979, + 2980 + ], + "valid" + ], + [ + [ + 2981, + 2983 + ], + "disallowed" + ], + [ + [ + 2984, + 2986 + ], + "valid" + ], + [ + [ + 2987, + 2989 + ], + "disallowed" + ], + [ + [ + 2990, + 2997 + ], + "valid" + ], + [ + [ + 2998, + 2998 + ], + "valid" + ], + [ + [ + 2999, + 3001 + ], + "valid" + ], + [ + [ + 3002, + 3005 + ], + "disallowed" + ], + [ + [ + 3006, + 3010 + ], + "valid" + ], + [ + [ + 3011, + 3013 + ], + "disallowed" + ], + [ + [ + 3014, + 3016 + ], + "valid" + ], + [ + [ + 3017, + 3017 + ], + "disallowed" + ], + [ + [ + 3018, + 3021 + ], + "valid" + ], + [ + [ + 3022, + 3023 + ], + "disallowed" + ], + [ + [ + 3024, + 3024 + ], + "valid" + ], + [ + [ + 3025, + 3030 + ], + "disallowed" + ], + [ + [ + 3031, + 3031 + ], + "valid" + ], + [ + [ + 3032, + 3045 + ], + "disallowed" + ], + [ + [ + 3046, + 3046 + ], + "valid" + ], + [ + [ + 3047, + 3055 + ], + "valid" + ], + [ + [ + 3056, + 3058 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 3059, + 3066 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 3067, + 3071 + ], + "disallowed" + ], + [ + [ + 3072, + 3072 + ], + "valid" + ], + [ + [ + 3073, + 3075 + ], + "valid" + ], + [ + [ + 3076, + 3076 + ], + "disallowed" + ], + [ + [ + 3077, + 3084 + ], + "valid" + ], + [ + [ + 3085, + 3085 + ], + "disallowed" + ], + [ + [ + 3086, + 3088 + ], + "valid" + ], + [ + [ + 3089, + 3089 + ], + "disallowed" + ], + [ + [ + 3090, + 3112 + ], + "valid" + ], + [ + [ + 3113, + 3113 + ], + "disallowed" + ], + [ + [ + 3114, + 3123 + ], + "valid" + ], + [ + [ + 3124, + 3124 + ], + "valid" + ], + [ + [ + 3125, + 3129 + ], + "valid" + ], + [ + [ + 3130, + 3132 + ], + "disallowed" + ], + [ + [ + 3133, + 3133 + ], + "valid" + ], + [ + [ + 3134, + 3140 + ], + "valid" + ], + [ + [ + 3141, + 3141 + ], + "disallowed" + ], + [ + [ + 3142, + 3144 + ], + "valid" + ], + [ + [ + 3145, + 3145 + ], + "disallowed" + ], + [ + [ + 3146, + 3149 + ], + "valid" + ], + [ + [ + 3150, + 3156 + ], + "disallowed" + ], + [ + [ + 3157, + 3158 + ], + "valid" + ], + [ + [ + 3159, + 3159 + ], + "disallowed" + ], + [ + [ + 3160, + 3161 + ], + "valid" + ], + [ + [ + 3162, + 3162 + ], + "valid" + ], + [ + [ + 3163, + 3167 + ], + "disallowed" + ], + [ + [ + 3168, + 3169 + ], + "valid" + ], + [ + [ + 3170, + 3171 + ], + "valid" + ], + [ + [ + 3172, + 3173 + ], + "disallowed" + ], + [ + [ + 3174, + 3183 + ], + "valid" + ], + [ + [ + 3184, + 3191 + ], + "disallowed" + ], + [ + [ + 3192, + 3199 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 3200, + 3200 + ], + "disallowed" + ], + [ + [ + 3201, + 3201 + ], + "valid" + ], + [ + [ + 3202, + 3203 + ], + "valid" + ], + [ + [ + 3204, + 3204 + ], + "disallowed" + ], + [ + [ + 3205, + 3212 + ], + "valid" + ], + [ + [ + 3213, + 3213 + ], + "disallowed" + ], + [ + [ + 3214, + 3216 + ], + "valid" + ], + [ + [ + 3217, + 3217 + ], + "disallowed" + ], + [ + [ + 3218, + 3240 + ], + "valid" + ], + [ + [ + 3241, + 3241 + ], + "disallowed" + ], + [ + [ + 3242, + 3251 + ], + "valid" + ], + [ + [ + 3252, + 3252 + ], + "disallowed" + ], + [ + [ + 3253, + 3257 + ], + "valid" + ], + [ + [ + 3258, + 3259 + ], + "disallowed" + ], + [ + [ + 3260, + 3261 + ], + "valid" + ], + [ + [ + 3262, + 3268 + ], + "valid" + ], + [ + [ + 3269, + 3269 + ], + "disallowed" + ], + [ + [ + 3270, + 3272 + ], + "valid" + ], + [ + [ + 3273, + 3273 + ], + "disallowed" + ], + [ + [ + 3274, + 3277 + ], + "valid" + ], + [ + [ + 3278, + 3284 + ], + "disallowed" + ], + [ + [ + 3285, + 3286 + ], + "valid" + ], + [ + [ + 3287, + 3293 + ], + "disallowed" + ], + [ + [ + 3294, + 3294 + ], + "valid" + ], + [ + [ + 3295, + 3295 + ], + "disallowed" + ], + [ + [ + 3296, + 3297 + ], + "valid" + ], + [ + [ + 3298, + 3299 + ], + "valid" + ], + [ + [ + 3300, + 3301 + ], + "disallowed" + ], + [ + [ + 3302, + 3311 + ], + "valid" + ], + [ + [ + 3312, + 3312 + ], + "disallowed" + ], + [ + [ + 3313, + 3314 + ], + "valid" + ], + [ + [ + 3315, + 3328 + ], + "disallowed" + ], + [ + [ + 3329, + 3329 + ], + "valid" + ], + [ + [ + 3330, + 3331 + ], + "valid" + ], + [ + [ + 3332, + 3332 + ], + "disallowed" + ], + [ + [ + 3333, + 3340 + ], + "valid" + ], + [ + [ + 3341, + 3341 + ], + "disallowed" + ], + [ + [ + 3342, + 3344 + ], + "valid" + ], + [ + [ + 3345, + 3345 + ], + "disallowed" + ], + [ + [ + 3346, + 3368 + ], + "valid" + ], + [ + [ + 3369, + 3369 + ], + "valid" + ], + [ + [ + 3370, + 3385 + ], + "valid" + ], + [ + [ + 3386, + 3386 + ], + "valid" + ], + [ + [ + 3387, + 3388 + ], + "disallowed" + ], + [ + [ + 3389, + 3389 + ], + "valid" + ], + [ + [ + 3390, + 3395 + ], + "valid" + ], + [ + [ + 3396, + 3396 + ], + "valid" + ], + [ + [ + 3397, + 3397 + ], + "disallowed" + ], + [ + [ + 3398, + 3400 + ], + "valid" + ], + [ + [ + 3401, + 3401 + ], + "disallowed" + ], + [ + [ + 3402, + 3405 + ], + "valid" + ], + [ + [ + 3406, + 3406 + ], + "valid" + ], + [ + [ + 3407, + 3414 + ], + "disallowed" + ], + [ + [ + 3415, + 3415 + ], + "valid" + ], + [ + [ + 3416, + 3422 + ], + "disallowed" + ], + [ + [ + 3423, + 3423 + ], + "valid" + ], + [ + [ + 3424, + 3425 + ], + "valid" + ], + [ + [ + 3426, + 3427 + ], + "valid" + ], + [ + [ + 3428, + 3429 + ], + "disallowed" + ], + [ + [ + 3430, + 3439 + ], + "valid" + ], + [ + [ + 3440, + 3445 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 3446, + 3448 + ], + "disallowed" + ], + [ + [ + 3449, + 3449 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 3450, + 3455 + ], + "valid" + ], + [ + [ + 3456, + 3457 + ], + "disallowed" + ], + [ + [ + 3458, + 3459 + ], + "valid" + ], + [ + [ + 3460, + 3460 + ], + "disallowed" + ], + [ + [ + 3461, + 3478 + ], + "valid" + ], + [ + [ + 3479, + 3481 + ], + "disallowed" + ], + [ + [ + 3482, + 3505 + ], + "valid" + ], + [ + [ + 3506, + 3506 + ], + "disallowed" + ], + [ + [ + 3507, + 3515 + ], + "valid" + ], + [ + [ + 3516, + 3516 + ], + "disallowed" + ], + [ + [ + 3517, + 3517 + ], + "valid" + ], + [ + [ + 3518, + 3519 + ], + "disallowed" + ], + [ + [ + 3520, + 3526 + ], + "valid" + ], + [ + [ + 3527, + 3529 + ], + "disallowed" + ], + [ + [ + 3530, + 3530 + ], + "valid" + ], + [ + [ + 3531, + 3534 + ], + "disallowed" + ], + [ + [ + 3535, + 3540 + ], + "valid" + ], + [ + [ + 3541, + 3541 + ], + "disallowed" + ], + [ + [ + 3542, + 3542 + ], + "valid" + ], + [ + [ + 3543, + 3543 + ], + "disallowed" + ], + [ + [ + 3544, + 3551 + ], + "valid" + ], + [ + [ + 3552, + 3557 + ], + "disallowed" + ], + [ + [ + 3558, + 3567 + ], + "valid" + ], + [ + [ + 3568, + 3569 + ], + "disallowed" + ], + [ + [ + 3570, + 3571 + ], + "valid" + ], + [ + [ + 3572, + 3572 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 3573, + 3584 + ], + "disallowed" + ], + [ + [ + 3585, + 3634 + ], + "valid" + ], + [ + [ + 3635, + 3635 + ], + "mapped", + [ + 3661, + 3634 + ] + ], + [ + [ + 3636, + 3642 + ], + "valid" + ], + [ + [ + 3643, + 3646 + ], + "disallowed" + ], + [ + [ + 3647, + 3647 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 3648, + 3662 + ], + "valid" + ], + [ + [ + 3663, + 3663 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 3664, + 3673 + ], + "valid" + ], + [ + [ + 3674, + 3675 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 3676, + 3712 + ], + "disallowed" + ], + [ + [ + 3713, + 3714 + ], + "valid" + ], + [ + [ + 3715, + 3715 + ], + "disallowed" + ], + [ + [ + 3716, + 3716 + ], + "valid" + ], + [ + [ + 3717, + 3718 + ], + "disallowed" + ], + [ + [ + 3719, + 3720 + ], + "valid" + ], + [ + [ + 3721, + 3721 + ], + "disallowed" + ], + [ + [ + 3722, + 3722 + ], + "valid" + ], + [ + [ + 3723, + 3724 + ], + "disallowed" + ], + [ + [ + 3725, + 3725 + ], + "valid" + ], + [ + [ + 3726, + 3731 + ], + "disallowed" + ], + [ + [ + 3732, + 3735 + ], + "valid" + ], + [ + [ + 3736, + 3736 + ], + "disallowed" + ], + [ + [ + 3737, + 3743 + ], + "valid" + ], + [ + [ + 3744, + 3744 + ], + "disallowed" + ], + [ + [ + 3745, + 3747 + ], + "valid" + ], + [ + [ + 3748, + 3748 + ], + "disallowed" + ], + [ + [ + 3749, + 3749 + ], + "valid" + ], + [ + [ + 3750, + 3750 + ], + "disallowed" + ], + [ + [ + 3751, + 3751 + ], + "valid" + ], + [ + [ + 3752, + 3753 + ], + "disallowed" + ], + [ + [ + 3754, + 3755 + ], + "valid" + ], + [ + [ + 3756, + 3756 + ], + "disallowed" + ], + [ + [ + 3757, + 3762 + ], + "valid" + ], + [ + [ + 3763, + 3763 + ], + "mapped", + [ + 3789, + 3762 + ] + ], + [ + [ + 3764, + 3769 + ], + "valid" + ], + [ + [ + 3770, + 3770 + ], + "disallowed" + ], + [ + [ + 3771, + 3773 + ], + "valid" + ], + [ + [ + 3774, + 3775 + ], + "disallowed" + ], + [ + [ + 3776, + 3780 + ], + "valid" + ], + [ + [ + 3781, + 3781 + ], + "disallowed" + ], + [ + [ + 3782, + 3782 + ], + "valid" + ], + [ + [ + 3783, + 3783 + ], + "disallowed" + ], + [ + [ + 3784, + 3789 + ], + "valid" + ], + [ + [ + 3790, + 3791 + ], + "disallowed" + ], + [ + [ + 3792, + 3801 + ], + "valid" + ], + [ + [ + 3802, + 3803 + ], + "disallowed" + ], + [ + [ + 3804, + 3804 + ], + "mapped", + [ + 3755, + 3737 + ] + ], + [ + [ + 3805, + 3805 + ], + "mapped", + [ + 3755, + 3745 + ] + ], + [ + [ + 3806, + 3807 + ], + "valid" + ], + [ + [ + 3808, + 3839 + ], + "disallowed" + ], + [ + [ + 3840, + 3840 + ], + "valid" + ], + [ + [ + 3841, + 3850 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 3851, + 3851 + ], + "valid" + ], + [ + [ + 3852, + 3852 + ], + "mapped", + [ + 3851 + ] + ], + [ + [ + 3853, + 3863 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 3864, + 3865 + ], + "valid" + ], + [ + [ + 3866, + 3871 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 3872, + 3881 + ], + "valid" + ], + [ + [ + 3882, + 3892 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 3893, + 3893 + ], + "valid" + ], + [ + [ + 3894, + 3894 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 3895, + 3895 + ], + "valid" + ], + [ + [ + 3896, + 3896 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 3897, + 3897 + ], + "valid" + ], + [ + [ + 3898, + 3901 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 3902, + 3906 + ], + "valid" + ], + [ + [ + 3907, + 3907 + ], + "mapped", + [ + 3906, + 4023 + ] + ], + [ + [ + 3908, + 3911 + ], + "valid" + ], + [ + [ + 3912, + 3912 + ], + "disallowed" + ], + [ + [ + 3913, + 3916 + ], + "valid" + ], + [ + [ + 3917, + 3917 + ], + "mapped", + [ + 3916, + 4023 + ] + ], + [ + [ + 3918, + 3921 + ], + "valid" + ], + [ + [ + 3922, + 3922 + ], + "mapped", + [ + 3921, + 4023 + ] + ], + [ + [ + 3923, + 3926 + ], + "valid" + ], + [ + [ + 3927, + 3927 + ], + "mapped", + [ + 3926, + 4023 + ] + ], + [ + [ + 3928, + 3931 + ], + "valid" + ], + [ + [ + 3932, + 3932 + ], + "mapped", + [ + 3931, + 4023 + ] + ], + [ + [ + 3933, + 3944 + ], + "valid" + ], + [ + [ + 3945, + 3945 + ], + "mapped", + [ + 3904, + 4021 + ] + ], + [ + [ + 3946, + 3946 + ], + "valid" + ], + [ + [ + 3947, + 3948 + ], + "valid" + ], + [ + [ + 3949, + 3952 + ], + "disallowed" + ], + [ + [ + 3953, + 3954 + ], + "valid" + ], + [ + [ + 3955, + 3955 + ], + "mapped", + [ + 3953, + 3954 + ] + ], + [ + [ + 3956, + 3956 + ], + "valid" + ], + [ + [ + 3957, + 3957 + ], + "mapped", + [ + 3953, + 3956 + ] + ], + [ + [ + 3958, + 3958 + ], + "mapped", + [ + 4018, + 3968 + ] + ], + [ + [ + 3959, + 3959 + ], + "mapped", + [ + 4018, + 3953, + 3968 + ] + ], + [ + [ + 3960, + 3960 + ], + "mapped", + [ + 4019, + 3968 + ] + ], + [ + [ + 3961, + 3961 + ], + "mapped", + [ + 4019, + 3953, + 3968 + ] + ], + [ + [ + 3962, + 3968 + ], + "valid" + ], + [ + [ + 3969, + 3969 + ], + "mapped", + [ + 3953, + 3968 + ] + ], + [ + [ + 3970, + 3972 + ], + "valid" + ], + [ + [ + 3973, + 3973 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 3974, + 3979 + ], + "valid" + ], + [ + [ + 3980, + 3983 + ], + "valid" + ], + [ + [ + 3984, + 3986 + ], + "valid" + ], + [ + [ + 3987, + 3987 + ], + "mapped", + [ + 3986, + 4023 + ] + ], + [ + [ + 3988, + 3989 + ], + "valid" + ], + [ + [ + 3990, + 3990 + ], + "valid" + ], + [ + [ + 3991, + 3991 + ], + "valid" + ], + [ + [ + 3992, + 3992 + ], + "disallowed" + ], + [ + [ + 3993, + 3996 + ], + "valid" + ], + [ + [ + 3997, + 3997 + ], + "mapped", + [ + 3996, + 4023 + ] + ], + [ + [ + 3998, + 4001 + ], + "valid" + ], + [ + [ + 4002, + 4002 + ], + "mapped", + [ + 4001, + 4023 + ] + ], + [ + [ + 4003, + 4006 + ], + "valid" + ], + [ + [ + 4007, + 4007 + ], + "mapped", + [ + 4006, + 4023 + ] + ], + [ + [ + 4008, + 4011 + ], + "valid" + ], + [ + [ + 4012, + 4012 + ], + "mapped", + [ + 4011, + 4023 + ] + ], + [ + [ + 4013, + 4013 + ], + "valid" + ], + [ + [ + 4014, + 4016 + ], + "valid" + ], + [ + [ + 4017, + 4023 + ], + "valid" + ], + [ + [ + 4024, + 4024 + ], + "valid" + ], + [ + [ + 4025, + 4025 + ], + "mapped", + [ + 3984, + 4021 + ] + ], + [ + [ + 4026, + 4028 + ], + "valid" + ], + [ + [ + 4029, + 4029 + ], + "disallowed" + ], + [ + [ + 4030, + 4037 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 4038, + 4038 + ], + "valid" + ], + [ + [ + 4039, + 4044 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 4045, + 4045 + ], + "disallowed" + ], + [ + [ + 4046, + 4046 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 4047, + 4047 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 4048, + 4049 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 4050, + 4052 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 4053, + 4056 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 4057, + 4058 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 4059, + 4095 + ], + "disallowed" + ], + [ + [ + 4096, + 4129 + ], + "valid" + ], + [ + [ + 4130, + 4130 + ], + "valid" + ], + [ + [ + 4131, + 4135 + ], + "valid" + ], + [ + [ + 4136, + 4136 + ], + "valid" + ], + [ + [ + 4137, + 4138 + ], + "valid" + ], + [ + [ + 4139, + 4139 + ], + "valid" + ], + [ + [ + 4140, + 4146 + ], + "valid" + ], + [ + [ + 4147, + 4149 + ], + "valid" + ], + [ + [ + 4150, + 4153 + ], + "valid" + ], + [ + [ + 4154, + 4159 + ], + "valid" + ], + [ + [ + 4160, + 4169 + ], + "valid" + ], + [ + [ + 4170, + 4175 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 4176, + 4185 + ], + "valid" + ], + [ + [ + 4186, + 4249 + ], + "valid" + ], + [ + [ + 4250, + 4253 + ], + "valid" + ], + [ + [ + 4254, + 4255 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 4256, + 4293 + ], + "disallowed" + ], + [ + [ + 4294, + 4294 + ], + "disallowed" + ], + [ + [ + 4295, + 4295 + ], + "mapped", + [ + 11559 + ] + ], + [ + [ + 4296, + 4300 + ], + "disallowed" + ], + [ + [ + 4301, + 4301 + ], + "mapped", + [ + 11565 + ] + ], + [ + [ + 4302, + 4303 + ], + "disallowed" + ], + [ + [ + 4304, + 4342 + ], + "valid" + ], + [ + [ + 4343, + 4344 + ], + "valid" + ], + [ + [ + 4345, + 4346 + ], + "valid" + ], + [ + [ + 4347, + 4347 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 4348, + 4348 + ], + "mapped", + [ + 4316 + ] + ], + [ + [ + 4349, + 4351 + ], + "valid" + ], + [ + [ + 4352, + 4441 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 4442, + 4446 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 4447, + 4448 + ], + "disallowed" + ], + [ + [ + 4449, + 4514 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 4515, + 4519 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 4520, + 4601 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 4602, + 4607 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 4608, + 4614 + ], + "valid" + ], + [ + [ + 4615, + 4615 + ], + "valid" + ], + [ + [ + 4616, + 4678 + ], + "valid" + ], + [ + [ + 4679, + 4679 + ], + "valid" + ], + [ + [ + 4680, + 4680 + ], + "valid" + ], + [ + [ + 4681, + 4681 + ], + "disallowed" + ], + [ + [ + 4682, + 4685 + ], + "valid" + ], + [ + [ + 4686, + 4687 + ], + "disallowed" + ], + [ + [ + 4688, + 4694 + ], + "valid" + ], + [ + [ + 4695, + 4695 + ], + "disallowed" + ], + [ + [ + 4696, + 4696 + ], + "valid" + ], + [ + [ + 4697, + 4697 + ], + "disallowed" + ], + [ + [ + 4698, + 4701 + ], + "valid" + ], + [ + [ + 4702, + 4703 + ], + "disallowed" + ], + [ + [ + 4704, + 4742 + ], + "valid" + ], + [ + [ + 4743, + 4743 + ], + "valid" + ], + [ + [ + 4744, + 4744 + ], + "valid" + ], + [ + [ + 4745, + 4745 + ], + "disallowed" + ], + [ + [ + 4746, + 4749 + ], + "valid" + ], + [ + [ + 4750, + 4751 + ], + "disallowed" + ], + [ + [ + 4752, + 4782 + ], + "valid" + ], + [ + [ + 4783, + 4783 + ], + "valid" + ], + [ + [ + 4784, + 4784 + ], + "valid" + ], + [ + [ + 4785, + 4785 + ], + "disallowed" + ], + [ + [ + 4786, + 4789 + ], + "valid" + ], + [ + [ + 4790, + 4791 + ], + "disallowed" + ], + [ + [ + 4792, + 4798 + ], + "valid" + ], + [ + [ + 4799, + 4799 + ], + "disallowed" + ], + [ + [ + 4800, + 4800 + ], + "valid" + ], + [ + [ + 4801, + 4801 + ], + "disallowed" + ], + [ + [ + 4802, + 4805 + ], + "valid" + ], + [ + [ + 4806, + 4807 + ], + "disallowed" + ], + [ + [ + 4808, + 4814 + ], + "valid" + ], + [ + [ + 4815, + 4815 + ], + "valid" + ], + [ + [ + 4816, + 4822 + ], + "valid" + ], + [ + [ + 4823, + 4823 + ], + "disallowed" + ], + [ + [ + 4824, + 4846 + ], + "valid" + ], + [ + [ + 4847, + 4847 + ], + "valid" + ], + [ + [ + 4848, + 4878 + ], + "valid" + ], + [ + [ + 4879, + 4879 + ], + "valid" + ], + [ + [ + 4880, + 4880 + ], + "valid" + ], + [ + [ + 4881, + 4881 + ], + "disallowed" + ], + [ + [ + 4882, + 4885 + ], + "valid" + ], + [ + [ + 4886, + 4887 + ], + "disallowed" + ], + [ + [ + 4888, + 4894 + ], + "valid" + ], + [ + [ + 4895, + 4895 + ], + "valid" + ], + [ + [ + 4896, + 4934 + ], + "valid" + ], + [ + [ + 4935, + 4935 + ], + "valid" + ], + [ + [ + 4936, + 4954 + ], + "valid" + ], + [ + [ + 4955, + 4956 + ], + "disallowed" + ], + [ + [ + 4957, + 4958 + ], + "valid" + ], + [ + [ + 4959, + 4959 + ], + "valid" + ], + [ + [ + 4960, + 4960 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 4961, + 4988 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 4989, + 4991 + ], + "disallowed" + ], + [ + [ + 4992, + 5007 + ], + "valid" + ], + [ + [ + 5008, + 5017 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 5018, + 5023 + ], + "disallowed" + ], + [ + [ + 5024, + 5108 + ], + "valid" + ], + [ + [ + 5109, + 5109 + ], + "valid" + ], + [ + [ + 5110, + 5111 + ], + "disallowed" + ], + [ + [ + 5112, + 5112 + ], + "mapped", + [ + 5104 + ] + ], + [ + [ + 5113, + 5113 + ], + "mapped", + [ + 5105 + ] + ], + [ + [ + 5114, + 5114 + ], + "mapped", + [ + 5106 + ] + ], + [ + [ + 5115, + 5115 + ], + "mapped", + [ + 5107 + ] + ], + [ + [ + 5116, + 5116 + ], + "mapped", + [ + 5108 + ] + ], + [ + [ + 5117, + 5117 + ], + "mapped", + [ + 5109 + ] + ], + [ + [ + 5118, + 5119 + ], + "disallowed" + ], + [ + [ + 5120, + 5120 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 5121, + 5740 + ], + "valid" + ], + [ + [ + 5741, + 5742 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 5743, + 5750 + ], + "valid" + ], + [ + [ + 5751, + 5759 + ], + "valid" + ], + [ + [ + 5760, + 5760 + ], + "disallowed" + ], + [ + [ + 5761, + 5786 + ], + "valid" + ], + [ + [ + 5787, + 5788 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 5789, + 5791 + ], + "disallowed" + ], + [ + [ + 5792, + 5866 + ], + "valid" + ], + [ + [ + 5867, + 5872 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 5873, + 5880 + ], + "valid" + ], + [ + [ + 5881, + 5887 + ], + "disallowed" + ], + [ + [ + 5888, + 5900 + ], + "valid" + ], + [ + [ + 5901, + 5901 + ], + "disallowed" + ], + [ + [ + 5902, + 5908 + ], + "valid" + ], + [ + [ + 5909, + 5919 + ], + "disallowed" + ], + [ + [ + 5920, + 5940 + ], + "valid" + ], + [ + [ + 5941, + 5942 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 5943, + 5951 + ], + "disallowed" + ], + [ + [ + 5952, + 5971 + ], + "valid" + ], + [ + [ + 5972, + 5983 + ], + "disallowed" + ], + [ + [ + 5984, + 5996 + ], + "valid" + ], + [ + [ + 5997, + 5997 + ], + "disallowed" + ], + [ + [ + 5998, + 6000 + ], + "valid" + ], + [ + [ + 6001, + 6001 + ], + "disallowed" + ], + [ + [ + 6002, + 6003 + ], + "valid" + ], + [ + [ + 6004, + 6015 + ], + "disallowed" + ], + [ + [ + 6016, + 6067 + ], + "valid" + ], + [ + [ + 6068, + 6069 + ], + "disallowed" + ], + [ + [ + 6070, + 6099 + ], + "valid" + ], + [ + [ + 6100, + 6102 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 6103, + 6103 + ], + "valid" + ], + [ + [ + 6104, + 6107 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 6108, + 6108 + ], + "valid" + ], + [ + [ + 6109, + 6109 + ], + "valid" + ], + [ + [ + 6110, + 6111 + ], + "disallowed" + ], + [ + [ + 6112, + 6121 + ], + "valid" + ], + [ + [ + 6122, + 6127 + ], + "disallowed" + ], + [ + [ + 6128, + 6137 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 6138, + 6143 + ], + "disallowed" + ], + [ + [ + 6144, + 6149 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 6150, + 6150 + ], + "disallowed" + ], + [ + [ + 6151, + 6154 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 6155, + 6157 + ], + "ignored" + ], + [ + [ + 6158, + 6158 + ], + "disallowed" + ], + [ + [ + 6159, + 6159 + ], + "disallowed" + ], + [ + [ + 6160, + 6169 + ], + "valid" + ], + [ + [ + 6170, + 6175 + ], + "disallowed" + ], + [ + [ + 6176, + 6263 + ], + "valid" + ], + [ + [ + 6264, + 6271 + ], + "disallowed" + ], + [ + [ + 6272, + 6313 + ], + "valid" + ], + [ + [ + 6314, + 6314 + ], + "valid" + ], + [ + [ + 6315, + 6319 + ], + "disallowed" + ], + [ + [ + 6320, + 6389 + ], + "valid" + ], + [ + [ + 6390, + 6399 + ], + "disallowed" + ], + [ + [ + 6400, + 6428 + ], + "valid" + ], + [ + [ + 6429, + 6430 + ], + "valid" + ], + [ + [ + 6431, + 6431 + ], + "disallowed" + ], + [ + [ + 6432, + 6443 + ], + "valid" + ], + [ + [ + 6444, + 6447 + ], + "disallowed" + ], + [ + [ + 6448, + 6459 + ], + "valid" + ], + [ + [ + 6460, + 6463 + ], + "disallowed" + ], + [ + [ + 6464, + 6464 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 6465, + 6467 + ], + "disallowed" + ], + [ + [ + 6468, + 6469 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 6470, + 6509 + ], + "valid" + ], + [ + [ + 6510, + 6511 + ], + "disallowed" + ], + [ + [ + 6512, + 6516 + ], + "valid" + ], + [ + [ + 6517, + 6527 + ], + "disallowed" + ], + [ + [ + 6528, + 6569 + ], + "valid" + ], + [ + [ + 6570, + 6571 + ], + "valid" + ], + [ + [ + 6572, + 6575 + ], + "disallowed" + ], + [ + [ + 6576, + 6601 + ], + "valid" + ], + [ + [ + 6602, + 6607 + ], + "disallowed" + ], + [ + [ + 6608, + 6617 + ], + "valid" + ], + [ + [ + 6618, + 6618 + ], + "valid", + [ + ], + "XV8" + ], + [ + [ + 6619, + 6621 + ], + "disallowed" + ], + [ + [ + 6622, + 6623 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 6624, + 6655 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 6656, + 6683 + ], + "valid" + ], + [ + [ + 6684, + 6685 + ], + "disallowed" + ], + [ + [ + 6686, + 6687 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 6688, + 6750 + ], + "valid" + ], + [ + [ + 6751, + 6751 + ], + "disallowed" + ], + [ + [ + 6752, + 6780 + ], + "valid" + ], + [ + [ + 6781, + 6782 + ], + "disallowed" + ], + [ + [ + 6783, + 6793 + ], + "valid" + ], + [ + [ + 6794, + 6799 + ], + "disallowed" + ], + [ + [ + 6800, + 6809 + ], + "valid" + ], + [ + [ + 6810, + 6815 + ], + "disallowed" + ], + [ + [ + 6816, + 6822 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 6823, + 6823 + ], + "valid" + ], + [ + [ + 6824, + 6829 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 6830, + 6831 + ], + "disallowed" + ], + [ + [ + 6832, + 6845 + ], + "valid" + ], + [ + [ + 6846, + 6846 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 6847, + 6911 + ], + "disallowed" + ], + [ + [ + 6912, + 6987 + ], + "valid" + ], + [ + [ + 6988, + 6991 + ], + "disallowed" + ], + [ + [ + 6992, + 7001 + ], + "valid" + ], + [ + [ + 7002, + 7018 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 7019, + 7027 + ], + "valid" + ], + [ + [ + 7028, + 7036 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 7037, + 7039 + ], + "disallowed" + ], + [ + [ + 7040, + 7082 + ], + "valid" + ], + [ + [ + 7083, + 7085 + ], + "valid" + ], + [ + [ + 7086, + 7097 + ], + "valid" + ], + [ + [ + 7098, + 7103 + ], + "valid" + ], + [ + [ + 7104, + 7155 + ], + "valid" + ], + [ + [ + 7156, + 7163 + ], + "disallowed" + ], + [ + [ + 7164, + 7167 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 7168, + 7223 + ], + "valid" + ], + [ + [ + 7224, + 7226 + ], + "disallowed" + ], + [ + [ + 7227, + 7231 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 7232, + 7241 + ], + "valid" + ], + [ + [ + 7242, + 7244 + ], + "disallowed" + ], + [ + [ + 7245, + 7293 + ], + "valid" + ], + [ + [ + 7294, + 7295 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 7296, + 7359 + ], + "disallowed" + ], + [ + [ + 7360, + 7367 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 7368, + 7375 + ], + "disallowed" + ], + [ + [ + 7376, + 7378 + ], + "valid" + ], + [ + [ + 7379, + 7379 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 7380, + 7410 + ], + "valid" + ], + [ + [ + 7411, + 7414 + ], + "valid" + ], + [ + [ + 7415, + 7415 + ], + "disallowed" + ], + [ + [ + 7416, + 7417 + ], + "valid" + ], + [ + [ + 7418, + 7423 + ], + "disallowed" + ], + [ + [ + 7424, + 7467 + ], + "valid" + ], + [ + [ + 7468, + 7468 + ], + "mapped", + [ + 97 + ] + ], + [ + [ + 7469, + 7469 + ], + "mapped", + [ + 230 + ] + ], + [ + [ + 7470, + 7470 + ], + "mapped", + [ + 98 + ] + ], + [ + [ + 7471, + 7471 + ], + "valid" + ], + [ + [ + 7472, + 7472 + ], + "mapped", + [ + 100 + ] + ], + [ + [ + 7473, + 7473 + ], + "mapped", + [ + 101 + ] + ], + [ + [ + 7474, + 7474 + ], + "mapped", + [ + 477 + ] + ], + [ + [ + 7475, + 7475 + ], + "mapped", + [ + 103 + ] + ], + [ + [ + 7476, + 7476 + ], + "mapped", + [ + 104 + ] + ], + [ + [ + 7477, + 7477 + ], + "mapped", + [ + 105 + ] + ], + [ + [ + 7478, + 7478 + ], + "mapped", + [ + 106 + ] + ], + [ + [ + 7479, + 7479 + ], + "mapped", + [ + 107 + ] + ], + [ + [ + 7480, + 7480 + ], + "mapped", + [ + 108 + ] + ], + [ + [ + 7481, + 7481 + ], + "mapped", + [ + 109 + ] + ], + [ + [ + 7482, + 7482 + ], + "mapped", + [ + 110 + ] + ], + [ + [ + 7483, + 7483 + ], + "valid" + ], + [ + [ + 7484, + 7484 + ], + "mapped", + [ + 111 + ] + ], + [ + [ + 7485, + 7485 + ], + "mapped", + [ + 547 + ] + ], + [ + [ + 7486, + 7486 + ], + "mapped", + [ + 112 + ] + ], + [ + [ + 7487, + 7487 + ], + "mapped", + [ + 114 + ] + ], + [ + [ + 7488, + 7488 + ], + "mapped", + [ + 116 + ] + ], + [ + [ + 7489, + 7489 + ], + "mapped", + [ + 117 + ] + ], + [ + [ + 7490, + 7490 + ], + "mapped", + [ + 119 + ] + ], + [ + [ + 7491, + 7491 + ], + "mapped", + [ + 97 + ] + ], + [ + [ + 7492, + 7492 + ], + "mapped", + [ + 592 + ] + ], + [ + [ + 7493, + 7493 + ], + "mapped", + [ + 593 + ] + ], + [ + [ + 7494, + 7494 + ], + "mapped", + [ + 7426 + ] + ], + [ + [ + 7495, + 7495 + ], + "mapped", + [ + 98 + ] + ], + [ + [ + 7496, + 7496 + ], + "mapped", + [ + 100 + ] + ], + [ + [ + 7497, + 7497 + ], + "mapped", + [ + 101 + ] + ], + [ + [ + 7498, + 7498 + ], + "mapped", + [ + 601 + ] + ], + [ + [ + 7499, + 7499 + ], + "mapped", + [ + 603 + ] + ], + [ + [ + 7500, + 7500 + ], + "mapped", + [ + 604 + ] + ], + [ + [ + 7501, + 7501 + ], + "mapped", + [ + 103 + ] + ], + [ + [ + 7502, + 7502 + ], + "valid" + ], + [ + [ + 7503, + 7503 + ], + "mapped", + [ + 107 + ] + ], + [ + [ + 7504, + 7504 + ], + "mapped", + [ + 109 + ] + ], + [ + [ + 7505, + 7505 + ], + "mapped", + [ + 331 + ] + ], + [ + [ + 7506, + 7506 + ], + "mapped", + [ + 111 + ] + ], + [ + [ + 7507, + 7507 + ], + "mapped", + [ + 596 + ] + ], + [ + [ + 7508, + 7508 + ], + "mapped", + [ + 7446 + ] + ], + [ + [ + 7509, + 7509 + ], + "mapped", + [ + 7447 + ] + ], + [ + [ + 7510, + 7510 + ], + "mapped", + [ + 112 + ] + ], + [ + [ + 7511, + 7511 + ], + "mapped", + [ + 116 + ] + ], + [ + [ + 7512, + 7512 + ], + "mapped", + [ + 117 + ] + ], + [ + [ + 7513, + 7513 + ], + "mapped", + [ + 7453 + ] + ], + [ + [ + 7514, + 7514 + ], + "mapped", + [ + 623 + ] + ], + [ + [ + 7515, + 7515 + ], + "mapped", + [ + 118 + ] + ], + [ + [ + 7516, + 7516 + ], + "mapped", + [ + 7461 + ] + ], + [ + [ + 7517, + 7517 + ], + "mapped", + [ + 946 + ] + ], + [ + [ + 7518, + 7518 + ], + "mapped", + [ + 947 + ] + ], + [ + [ + 7519, + 7519 + ], + "mapped", + [ + 948 + ] + ], + [ + [ + 7520, + 7520 + ], + "mapped", + [ + 966 + ] + ], + [ + [ + 7521, + 7521 + ], + "mapped", + [ + 967 + ] + ], + [ + [ + 7522, + 7522 + ], + "mapped", + [ + 105 + ] + ], + [ + [ + 7523, + 7523 + ], + "mapped", + [ + 114 + ] + ], + [ + [ + 7524, + 7524 + ], + "mapped", + [ + 117 + ] + ], + [ + [ + 7525, + 7525 + ], + "mapped", + [ + 118 + ] + ], + [ + [ + 7526, + 7526 + ], + "mapped", + [ + 946 + ] + ], + [ + [ + 7527, + 7527 + ], + "mapped", + [ + 947 + ] + ], + [ + [ + 7528, + 7528 + ], + "mapped", + [ + 961 + ] + ], + [ + [ + 7529, + 7529 + ], + "mapped", + [ + 966 + ] + ], + [ + [ + 7530, + 7530 + ], + "mapped", + [ + 967 + ] + ], + [ + [ + 7531, + 7531 + ], + "valid" + ], + [ + [ + 7532, + 7543 + ], + "valid" + ], + [ + [ + 7544, + 7544 + ], + "mapped", + [ + 1085 + ] + ], + [ + [ + 7545, + 7578 + ], + "valid" + ], + [ + [ + 7579, + 7579 + ], + "mapped", + [ + 594 + ] + ], + [ + [ + 7580, + 7580 + ], + "mapped", + [ + 99 + ] + ], + [ + [ + 7581, + 7581 + ], + "mapped", + [ + 597 + ] + ], + [ + [ + 7582, + 7582 + ], + "mapped", + [ + 240 + ] + ], + [ + [ + 7583, + 7583 + ], + "mapped", + [ + 604 + ] + ], + [ + [ + 7584, + 7584 + ], + "mapped", + [ + 102 + ] + ], + [ + [ + 7585, + 7585 + ], + "mapped", + [ + 607 + ] + ], + [ + [ + 7586, + 7586 + ], + "mapped", + [ + 609 + ] + ], + [ + [ + 7587, + 7587 + ], + "mapped", + [ + 613 + ] + ], + [ + [ + 7588, + 7588 + ], + "mapped", + [ + 616 + ] + ], + [ + [ + 7589, + 7589 + ], + "mapped", + [ + 617 + ] + ], + [ + [ + 7590, + 7590 + ], + "mapped", + [ + 618 + ] + ], + [ + [ + 7591, + 7591 + ], + "mapped", + [ + 7547 + ] + ], + [ + [ + 7592, + 7592 + ], + "mapped", + [ + 669 + ] + ], + [ + [ + 7593, + 7593 + ], + "mapped", + [ + 621 + ] + ], + [ + [ + 7594, + 7594 + ], + "mapped", + [ + 7557 + ] + ], + [ + [ + 7595, + 7595 + ], + "mapped", + [ + 671 + ] + ], + [ + [ + 7596, + 7596 + ], + "mapped", + [ + 625 + ] + ], + [ + [ + 7597, + 7597 + ], + "mapped", + [ + 624 + ] + ], + [ + [ + 7598, + 7598 + ], + "mapped", + [ + 626 + ] + ], + [ + [ + 7599, + 7599 + ], + "mapped", + [ + 627 + ] + ], + [ + [ + 7600, + 7600 + ], + "mapped", + [ + 628 + ] + ], + [ + [ + 7601, + 7601 + ], + "mapped", + [ + 629 + ] + ], + [ + [ + 7602, + 7602 + ], + "mapped", + [ + 632 + ] + ], + [ + [ + 7603, + 7603 + ], + "mapped", + [ + 642 + ] + ], + [ + [ + 7604, + 7604 + ], + "mapped", + [ + 643 + ] + ], + [ + [ + 7605, + 7605 + ], + "mapped", + [ + 427 + ] + ], + [ + [ + 7606, + 7606 + ], + "mapped", + [ + 649 + ] + ], + [ + [ + 7607, + 7607 + ], + "mapped", + [ + 650 + ] + ], + [ + [ + 7608, + 7608 + ], + "mapped", + [ + 7452 + ] + ], + [ + [ + 7609, + 7609 + ], + "mapped", + [ + 651 + ] + ], + [ + [ + 7610, + 7610 + ], + "mapped", + [ + 652 + ] + ], + [ + [ + 7611, + 7611 + ], + "mapped", + [ + 122 + ] + ], + [ + [ + 7612, + 7612 + ], + "mapped", + [ + 656 + ] + ], + [ + [ + 7613, + 7613 + ], + "mapped", + [ + 657 + ] + ], + [ + [ + 7614, + 7614 + ], + "mapped", + [ + 658 + ] + ], + [ + [ + 7615, + 7615 + ], + "mapped", + [ + 952 + ] + ], + [ + [ + 7616, + 7619 + ], + "valid" + ], + [ + [ + 7620, + 7626 + ], + "valid" + ], + [ + [ + 7627, + 7654 + ], + "valid" + ], + [ + [ + 7655, + 7669 + ], + "valid" + ], + [ + [ + 7670, + 7675 + ], + "disallowed" + ], + [ + [ + 7676, + 7676 + ], + "valid" + ], + [ + [ + 7677, + 7677 + ], + "valid" + ], + [ + [ + 7678, + 7679 + ], + "valid" + ], + [ + [ + 7680, + 7680 + ], + "mapped", + [ + 7681 + ] + ], + [ + [ + 7681, + 7681 + ], + "valid" + ], + [ + [ + 7682, + 7682 + ], + "mapped", + [ + 7683 + ] + ], + [ + [ + 7683, + 7683 + ], + "valid" + ], + [ + [ + 7684, + 7684 + ], + "mapped", + [ + 7685 + ] + ], + [ + [ + 7685, + 7685 + ], + "valid" + ], + [ + [ + 7686, + 7686 + ], + "mapped", + [ + 7687 + ] + ], + [ + [ + 7687, + 7687 + ], + "valid" + ], + [ + [ + 7688, + 7688 + ], + "mapped", + [ + 7689 + ] + ], + [ + [ + 7689, + 7689 + ], + "valid" + ], + [ + [ + 7690, + 7690 + ], + "mapped", + [ + 7691 + ] + ], + [ + [ + 7691, + 7691 + ], + "valid" + ], + [ + [ + 7692, + 7692 + ], + "mapped", + [ + 7693 + ] + ], + [ + [ + 7693, + 7693 + ], + "valid" + ], + [ + [ + 7694, + 7694 + ], + "mapped", + [ + 7695 + ] + ], + [ + [ + 7695, + 7695 + ], + "valid" + ], + [ + [ + 7696, + 7696 + ], + "mapped", + [ + 7697 + ] + ], + [ + [ + 7697, + 7697 + ], + "valid" + ], + [ + [ + 7698, + 7698 + ], + "mapped", + [ + 7699 + ] + ], + [ + [ + 7699, + 7699 + ], + "valid" + ], + [ + [ + 7700, + 7700 + ], + "mapped", + [ + 7701 + ] + ], + [ + [ + 7701, + 7701 + ], + "valid" + ], + [ + [ + 7702, + 7702 + ], + "mapped", + [ + 7703 + ] + ], + [ + [ + 7703, + 7703 + ], + "valid" + ], + [ + [ + 7704, + 7704 + ], + "mapped", + [ + 7705 + ] + ], + [ + [ + 7705, + 7705 + ], + "valid" + ], + [ + [ + 7706, + 7706 + ], + "mapped", + [ + 7707 + ] + ], + [ + [ + 7707, + 7707 + ], + "valid" + ], + [ + [ + 7708, + 7708 + ], + "mapped", + [ + 7709 + ] + ], + [ + [ + 7709, + 7709 + ], + "valid" + ], + [ + [ + 7710, + 7710 + ], + "mapped", + [ + 7711 + ] + ], + [ + [ + 7711, + 7711 + ], + "valid" + ], + [ + [ + 7712, + 7712 + ], + "mapped", + [ + 7713 + ] + ], + [ + [ + 7713, + 7713 + ], + "valid" + ], + [ + [ + 7714, + 7714 + ], + "mapped", + [ + 7715 + ] + ], + [ + [ + 7715, + 7715 + ], + "valid" + ], + [ + [ + 7716, + 7716 + ], + "mapped", + [ + 7717 + ] + ], + [ + [ + 7717, + 7717 + ], + "valid" + ], + [ + [ + 7718, + 7718 + ], + "mapped", + [ + 7719 + ] + ], + [ + [ + 7719, + 7719 + ], + "valid" + ], + [ + [ + 7720, + 7720 + ], + "mapped", + [ + 7721 + ] + ], + [ + [ + 7721, + 7721 + ], + "valid" + ], + [ + [ + 7722, + 7722 + ], + "mapped", + [ + 7723 + ] + ], + [ + [ + 7723, + 7723 + ], + "valid" + ], + [ + [ + 7724, + 7724 + ], + "mapped", + [ + 7725 + ] + ], + [ + [ + 7725, + 7725 + ], + "valid" + ], + [ + [ + 7726, + 7726 + ], + "mapped", + [ + 7727 + ] + ], + [ + [ + 7727, + 7727 + ], + "valid" + ], + [ + [ + 7728, + 7728 + ], + "mapped", + [ + 7729 + ] + ], + [ + [ + 7729, + 7729 + ], + "valid" + ], + [ + [ + 7730, + 7730 + ], + "mapped", + [ + 7731 + ] + ], + [ + [ + 7731, + 7731 + ], + "valid" + ], + [ + [ + 7732, + 7732 + ], + "mapped", + [ + 7733 + ] + ], + [ + [ + 7733, + 7733 + ], + "valid" + ], + [ + [ + 7734, + 7734 + ], + "mapped", + [ + 7735 + ] + ], + [ + [ + 7735, + 7735 + ], + "valid" + ], + [ + [ + 7736, + 7736 + ], + "mapped", + [ + 7737 + ] + ], + [ + [ + 7737, + 7737 + ], + "valid" + ], + [ + [ + 7738, + 7738 + ], + "mapped", + [ + 7739 + ] + ], + [ + [ + 7739, + 7739 + ], + "valid" + ], + [ + [ + 7740, + 7740 + ], + "mapped", + [ + 7741 + ] + ], + [ + [ + 7741, + 7741 + ], + "valid" + ], + [ + [ + 7742, + 7742 + ], + "mapped", + [ + 7743 + ] + ], + [ + [ + 7743, + 7743 + ], + "valid" + ], + [ + [ + 7744, + 7744 + ], + "mapped", + [ + 7745 + ] + ], + [ + [ + 7745, + 7745 + ], + "valid" + ], + [ + [ + 7746, + 7746 + ], + "mapped", + [ + 7747 + ] + ], + [ + [ + 7747, + 7747 + ], + "valid" + ], + [ + [ + 7748, + 7748 + ], + "mapped", + [ + 7749 + ] + ], + [ + [ + 7749, + 7749 + ], + "valid" + ], + [ + [ + 7750, + 7750 + ], + "mapped", + [ + 7751 + ] + ], + [ + [ + 7751, + 7751 + ], + "valid" + ], + [ + [ + 7752, + 7752 + ], + "mapped", + [ + 7753 + ] + ], + [ + [ + 7753, + 7753 + ], + "valid" + ], + [ + [ + 7754, + 7754 + ], + "mapped", + [ + 7755 + ] + ], + [ + [ + 7755, + 7755 + ], + "valid" + ], + [ + [ + 7756, + 7756 + ], + "mapped", + [ + 7757 + ] + ], + [ + [ + 7757, + 7757 + ], + "valid" + ], + [ + [ + 7758, + 7758 + ], + "mapped", + [ + 7759 + ] + ], + [ + [ + 7759, + 7759 + ], + "valid" + ], + [ + [ + 7760, + 7760 + ], + "mapped", + [ + 7761 + ] + ], + [ + [ + 7761, + 7761 + ], + "valid" + ], + [ + [ + 7762, + 7762 + ], + "mapped", + [ + 7763 + ] + ], + [ + [ + 7763, + 7763 + ], + "valid" + ], + [ + [ + 7764, + 7764 + ], + "mapped", + [ + 7765 + ] + ], + [ + [ + 7765, + 7765 + ], + "valid" + ], + [ + [ + 7766, + 7766 + ], + "mapped", + [ + 7767 + ] + ], + [ + [ + 7767, + 7767 + ], + "valid" + ], + [ + [ + 7768, + 7768 + ], + "mapped", + [ + 7769 + ] + ], + [ + [ + 7769, + 7769 + ], + "valid" + ], + [ + [ + 7770, + 7770 + ], + "mapped", + [ + 7771 + ] + ], + [ + [ + 7771, + 7771 + ], + "valid" + ], + [ + [ + 7772, + 7772 + ], + "mapped", + [ + 7773 + ] + ], + [ + [ + 7773, + 7773 + ], + "valid" + ], + [ + [ + 7774, + 7774 + ], + "mapped", + [ + 7775 + ] + ], + [ + [ + 7775, + 7775 + ], + "valid" + ], + [ + [ + 7776, + 7776 + ], + "mapped", + [ + 7777 + ] + ], + [ + [ + 7777, + 7777 + ], + "valid" + ], + [ + [ + 7778, + 7778 + ], + "mapped", + [ + 7779 + ] + ], + [ + [ + 7779, + 7779 + ], + "valid" + ], + [ + [ + 7780, + 7780 + ], + "mapped", + [ + 7781 + ] + ], + [ + [ + 7781, + 7781 + ], + "valid" + ], + [ + [ + 7782, + 7782 + ], + "mapped", + [ + 7783 + ] + ], + [ + [ + 7783, + 7783 + ], + "valid" + ], + [ + [ + 7784, + 7784 + ], + "mapped", + [ + 7785 + ] + ], + [ + [ + 7785, + 7785 + ], + "valid" + ], + [ + [ + 7786, + 7786 + ], + "mapped", + [ + 7787 + ] + ], + [ + [ + 7787, + 7787 + ], + "valid" + ], + [ + [ + 7788, + 7788 + ], + "mapped", + [ + 7789 + ] + ], + [ + [ + 7789, + 7789 + ], + "valid" + ], + [ + [ + 7790, + 7790 + ], + "mapped", + [ + 7791 + ] + ], + [ + [ + 7791, + 7791 + ], + "valid" + ], + [ + [ + 7792, + 7792 + ], + "mapped", + [ + 7793 + ] + ], + [ + [ + 7793, + 7793 + ], + "valid" + ], + [ + [ + 7794, + 7794 + ], + "mapped", + [ + 7795 + ] + ], + [ + [ + 7795, + 7795 + ], + "valid" + ], + [ + [ + 7796, + 7796 + ], + "mapped", + [ + 7797 + ] + ], + [ + [ + 7797, + 7797 + ], + "valid" + ], + [ + [ + 7798, + 7798 + ], + "mapped", + [ + 7799 + ] + ], + [ + [ + 7799, + 7799 + ], + "valid" + ], + [ + [ + 7800, + 7800 + ], + "mapped", + [ + 7801 + ] + ], + [ + [ + 7801, + 7801 + ], + "valid" + ], + [ + [ + 7802, + 7802 + ], + "mapped", + [ + 7803 + ] + ], + [ + [ + 7803, + 7803 + ], + "valid" + ], + [ + [ + 7804, + 7804 + ], + "mapped", + [ + 7805 + ] + ], + [ + [ + 7805, + 7805 + ], + "valid" + ], + [ + [ + 7806, + 7806 + ], + "mapped", + [ + 7807 + ] + ], + [ + [ + 7807, + 7807 + ], + "valid" + ], + [ + [ + 7808, + 7808 + ], + "mapped", + [ + 7809 + ] + ], + [ + [ + 7809, + 7809 + ], + "valid" + ], + [ + [ + 7810, + 7810 + ], + "mapped", + [ + 7811 + ] + ], + [ + [ + 7811, + 7811 + ], + "valid" + ], + [ + [ + 7812, + 7812 + ], + "mapped", + [ + 7813 + ] + ], + [ + [ + 7813, + 7813 + ], + "valid" + ], + [ + [ + 7814, + 7814 + ], + "mapped", + [ + 7815 + ] + ], + [ + [ + 7815, + 7815 + ], + "valid" + ], + [ + [ + 7816, + 7816 + ], + "mapped", + [ + 7817 + ] + ], + [ + [ + 7817, + 7817 + ], + "valid" + ], + [ + [ + 7818, + 7818 + ], + "mapped", + [ + 7819 + ] + ], + [ + [ + 7819, + 7819 + ], + "valid" + ], + [ + [ + 7820, + 7820 + ], + "mapped", + [ + 7821 + ] + ], + [ + [ + 7821, + 7821 + ], + "valid" + ], + [ + [ + 7822, + 7822 + ], + "mapped", + [ + 7823 + ] + ], + [ + [ + 7823, + 7823 + ], + "valid" + ], + [ + [ + 7824, + 7824 + ], + "mapped", + [ + 7825 + ] + ], + [ + [ + 7825, + 7825 + ], + "valid" + ], + [ + [ + 7826, + 7826 + ], + "mapped", + [ + 7827 + ] + ], + [ + [ + 7827, + 7827 + ], + "valid" + ], + [ + [ + 7828, + 7828 + ], + "mapped", + [ + 7829 + ] + ], + [ + [ + 7829, + 7833 + ], + "valid" + ], + [ + [ + 7834, + 7834 + ], + "mapped", + [ + 97, + 702 + ] + ], + [ + [ + 7835, + 7835 + ], + "mapped", + [ + 7777 + ] + ], + [ + [ + 7836, + 7837 + ], + "valid" + ], + [ + [ + 7838, + 7838 + ], + "mapped", + [ + 115, + 115 + ] + ], + [ + [ + 7839, + 7839 + ], + "valid" + ], + [ + [ + 7840, + 7840 + ], + "mapped", + [ + 7841 + ] + ], + [ + [ + 7841, + 7841 + ], + "valid" + ], + [ + [ + 7842, + 7842 + ], + "mapped", + [ + 7843 + ] + ], + [ + [ + 7843, + 7843 + ], + "valid" + ], + [ + [ + 7844, + 7844 + ], + "mapped", + [ + 7845 + ] + ], + [ + [ + 7845, + 7845 + ], + "valid" + ], + [ + [ + 7846, + 7846 + ], + "mapped", + [ + 7847 + ] + ], + [ + [ + 7847, + 7847 + ], + "valid" + ], + [ + [ + 7848, + 7848 + ], + "mapped", + [ + 7849 + ] + ], + [ + [ + 7849, + 7849 + ], + "valid" + ], + [ + [ + 7850, + 7850 + ], + "mapped", + [ + 7851 + ] + ], + [ + [ + 7851, + 7851 + ], + "valid" + ], + [ + [ + 7852, + 7852 + ], + "mapped", + [ + 7853 + ] + ], + [ + [ + 7853, + 7853 + ], + "valid" + ], + [ + [ + 7854, + 7854 + ], + "mapped", + [ + 7855 + ] + ], + [ + [ + 7855, + 7855 + ], + "valid" + ], + [ + [ + 7856, + 7856 + ], + "mapped", + [ + 7857 + ] + ], + [ + [ + 7857, + 7857 + ], + "valid" + ], + [ + [ + 7858, + 7858 + ], + "mapped", + [ + 7859 + ] + ], + [ + [ + 7859, + 7859 + ], + "valid" + ], + [ + [ + 7860, + 7860 + ], + "mapped", + [ + 7861 + ] + ], + [ + [ + 7861, + 7861 + ], + "valid" + ], + [ + [ + 7862, + 7862 + ], + "mapped", + [ + 7863 + ] + ], + [ + [ + 7863, + 7863 + ], + "valid" + ], + [ + [ + 7864, + 7864 + ], + "mapped", + [ + 7865 + ] + ], + [ + [ + 7865, + 7865 + ], + "valid" + ], + [ + [ + 7866, + 7866 + ], + "mapped", + [ + 7867 + ] + ], + [ + [ + 7867, + 7867 + ], + "valid" + ], + [ + [ + 7868, + 7868 + ], + "mapped", + [ + 7869 + ] + ], + [ + [ + 7869, + 7869 + ], + "valid" + ], + [ + [ + 7870, + 7870 + ], + "mapped", + [ + 7871 + ] + ], + [ + [ + 7871, + 7871 + ], + "valid" + ], + [ + [ + 7872, + 7872 + ], + "mapped", + [ + 7873 + ] + ], + [ + [ + 7873, + 7873 + ], + "valid" + ], + [ + [ + 7874, + 7874 + ], + "mapped", + [ + 7875 + ] + ], + [ + [ + 7875, + 7875 + ], + "valid" + ], + [ + [ + 7876, + 7876 + ], + "mapped", + [ + 7877 + ] + ], + [ + [ + 7877, + 7877 + ], + "valid" + ], + [ + [ + 7878, + 7878 + ], + "mapped", + [ + 7879 + ] + ], + [ + [ + 7879, + 7879 + ], + "valid" + ], + [ + [ + 7880, + 7880 + ], + "mapped", + [ + 7881 + ] + ], + [ + [ + 7881, + 7881 + ], + "valid" + ], + [ + [ + 7882, + 7882 + ], + "mapped", + [ + 7883 + ] + ], + [ + [ + 7883, + 7883 + ], + "valid" + ], + [ + [ + 7884, + 7884 + ], + "mapped", + [ + 7885 + ] + ], + [ + [ + 7885, + 7885 + ], + "valid" + ], + [ + [ + 7886, + 7886 + ], + "mapped", + [ + 7887 + ] + ], + [ + [ + 7887, + 7887 + ], + "valid" + ], + [ + [ + 7888, + 7888 + ], + "mapped", + [ + 7889 + ] + ], + [ + [ + 7889, + 7889 + ], + "valid" + ], + [ + [ + 7890, + 7890 + ], + "mapped", + [ + 7891 + ] + ], + [ + [ + 7891, + 7891 + ], + "valid" + ], + [ + [ + 7892, + 7892 + ], + "mapped", + [ + 7893 + ] + ], + [ + [ + 7893, + 7893 + ], + "valid" + ], + [ + [ + 7894, + 7894 + ], + "mapped", + [ + 7895 + ] + ], + [ + [ + 7895, + 7895 + ], + "valid" + ], + [ + [ + 7896, + 7896 + ], + "mapped", + [ + 7897 + ] + ], + [ + [ + 7897, + 7897 + ], + "valid" + ], + [ + [ + 7898, + 7898 + ], + "mapped", + [ + 7899 + ] + ], + [ + [ + 7899, + 7899 + ], + "valid" + ], + [ + [ + 7900, + 7900 + ], + "mapped", + [ + 7901 + ] + ], + [ + [ + 7901, + 7901 + ], + "valid" + ], + [ + [ + 7902, + 7902 + ], + "mapped", + [ + 7903 + ] + ], + [ + [ + 7903, + 7903 + ], + "valid" + ], + [ + [ + 7904, + 7904 + ], + "mapped", + [ + 7905 + ] + ], + [ + [ + 7905, + 7905 + ], + "valid" + ], + [ + [ + 7906, + 7906 + ], + "mapped", + [ + 7907 + ] + ], + [ + [ + 7907, + 7907 + ], + "valid" + ], + [ + [ + 7908, + 7908 + ], + "mapped", + [ + 7909 + ] + ], + [ + [ + 7909, + 7909 + ], + "valid" + ], + [ + [ + 7910, + 7910 + ], + "mapped", + [ + 7911 + ] + ], + [ + [ + 7911, + 7911 + ], + "valid" + ], + [ + [ + 7912, + 7912 + ], + "mapped", + [ + 7913 + ] + ], + [ + [ + 7913, + 7913 + ], + "valid" + ], + [ + [ + 7914, + 7914 + ], + "mapped", + [ + 7915 + ] + ], + [ + [ + 7915, + 7915 + ], + "valid" + ], + [ + [ + 7916, + 7916 + ], + "mapped", + [ + 7917 + ] + ], + [ + [ + 7917, + 7917 + ], + "valid" + ], + [ + [ + 7918, + 7918 + ], + "mapped", + [ + 7919 + ] + ], + [ + [ + 7919, + 7919 + ], + "valid" + ], + [ + [ + 7920, + 7920 + ], + "mapped", + [ + 7921 + ] + ], + [ + [ + 7921, + 7921 + ], + "valid" + ], + [ + [ + 7922, + 7922 + ], + "mapped", + [ + 7923 + ] + ], + [ + [ + 7923, + 7923 + ], + "valid" + ], + [ + [ + 7924, + 7924 + ], + "mapped", + [ + 7925 + ] + ], + [ + [ + 7925, + 7925 + ], + "valid" + ], + [ + [ + 7926, + 7926 + ], + "mapped", + [ + 7927 + ] + ], + [ + [ + 7927, + 7927 + ], + "valid" + ], + [ + [ + 7928, + 7928 + ], + "mapped", + [ + 7929 + ] + ], + [ + [ + 7929, + 7929 + ], + "valid" + ], + [ + [ + 7930, + 7930 + ], + "mapped", + [ + 7931 + ] + ], + [ + [ + 7931, + 7931 + ], + "valid" + ], + [ + [ + 7932, + 7932 + ], + "mapped", + [ + 7933 + ] + ], + [ + [ + 7933, + 7933 + ], + "valid" + ], + [ + [ + 7934, + 7934 + ], + "mapped", + [ + 7935 + ] + ], + [ + [ + 7935, + 7935 + ], + "valid" + ], + [ + [ + 7936, + 7943 + ], + "valid" + ], + [ + [ + 7944, + 7944 + ], + "mapped", + [ + 7936 + ] + ], + [ + [ + 7945, + 7945 + ], + "mapped", + [ + 7937 + ] + ], + [ + [ + 7946, + 7946 + ], + "mapped", + [ + 7938 + ] + ], + [ + [ + 7947, + 7947 + ], + "mapped", + [ + 7939 + ] + ], + [ + [ + 7948, + 7948 + ], + "mapped", + [ + 7940 + ] + ], + [ + [ + 7949, + 7949 + ], + "mapped", + [ + 7941 + ] + ], + [ + [ + 7950, + 7950 + ], + "mapped", + [ + 7942 + ] + ], + [ + [ + 7951, + 7951 + ], + "mapped", + [ + 7943 + ] + ], + [ + [ + 7952, + 7957 + ], + "valid" + ], + [ + [ + 7958, + 7959 + ], + "disallowed" + ], + [ + [ + 7960, + 7960 + ], + "mapped", + [ + 7952 + ] + ], + [ + [ + 7961, + 7961 + ], + "mapped", + [ + 7953 + ] + ], + [ + [ + 7962, + 7962 + ], + "mapped", + [ + 7954 + ] + ], + [ + [ + 7963, + 7963 + ], + "mapped", + [ + 7955 + ] + ], + [ + [ + 7964, + 7964 + ], + "mapped", + [ + 7956 + ] + ], + [ + [ + 7965, + 7965 + ], + "mapped", + [ + 7957 + ] + ], + [ + [ + 7966, + 7967 + ], + "disallowed" + ], + [ + [ + 7968, + 7975 + ], + "valid" + ], + [ + [ + 7976, + 7976 + ], + "mapped", + [ + 7968 + ] + ], + [ + [ + 7977, + 7977 + ], + "mapped", + [ + 7969 + ] + ], + [ + [ + 7978, + 7978 + ], + "mapped", + [ + 7970 + ] + ], + [ + [ + 7979, + 7979 + ], + "mapped", + [ + 7971 + ] + ], + [ + [ + 7980, + 7980 + ], + "mapped", + [ + 7972 + ] + ], + [ + [ + 7981, + 7981 + ], + "mapped", + [ + 7973 + ] + ], + [ + [ + 7982, + 7982 + ], + "mapped", + [ + 7974 + ] + ], + [ + [ + 7983, + 7983 + ], + "mapped", + [ + 7975 + ] + ], + [ + [ + 7984, + 7991 + ], + "valid" + ], + [ + [ + 7992, + 7992 + ], + "mapped", + [ + 7984 + ] + ], + [ + [ + 7993, + 7993 + ], + "mapped", + [ + 7985 + ] + ], + [ + [ + 7994, + 7994 + ], + "mapped", + [ + 7986 + ] + ], + [ + [ + 7995, + 7995 + ], + "mapped", + [ + 7987 + ] + ], + [ + [ + 7996, + 7996 + ], + "mapped", + [ + 7988 + ] + ], + [ + [ + 7997, + 7997 + ], + "mapped", + [ + 7989 + ] + ], + [ + [ + 7998, + 7998 + ], + "mapped", + [ + 7990 + ] + ], + [ + [ + 7999, + 7999 + ], + "mapped", + [ + 7991 + ] + ], + [ + [ + 8000, + 8005 + ], + "valid" + ], + [ + [ + 8006, + 8007 + ], + "disallowed" + ], + [ + [ + 8008, + 8008 + ], + "mapped", + [ + 8000 + ] + ], + [ + [ + 8009, + 8009 + ], + "mapped", + [ + 8001 + ] + ], + [ + [ + 8010, + 8010 + ], + "mapped", + [ + 8002 + ] + ], + [ + [ + 8011, + 8011 + ], + "mapped", + [ + 8003 + ] + ], + [ + [ + 8012, + 8012 + ], + "mapped", + [ + 8004 + ] + ], + [ + [ + 8013, + 8013 + ], + "mapped", + [ + 8005 + ] + ], + [ + [ + 8014, + 8015 + ], + "disallowed" + ], + [ + [ + 8016, + 8023 + ], + "valid" + ], + [ + [ + 8024, + 8024 + ], + "disallowed" + ], + [ + [ + 8025, + 8025 + ], + "mapped", + [ + 8017 + ] + ], + [ + [ + 8026, + 8026 + ], + "disallowed" + ], + [ + [ + 8027, + 8027 + ], + "mapped", + [ + 8019 + ] + ], + [ + [ + 8028, + 8028 + ], + "disallowed" + ], + [ + [ + 8029, + 8029 + ], + "mapped", + [ + 8021 + ] + ], + [ + [ + 8030, + 8030 + ], + "disallowed" + ], + [ + [ + 8031, + 8031 + ], + "mapped", + [ + 8023 + ] + ], + [ + [ + 8032, + 8039 + ], + "valid" + ], + [ + [ + 8040, + 8040 + ], + "mapped", + [ + 8032 + ] + ], + [ + [ + 8041, + 8041 + ], + "mapped", + [ + 8033 + ] + ], + [ + [ + 8042, + 8042 + ], + "mapped", + [ + 8034 + ] + ], + [ + [ + 8043, + 8043 + ], + "mapped", + [ + 8035 + ] + ], + [ + [ + 8044, + 8044 + ], + "mapped", + [ + 8036 + ] + ], + [ + [ + 8045, + 8045 + ], + "mapped", + [ + 8037 + ] + ], + [ + [ + 8046, + 8046 + ], + "mapped", + [ + 8038 + ] + ], + [ + [ + 8047, + 8047 + ], + "mapped", + [ + 8039 + ] + ], + [ + [ + 8048, + 8048 + ], + "valid" + ], + [ + [ + 8049, + 8049 + ], + "mapped", + [ + 940 + ] + ], + [ + [ + 8050, + 8050 + ], + "valid" + ], + [ + [ + 8051, + 8051 + ], + "mapped", + [ + 941 + ] + ], + [ + [ + 8052, + 8052 + ], + "valid" + ], + [ + [ + 8053, + 8053 + ], + "mapped", + [ + 942 + ] + ], + [ + [ + 8054, + 8054 + ], + "valid" + ], + [ + [ + 8055, + 8055 + ], + "mapped", + [ + 943 + ] + ], + [ + [ + 8056, + 8056 + ], + "valid" + ], + [ + [ + 8057, + 8057 + ], + "mapped", + [ + 972 + ] + ], + [ + [ + 8058, + 8058 + ], + "valid" + ], + [ + [ + 8059, + 8059 + ], + "mapped", + [ + 973 + ] + ], + [ + [ + 8060, + 8060 + ], + "valid" + ], + [ + [ + 8061, + 8061 + ], + "mapped", + [ + 974 + ] + ], + [ + [ + 8062, + 8063 + ], + "disallowed" + ], + [ + [ + 8064, + 8064 + ], + "mapped", + [ + 7936, + 953 + ] + ], + [ + [ + 8065, + 8065 + ], + "mapped", + [ + 7937, + 953 + ] + ], + [ + [ + 8066, + 8066 + ], + "mapped", + [ + 7938, + 953 + ] + ], + [ + [ + 8067, + 8067 + ], + "mapped", + [ + 7939, + 953 + ] + ], + [ + [ + 8068, + 8068 + ], + "mapped", + [ + 7940, + 953 + ] + ], + [ + [ + 8069, + 8069 + ], + "mapped", + [ + 7941, + 953 + ] + ], + [ + [ + 8070, + 8070 + ], + "mapped", + [ + 7942, + 953 + ] + ], + [ + [ + 8071, + 8071 + ], + "mapped", + [ + 7943, + 953 + ] + ], + [ + [ + 8072, + 8072 + ], + "mapped", + [ + 7936, + 953 + ] + ], + [ + [ + 8073, + 8073 + ], + "mapped", + [ + 7937, + 953 + ] + ], + [ + [ + 8074, + 8074 + ], + "mapped", + [ + 7938, + 953 + ] + ], + [ + [ + 8075, + 8075 + ], + "mapped", + [ + 7939, + 953 + ] + ], + [ + [ + 8076, + 8076 + ], + "mapped", + [ + 7940, + 953 + ] + ], + [ + [ + 8077, + 8077 + ], + "mapped", + [ + 7941, + 953 + ] + ], + [ + [ + 8078, + 8078 + ], + "mapped", + [ + 7942, + 953 + ] + ], + [ + [ + 8079, + 8079 + ], + "mapped", + [ + 7943, + 953 + ] + ], + [ + [ + 8080, + 8080 + ], + "mapped", + [ + 7968, + 953 + ] + ], + [ + [ + 8081, + 8081 + ], + "mapped", + [ + 7969, + 953 + ] + ], + [ + [ + 8082, + 8082 + ], + "mapped", + [ + 7970, + 953 + ] + ], + [ + [ + 8083, + 8083 + ], + "mapped", + [ + 7971, + 953 + ] + ], + [ + [ + 8084, + 8084 + ], + "mapped", + [ + 7972, + 953 + ] + ], + [ + [ + 8085, + 8085 + ], + "mapped", + [ + 7973, + 953 + ] + ], + [ + [ + 8086, + 8086 + ], + "mapped", + [ + 7974, + 953 + ] + ], + [ + [ + 8087, + 8087 + ], + "mapped", + [ + 7975, + 953 + ] + ], + [ + [ + 8088, + 8088 + ], + "mapped", + [ + 7968, + 953 + ] + ], + [ + [ + 8089, + 8089 + ], + "mapped", + [ + 7969, + 953 + ] + ], + [ + [ + 8090, + 8090 + ], + "mapped", + [ + 7970, + 953 + ] + ], + [ + [ + 8091, + 8091 + ], + "mapped", + [ + 7971, + 953 + ] + ], + [ + [ + 8092, + 8092 + ], + "mapped", + [ + 7972, + 953 + ] + ], + [ + [ + 8093, + 8093 + ], + "mapped", + [ + 7973, + 953 + ] + ], + [ + [ + 8094, + 8094 + ], + "mapped", + [ + 7974, + 953 + ] + ], + [ + [ + 8095, + 8095 + ], + "mapped", + [ + 7975, + 953 + ] + ], + [ + [ + 8096, + 8096 + ], + "mapped", + [ + 8032, + 953 + ] + ], + [ + [ + 8097, + 8097 + ], + "mapped", + [ + 8033, + 953 + ] + ], + [ + [ + 8098, + 8098 + ], + "mapped", + [ + 8034, + 953 + ] + ], + [ + [ + 8099, + 8099 + ], + "mapped", + [ + 8035, + 953 + ] + ], + [ + [ + 8100, + 8100 + ], + "mapped", + [ + 8036, + 953 + ] + ], + [ + [ + 8101, + 8101 + ], + "mapped", + [ + 8037, + 953 + ] + ], + [ + [ + 8102, + 8102 + ], + "mapped", + [ + 8038, + 953 + ] + ], + [ + [ + 8103, + 8103 + ], + "mapped", + [ + 8039, + 953 + ] + ], + [ + [ + 8104, + 8104 + ], + "mapped", + [ + 8032, + 953 + ] + ], + [ + [ + 8105, + 8105 + ], + "mapped", + [ + 8033, + 953 + ] + ], + [ + [ + 8106, + 8106 + ], + "mapped", + [ + 8034, + 953 + ] + ], + [ + [ + 8107, + 8107 + ], + "mapped", + [ + 8035, + 953 + ] + ], + [ + [ + 8108, + 8108 + ], + "mapped", + [ + 8036, + 953 + ] + ], + [ + [ + 8109, + 8109 + ], + "mapped", + [ + 8037, + 953 + ] + ], + [ + [ + 8110, + 8110 + ], + "mapped", + [ + 8038, + 953 + ] + ], + [ + [ + 8111, + 8111 + ], + "mapped", + [ + 8039, + 953 + ] + ], + [ + [ + 8112, + 8113 + ], + "valid" + ], + [ + [ + 8114, + 8114 + ], + "mapped", + [ + 8048, + 953 + ] + ], + [ + [ + 8115, + 8115 + ], + "mapped", + [ + 945, + 953 + ] + ], + [ + [ + 8116, + 8116 + ], + "mapped", + [ + 940, + 953 + ] + ], + [ + [ + 8117, + 8117 + ], + "disallowed" + ], + [ + [ + 8118, + 8118 + ], + "valid" + ], + [ + [ + 8119, + 8119 + ], + "mapped", + [ + 8118, + 953 + ] + ], + [ + [ + 8120, + 8120 + ], + "mapped", + [ + 8112 + ] + ], + [ + [ + 8121, + 8121 + ], + "mapped", + [ + 8113 + ] + ], + [ + [ + 8122, + 8122 + ], + "mapped", + [ + 8048 + ] + ], + [ + [ + 8123, + 8123 + ], + "mapped", + [ + 940 + ] + ], + [ + [ + 8124, + 8124 + ], + "mapped", + [ + 945, + 953 + ] + ], + [ + [ + 8125, + 8125 + ], + "disallowed_STD3_mapped", + [ + 32, + 787 + ] + ], + [ + [ + 8126, + 8126 + ], + "mapped", + [ + 953 + ] + ], + [ + [ + 8127, + 8127 + ], + "disallowed_STD3_mapped", + [ + 32, + 787 + ] + ], + [ + [ + 8128, + 8128 + ], + "disallowed_STD3_mapped", + [ + 32, + 834 + ] + ], + [ + [ + 8129, + 8129 + ], + "disallowed_STD3_mapped", + [ + 32, + 776, + 834 + ] + ], + [ + [ + 8130, + 8130 + ], + "mapped", + [ + 8052, + 953 + ] + ], + [ + [ + 8131, + 8131 + ], + "mapped", + [ + 951, + 953 + ] + ], + [ + [ + 8132, + 8132 + ], + "mapped", + [ + 942, + 953 + ] + ], + [ + [ + 8133, + 8133 + ], + "disallowed" + ], + [ + [ + 8134, + 8134 + ], + "valid" + ], + [ + [ + 8135, + 8135 + ], + "mapped", + [ + 8134, + 953 + ] + ], + [ + [ + 8136, + 8136 + ], + "mapped", + [ + 8050 + ] + ], + [ + [ + 8137, + 8137 + ], + "mapped", + [ + 941 + ] + ], + [ + [ + 8138, + 8138 + ], + "mapped", + [ + 8052 + ] + ], + [ + [ + 8139, + 8139 + ], + "mapped", + [ + 942 + ] + ], + [ + [ + 8140, + 8140 + ], + "mapped", + [ + 951, + 953 + ] + ], + [ + [ + 8141, + 8141 + ], + "disallowed_STD3_mapped", + [ + 32, + 787, + 768 + ] + ], + [ + [ + 8142, + 8142 + ], + "disallowed_STD3_mapped", + [ + 32, + 787, + 769 + ] + ], + [ + [ + 8143, + 8143 + ], + "disallowed_STD3_mapped", + [ + 32, + 787, + 834 + ] + ], + [ + [ + 8144, + 8146 + ], + "valid" + ], + [ + [ + 8147, + 8147 + ], + "mapped", + [ + 912 + ] + ], + [ + [ + 8148, + 8149 + ], + "disallowed" + ], + [ + [ + 8150, + 8151 + ], + "valid" + ], + [ + [ + 8152, + 8152 + ], + "mapped", + [ + 8144 + ] + ], + [ + [ + 8153, + 8153 + ], + "mapped", + [ + 8145 + ] + ], + [ + [ + 8154, + 8154 + ], + "mapped", + [ + 8054 + ] + ], + [ + [ + 8155, + 8155 + ], + "mapped", + [ + 943 + ] + ], + [ + [ + 8156, + 8156 + ], + "disallowed" + ], + [ + [ + 8157, + 8157 + ], + "disallowed_STD3_mapped", + [ + 32, + 788, + 768 + ] + ], + [ + [ + 8158, + 8158 + ], + "disallowed_STD3_mapped", + [ + 32, + 788, + 769 + ] + ], + [ + [ + 8159, + 8159 + ], + "disallowed_STD3_mapped", + [ + 32, + 788, + 834 + ] + ], + [ + [ + 8160, + 8162 + ], + "valid" + ], + [ + [ + 8163, + 8163 + ], + "mapped", + [ + 944 + ] + ], + [ + [ + 8164, + 8167 + ], + "valid" + ], + [ + [ + 8168, + 8168 + ], + "mapped", + [ + 8160 + ] + ], + [ + [ + 8169, + 8169 + ], + "mapped", + [ + 8161 + ] + ], + [ + [ + 8170, + 8170 + ], + "mapped", + [ + 8058 + ] + ], + [ + [ + 8171, + 8171 + ], + "mapped", + [ + 973 + ] + ], + [ + [ + 8172, + 8172 + ], + "mapped", + [ + 8165 + ] + ], + [ + [ + 8173, + 8173 + ], + "disallowed_STD3_mapped", + [ + 32, + 776, + 768 + ] + ], + [ + [ + 8174, + 8174 + ], + "disallowed_STD3_mapped", + [ + 32, + 776, + 769 + ] + ], + [ + [ + 8175, + 8175 + ], + "disallowed_STD3_mapped", + [ + 96 + ] + ], + [ + [ + 8176, + 8177 + ], + "disallowed" + ], + [ + [ + 8178, + 8178 + ], + "mapped", + [ + 8060, + 953 + ] + ], + [ + [ + 8179, + 8179 + ], + "mapped", + [ + 969, + 953 + ] + ], + [ + [ + 8180, + 8180 + ], + "mapped", + [ + 974, + 953 + ] + ], + [ + [ + 8181, + 8181 + ], + "disallowed" + ], + [ + [ + 8182, + 8182 + ], + "valid" + ], + [ + [ + 8183, + 8183 + ], + "mapped", + [ + 8182, + 953 + ] + ], + [ + [ + 8184, + 8184 + ], + "mapped", + [ + 8056 + ] + ], + [ + [ + 8185, + 8185 + ], + "mapped", + [ + 972 + ] + ], + [ + [ + 8186, + 8186 + ], + "mapped", + [ + 8060 + ] + ], + [ + [ + 8187, + 8187 + ], + "mapped", + [ + 974 + ] + ], + [ + [ + 8188, + 8188 + ], + "mapped", + [ + 969, + 953 + ] + ], + [ + [ + 8189, + 8189 + ], + "disallowed_STD3_mapped", + [ + 32, + 769 + ] + ], + [ + [ + 8190, + 8190 + ], + "disallowed_STD3_mapped", + [ + 32, + 788 + ] + ], + [ + [ + 8191, + 8191 + ], + "disallowed" + ], + [ + [ + 8192, + 8202 + ], + "disallowed_STD3_mapped", + [ + 32 + ] + ], + [ + [ + 8203, + 8203 + ], + "ignored" + ], + [ + [ + 8204, + 8205 + ], + "deviation", + [ + ] + ], + [ + [ + 8206, + 8207 + ], + "disallowed" + ], + [ + [ + 8208, + 8208 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 8209, + 8209 + ], + "mapped", + [ + 8208 + ] + ], + [ + [ + 8210, + 8214 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 8215, + 8215 + ], + "disallowed_STD3_mapped", + [ + 32, + 819 + ] + ], + [ + [ + 8216, + 8227 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 8228, + 8230 + ], + "disallowed" + ], + [ + [ + 8231, + 8231 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 8232, + 8238 + ], + "disallowed" + ], + [ + [ + 8239, + 8239 + ], + "disallowed_STD3_mapped", + [ + 32 + ] + ], + [ + [ + 8240, + 8242 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 8243, + 8243 + ], + "mapped", + [ + 8242, + 8242 + ] + ], + [ + [ + 8244, + 8244 + ], + "mapped", + [ + 8242, + 8242, + 8242 + ] + ], + [ + [ + 8245, + 8245 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 8246, + 8246 + ], + "mapped", + [ + 8245, + 8245 + ] + ], + [ + [ + 8247, + 8247 + ], + "mapped", + [ + 8245, + 8245, + 8245 + ] + ], + [ + [ + 8248, + 8251 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 8252, + 8252 + ], + "disallowed_STD3_mapped", + [ + 33, + 33 + ] + ], + [ + [ + 8253, + 8253 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 8254, + 8254 + ], + "disallowed_STD3_mapped", + [ + 32, + 773 + ] + ], + [ + [ + 8255, + 8262 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 8263, + 8263 + ], + "disallowed_STD3_mapped", + [ + 63, + 63 + ] + ], + [ + [ + 8264, + 8264 + ], + "disallowed_STD3_mapped", + [ + 63, + 33 + ] + ], + [ + [ + 8265, + 8265 + ], + "disallowed_STD3_mapped", + [ + 33, + 63 + ] + ], + [ + [ + 8266, + 8269 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 8270, + 8274 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 8275, + 8276 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 8277, + 8278 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 8279, + 8279 + ], + "mapped", + [ + 8242, + 8242, + 8242, + 8242 + ] + ], + [ + [ + 8280, + 8286 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 8287, + 8287 + ], + "disallowed_STD3_mapped", + [ + 32 + ] + ], + [ + [ + 8288, + 8288 + ], + "ignored" + ], + [ + [ + 8289, + 8291 + ], + "disallowed" + ], + [ + [ + 8292, + 8292 + ], + "ignored" + ], + [ + [ + 8293, + 8293 + ], + "disallowed" + ], + [ + [ + 8294, + 8297 + ], + "disallowed" + ], + [ + [ + 8298, + 8303 + ], + "disallowed" + ], + [ + [ + 8304, + 8304 + ], + "mapped", + [ + 48 + ] + ], + [ + [ + 8305, + 8305 + ], + "mapped", + [ + 105 + ] + ], + [ + [ + 8306, + 8307 + ], + "disallowed" + ], + [ + [ + 8308, + 8308 + ], + "mapped", + [ + 52 + ] + ], + [ + [ + 8309, + 8309 + ], + "mapped", + [ + 53 + ] + ], + [ + [ + 8310, + 8310 + ], + "mapped", + [ + 54 + ] + ], + [ + [ + 8311, + 8311 + ], + "mapped", + [ + 55 + ] + ], + [ + [ + 8312, + 8312 + ], + "mapped", + [ + 56 + ] + ], + [ + [ + 8313, + 8313 + ], + "mapped", + [ + 57 + ] + ], + [ + [ + 8314, + 8314 + ], + "disallowed_STD3_mapped", + [ + 43 + ] + ], + [ + [ + 8315, + 8315 + ], + "mapped", + [ + 8722 + ] + ], + [ + [ + 8316, + 8316 + ], + "disallowed_STD3_mapped", + [ + 61 + ] + ], + [ + [ + 8317, + 8317 + ], + "disallowed_STD3_mapped", + [ + 40 + ] + ], + [ + [ + 8318, + 8318 + ], + "disallowed_STD3_mapped", + [ + 41 + ] + ], + [ + [ + 8319, + 8319 + ], + "mapped", + [ + 110 + ] + ], + [ + [ + 8320, + 8320 + ], + "mapped", + [ + 48 + ] + ], + [ + [ + 8321, + 8321 + ], + "mapped", + [ + 49 + ] + ], + [ + [ + 8322, + 8322 + ], + "mapped", + [ + 50 + ] + ], + [ + [ + 8323, + 8323 + ], + "mapped", + [ + 51 + ] + ], + [ + [ + 8324, + 8324 + ], + "mapped", + [ + 52 + ] + ], + [ + [ + 8325, + 8325 + ], + "mapped", + [ + 53 + ] + ], + [ + [ + 8326, + 8326 + ], + "mapped", + [ + 54 + ] + ], + [ + [ + 8327, + 8327 + ], + "mapped", + [ + 55 + ] + ], + [ + [ + 8328, + 8328 + ], + "mapped", + [ + 56 + ] + ], + [ + [ + 8329, + 8329 + ], + "mapped", + [ + 57 + ] + ], + [ + [ + 8330, + 8330 + ], + "disallowed_STD3_mapped", + [ + 43 + ] + ], + [ + [ + 8331, + 8331 + ], + "mapped", + [ + 8722 + ] + ], + [ + [ + 8332, + 8332 + ], + "disallowed_STD3_mapped", + [ + 61 + ] + ], + [ + [ + 8333, + 8333 + ], + "disallowed_STD3_mapped", + [ + 40 + ] + ], + [ + [ + 8334, + 8334 + ], + "disallowed_STD3_mapped", + [ + 41 + ] + ], + [ + [ + 8335, + 8335 + ], + "disallowed" + ], + [ + [ + 8336, + 8336 + ], + "mapped", + [ + 97 + ] + ], + [ + [ + 8337, + 8337 + ], + "mapped", + [ + 101 + ] + ], + [ + [ + 8338, + 8338 + ], + "mapped", + [ + 111 + ] + ], + [ + [ + 8339, + 8339 + ], + "mapped", + [ + 120 + ] + ], + [ + [ + 8340, + 8340 + ], + "mapped", + [ + 601 + ] + ], + [ + [ + 8341, + 8341 + ], + "mapped", + [ + 104 + ] + ], + [ + [ + 8342, + 8342 + ], + "mapped", + [ + 107 + ] + ], + [ + [ + 8343, + 8343 + ], + "mapped", + [ + 108 + ] + ], + [ + [ + 8344, + 8344 + ], + "mapped", + [ + 109 + ] + ], + [ + [ + 8345, + 8345 + ], + "mapped", + [ + 110 + ] + ], + [ + [ + 8346, + 8346 + ], + "mapped", + [ + 112 + ] + ], + [ + [ + 8347, + 8347 + ], + "mapped", + [ + 115 + ] + ], + [ + [ + 8348, + 8348 + ], + "mapped", + [ + 116 + ] + ], + [ + [ + 8349, + 8351 + ], + "disallowed" + ], + [ + [ + 8352, + 8359 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 8360, + 8360 + ], + "mapped", + [ + 114, + 115 + ] + ], + [ + [ + 8361, + 8362 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 8363, + 8363 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 8364, + 8364 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 8365, + 8367 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 8368, + 8369 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 8370, + 8373 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 8374, + 8376 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 8377, + 8377 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 8378, + 8378 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 8379, + 8381 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 8382, + 8382 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 8383, + 8399 + ], + "disallowed" + ], + [ + [ + 8400, + 8417 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 8418, + 8419 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 8420, + 8426 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 8427, + 8427 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 8428, + 8431 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 8432, + 8432 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 8433, + 8447 + ], + "disallowed" + ], + [ + [ + 8448, + 8448 + ], + "disallowed_STD3_mapped", + [ + 97, + 47, + 99 + ] + ], + [ + [ + 8449, + 8449 + ], + "disallowed_STD3_mapped", + [ + 97, + 47, + 115 + ] + ], + [ + [ + 8450, + 8450 + ], + "mapped", + [ + 99 + ] + ], + [ + [ + 8451, + 8451 + ], + "mapped", + [ + 176, + 99 + ] + ], + [ + [ + 8452, + 8452 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 8453, + 8453 + ], + "disallowed_STD3_mapped", + [ + 99, + 47, + 111 + ] + ], + [ + [ + 8454, + 8454 + ], + "disallowed_STD3_mapped", + [ + 99, + 47, + 117 + ] + ], + [ + [ + 8455, + 8455 + ], + "mapped", + [ + 603 + ] + ], + [ + [ + 8456, + 8456 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 8457, + 8457 + ], + "mapped", + [ + 176, + 102 + ] + ], + [ + [ + 8458, + 8458 + ], + "mapped", + [ + 103 + ] + ], + [ + [ + 8459, + 8462 + ], + "mapped", + [ + 104 + ] + ], + [ + [ + 8463, + 8463 + ], + "mapped", + [ + 295 + ] + ], + [ + [ + 8464, + 8465 + ], + "mapped", + [ + 105 + ] + ], + [ + [ + 8466, + 8467 + ], + "mapped", + [ + 108 + ] + ], + [ + [ + 8468, + 8468 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 8469, + 8469 + ], + "mapped", + [ + 110 + ] + ], + [ + [ + 8470, + 8470 + ], + "mapped", + [ + 110, + 111 + ] + ], + [ + [ + 8471, + 8472 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 8473, + 8473 + ], + "mapped", + [ + 112 + ] + ], + [ + [ + 8474, + 8474 + ], + "mapped", + [ + 113 + ] + ], + [ + [ + 8475, + 8477 + ], + "mapped", + [ + 114 + ] + ], + [ + [ + 8478, + 8479 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 8480, + 8480 + ], + "mapped", + [ + 115, + 109 + ] + ], + [ + [ + 8481, + 8481 + ], + "mapped", + [ + 116, + 101, + 108 + ] + ], + [ + [ + 8482, + 8482 + ], + "mapped", + [ + 116, + 109 + ] + ], + [ + [ + 8483, + 8483 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 8484, + 8484 + ], + "mapped", + [ + 122 + ] + ], + [ + [ + 8485, + 8485 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 8486, + 8486 + ], + "mapped", + [ + 969 + ] + ], + [ + [ + 8487, + 8487 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 8488, + 8488 + ], + "mapped", + [ + 122 + ] + ], + [ + [ + 8489, + 8489 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 8490, + 8490 + ], + "mapped", + [ + 107 + ] + ], + [ + [ + 8491, + 8491 + ], + "mapped", + [ + 229 + ] + ], + [ + [ + 8492, + 8492 + ], + "mapped", + [ + 98 + ] + ], + [ + [ + 8493, + 8493 + ], + "mapped", + [ + 99 + ] + ], + [ + [ + 8494, + 8494 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 8495, + 8496 + ], + "mapped", + [ + 101 + ] + ], + [ + [ + 8497, + 8497 + ], + "mapped", + [ + 102 + ] + ], + [ + [ + 8498, + 8498 + ], + "disallowed" + ], + [ + [ + 8499, + 8499 + ], + "mapped", + [ + 109 + ] + ], + [ + [ + 8500, + 8500 + ], + "mapped", + [ + 111 + ] + ], + [ + [ + 8501, + 8501 + ], + "mapped", + [ + 1488 + ] + ], + [ + [ + 8502, + 8502 + ], + "mapped", + [ + 1489 + ] + ], + [ + [ + 8503, + 8503 + ], + "mapped", + [ + 1490 + ] + ], + [ + [ + 8504, + 8504 + ], + "mapped", + [ + 1491 + ] + ], + [ + [ + 8505, + 8505 + ], + "mapped", + [ + 105 + ] + ], + [ + [ + 8506, + 8506 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 8507, + 8507 + ], + "mapped", + [ + 102, + 97, + 120 + ] + ], + [ + [ + 8508, + 8508 + ], + "mapped", + [ + 960 + ] + ], + [ + [ + 8509, + 8510 + ], + "mapped", + [ + 947 + ] + ], + [ + [ + 8511, + 8511 + ], + "mapped", + [ + 960 + ] + ], + [ + [ + 8512, + 8512 + ], + "mapped", + [ + 8721 + ] + ], + [ + [ + 8513, + 8516 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 8517, + 8518 + ], + "mapped", + [ + 100 + ] + ], + [ + [ + 8519, + 8519 + ], + "mapped", + [ + 101 + ] + ], + [ + [ + 8520, + 8520 + ], + "mapped", + [ + 105 + ] + ], + [ + [ + 8521, + 8521 + ], + "mapped", + [ + 106 + ] + ], + [ + [ + 8522, + 8523 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 8524, + 8524 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 8525, + 8525 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 8526, + 8526 + ], + "valid" + ], + [ + [ + 8527, + 8527 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 8528, + 8528 + ], + "mapped", + [ + 49, + 8260, + 55 + ] + ], + [ + [ + 8529, + 8529 + ], + "mapped", + [ + 49, + 8260, + 57 + ] + ], + [ + [ + 8530, + 8530 + ], + "mapped", + [ + 49, + 8260, + 49, + 48 + ] + ], + [ + [ + 8531, + 8531 + ], + "mapped", + [ + 49, + 8260, + 51 + ] + ], + [ + [ + 8532, + 8532 + ], + "mapped", + [ + 50, + 8260, + 51 + ] + ], + [ + [ + 8533, + 8533 + ], + "mapped", + [ + 49, + 8260, + 53 + ] + ], + [ + [ + 8534, + 8534 + ], + "mapped", + [ + 50, + 8260, + 53 + ] + ], + [ + [ + 8535, + 8535 + ], + "mapped", + [ + 51, + 8260, + 53 + ] + ], + [ + [ + 8536, + 8536 + ], + "mapped", + [ + 52, + 8260, + 53 + ] + ], + [ + [ + 8537, + 8537 + ], + "mapped", + [ + 49, + 8260, + 54 + ] + ], + [ + [ + 8538, + 8538 + ], + "mapped", + [ + 53, + 8260, + 54 + ] + ], + [ + [ + 8539, + 8539 + ], + "mapped", + [ + 49, + 8260, + 56 + ] + ], + [ + [ + 8540, + 8540 + ], + "mapped", + [ + 51, + 8260, + 56 + ] + ], + [ + [ + 8541, + 8541 + ], + "mapped", + [ + 53, + 8260, + 56 + ] + ], + [ + [ + 8542, + 8542 + ], + "mapped", + [ + 55, + 8260, + 56 + ] + ], + [ + [ + 8543, + 8543 + ], + "mapped", + [ + 49, + 8260 + ] + ], + [ + [ + 8544, + 8544 + ], + "mapped", + [ + 105 + ] + ], + [ + [ + 8545, + 8545 + ], + "mapped", + [ + 105, + 105 + ] + ], + [ + [ + 8546, + 8546 + ], + "mapped", + [ + 105, + 105, + 105 + ] + ], + [ + [ + 8547, + 8547 + ], + "mapped", + [ + 105, + 118 + ] + ], + [ + [ + 8548, + 8548 + ], + "mapped", + [ + 118 + ] + ], + [ + [ + 8549, + 8549 + ], + "mapped", + [ + 118, + 105 + ] + ], + [ + [ + 8550, + 8550 + ], + "mapped", + [ + 118, + 105, + 105 + ] + ], + [ + [ + 8551, + 8551 + ], + "mapped", + [ + 118, + 105, + 105, + 105 + ] + ], + [ + [ + 8552, + 8552 + ], + "mapped", + [ + 105, + 120 + ] + ], + [ + [ + 8553, + 8553 + ], + "mapped", + [ + 120 + ] + ], + [ + [ + 8554, + 8554 + ], + "mapped", + [ + 120, + 105 + ] + ], + [ + [ + 8555, + 8555 + ], + "mapped", + [ + 120, + 105, + 105 + ] + ], + [ + [ + 8556, + 8556 + ], + "mapped", + [ + 108 + ] + ], + [ + [ + 8557, + 8557 + ], + "mapped", + [ + 99 + ] + ], + [ + [ + 8558, + 8558 + ], + "mapped", + [ + 100 + ] + ], + [ + [ + 8559, + 8559 + ], + "mapped", + [ + 109 + ] + ], + [ + [ + 8560, + 8560 + ], + "mapped", + [ + 105 + ] + ], + [ + [ + 8561, + 8561 + ], + "mapped", + [ + 105, + 105 + ] + ], + [ + [ + 8562, + 8562 + ], + "mapped", + [ + 105, + 105, + 105 + ] + ], + [ + [ + 8563, + 8563 + ], + "mapped", + [ + 105, + 118 + ] + ], + [ + [ + 8564, + 8564 + ], + "mapped", + [ + 118 + ] + ], + [ + [ + 8565, + 8565 + ], + "mapped", + [ + 118, + 105 + ] + ], + [ + [ + 8566, + 8566 + ], + "mapped", + [ + 118, + 105, + 105 + ] + ], + [ + [ + 8567, + 8567 + ], + "mapped", + [ + 118, + 105, + 105, + 105 + ] + ], + [ + [ + 8568, + 8568 + ], + "mapped", + [ + 105, + 120 + ] + ], + [ + [ + 8569, + 8569 + ], + "mapped", + [ + 120 + ] + ], + [ + [ + 8570, + 8570 + ], + "mapped", + [ + 120, + 105 + ] + ], + [ + [ + 8571, + 8571 + ], + "mapped", + [ + 120, + 105, + 105 + ] + ], + [ + [ + 8572, + 8572 + ], + "mapped", + [ + 108 + ] + ], + [ + [ + 8573, + 8573 + ], + "mapped", + [ + 99 + ] + ], + [ + [ + 8574, + 8574 + ], + "mapped", + [ + 100 + ] + ], + [ + [ + 8575, + 8575 + ], + "mapped", + [ + 109 + ] + ], + [ + [ + 8576, + 8578 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 8579, + 8579 + ], + "disallowed" + ], + [ + [ + 8580, + 8580 + ], + "valid" + ], + [ + [ + 8581, + 8584 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 8585, + 8585 + ], + "mapped", + [ + 48, + 8260, + 51 + ] + ], + [ + [ + 8586, + 8587 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 8588, + 8591 + ], + "disallowed" + ], + [ + [ + 8592, + 8682 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 8683, + 8691 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 8692, + 8703 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 8704, + 8747 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 8748, + 8748 + ], + "mapped", + [ + 8747, + 8747 + ] + ], + [ + [ + 8749, + 8749 + ], + "mapped", + [ + 8747, + 8747, + 8747 + ] + ], + [ + [ + 8750, + 8750 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 8751, + 8751 + ], + "mapped", + [ + 8750, + 8750 + ] + ], + [ + [ + 8752, + 8752 + ], + "mapped", + [ + 8750, + 8750, + 8750 + ] + ], + [ + [ + 8753, + 8799 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 8800, + 8800 + ], + "disallowed_STD3_valid" + ], + [ + [ + 8801, + 8813 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 8814, + 8815 + ], + "disallowed_STD3_valid" + ], + [ + [ + 8816, + 8945 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 8946, + 8959 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 8960, + 8960 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 8961, + 8961 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 8962, + 9000 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 9001, + 9001 + ], + "mapped", + [ + 12296 + ] + ], + [ + [ + 9002, + 9002 + ], + "mapped", + [ + 12297 + ] + ], + [ + [ + 9003, + 9082 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 9083, + 9083 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 9084, + 9084 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 9085, + 9114 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 9115, + 9166 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 9167, + 9168 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 9169, + 9179 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 9180, + 9191 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 9192, + 9192 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 9193, + 9203 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 9204, + 9210 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 9211, + 9215 + ], + "disallowed" + ], + [ + [ + 9216, + 9252 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 9253, + 9254 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 9255, + 9279 + ], + "disallowed" + ], + [ + [ + 9280, + 9290 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 9291, + 9311 + ], + "disallowed" + ], + [ + [ + 9312, + 9312 + ], + "mapped", + [ + 49 + ] + ], + [ + [ + 9313, + 9313 + ], + "mapped", + [ + 50 + ] + ], + [ + [ + 9314, + 9314 + ], + "mapped", + [ + 51 + ] + ], + [ + [ + 9315, + 9315 + ], + "mapped", + [ + 52 + ] + ], + [ + [ + 9316, + 9316 + ], + "mapped", + [ + 53 + ] + ], + [ + [ + 9317, + 9317 + ], + "mapped", + [ + 54 + ] + ], + [ + [ + 9318, + 9318 + ], + "mapped", + [ + 55 + ] + ], + [ + [ + 9319, + 9319 + ], + "mapped", + [ + 56 + ] + ], + [ + [ + 9320, + 9320 + ], + "mapped", + [ + 57 + ] + ], + [ + [ + 9321, + 9321 + ], + "mapped", + [ + 49, + 48 + ] + ], + [ + [ + 9322, + 9322 + ], + "mapped", + [ + 49, + 49 + ] + ], + [ + [ + 9323, + 9323 + ], + "mapped", + [ + 49, + 50 + ] + ], + [ + [ + 9324, + 9324 + ], + "mapped", + [ + 49, + 51 + ] + ], + [ + [ + 9325, + 9325 + ], + "mapped", + [ + 49, + 52 + ] + ], + [ + [ + 9326, + 9326 + ], + "mapped", + [ + 49, + 53 + ] + ], + [ + [ + 9327, + 9327 + ], + "mapped", + [ + 49, + 54 + ] + ], + [ + [ + 9328, + 9328 + ], + "mapped", + [ + 49, + 55 + ] + ], + [ + [ + 9329, + 9329 + ], + "mapped", + [ + 49, + 56 + ] + ], + [ + [ + 9330, + 9330 + ], + "mapped", + [ + 49, + 57 + ] + ], + [ + [ + 9331, + 9331 + ], + "mapped", + [ + 50, + 48 + ] + ], + [ + [ + 9332, + 9332 + ], + "disallowed_STD3_mapped", + [ + 40, + 49, + 41 + ] + ], + [ + [ + 9333, + 9333 + ], + "disallowed_STD3_mapped", + [ + 40, + 50, + 41 + ] + ], + [ + [ + 9334, + 9334 + ], + "disallowed_STD3_mapped", + [ + 40, + 51, + 41 + ] + ], + [ + [ + 9335, + 9335 + ], + "disallowed_STD3_mapped", + [ + 40, + 52, + 41 + ] + ], + [ + [ + 9336, + 9336 + ], + "disallowed_STD3_mapped", + [ + 40, + 53, + 41 + ] + ], + [ + [ + 9337, + 9337 + ], + "disallowed_STD3_mapped", + [ + 40, + 54, + 41 + ] + ], + [ + [ + 9338, + 9338 + ], + "disallowed_STD3_mapped", + [ + 40, + 55, + 41 + ] + ], + [ + [ + 9339, + 9339 + ], + "disallowed_STD3_mapped", + [ + 40, + 56, + 41 + ] + ], + [ + [ + 9340, + 9340 + ], + "disallowed_STD3_mapped", + [ + 40, + 57, + 41 + ] + ], + [ + [ + 9341, + 9341 + ], + "disallowed_STD3_mapped", + [ + 40, + 49, + 48, + 41 + ] + ], + [ + [ + 9342, + 9342 + ], + "disallowed_STD3_mapped", + [ + 40, + 49, + 49, + 41 + ] + ], + [ + [ + 9343, + 9343 + ], + "disallowed_STD3_mapped", + [ + 40, + 49, + 50, + 41 + ] + ], + [ + [ + 9344, + 9344 + ], + "disallowed_STD3_mapped", + [ + 40, + 49, + 51, + 41 + ] + ], + [ + [ + 9345, + 9345 + ], + "disallowed_STD3_mapped", + [ + 40, + 49, + 52, + 41 + ] + ], + [ + [ + 9346, + 9346 + ], + "disallowed_STD3_mapped", + [ + 40, + 49, + 53, + 41 + ] + ], + [ + [ + 9347, + 9347 + ], + "disallowed_STD3_mapped", + [ + 40, + 49, + 54, + 41 + ] + ], + [ + [ + 9348, + 9348 + ], + "disallowed_STD3_mapped", + [ + 40, + 49, + 55, + 41 + ] + ], + [ + [ + 9349, + 9349 + ], + "disallowed_STD3_mapped", + [ + 40, + 49, + 56, + 41 + ] + ], + [ + [ + 9350, + 9350 + ], + "disallowed_STD3_mapped", + [ + 40, + 49, + 57, + 41 + ] + ], + [ + [ + 9351, + 9351 + ], + "disallowed_STD3_mapped", + [ + 40, + 50, + 48, + 41 + ] + ], + [ + [ + 9352, + 9371 + ], + "disallowed" + ], + [ + [ + 9372, + 9372 + ], + "disallowed_STD3_mapped", + [ + 40, + 97, + 41 + ] + ], + [ + [ + 9373, + 9373 + ], + "disallowed_STD3_mapped", + [ + 40, + 98, + 41 + ] + ], + [ + [ + 9374, + 9374 + ], + "disallowed_STD3_mapped", + [ + 40, + 99, + 41 + ] + ], + [ + [ + 9375, + 9375 + ], + "disallowed_STD3_mapped", + [ + 40, + 100, + 41 + ] + ], + [ + [ + 9376, + 9376 + ], + "disallowed_STD3_mapped", + [ + 40, + 101, + 41 + ] + ], + [ + [ + 9377, + 9377 + ], + "disallowed_STD3_mapped", + [ + 40, + 102, + 41 + ] + ], + [ + [ + 9378, + 9378 + ], + "disallowed_STD3_mapped", + [ + 40, + 103, + 41 + ] + ], + [ + [ + 9379, + 9379 + ], + "disallowed_STD3_mapped", + [ + 40, + 104, + 41 + ] + ], + [ + [ + 9380, + 9380 + ], + "disallowed_STD3_mapped", + [ + 40, + 105, + 41 + ] + ], + [ + [ + 9381, + 9381 + ], + "disallowed_STD3_mapped", + [ + 40, + 106, + 41 + ] + ], + [ + [ + 9382, + 9382 + ], + "disallowed_STD3_mapped", + [ + 40, + 107, + 41 + ] + ], + [ + [ + 9383, + 9383 + ], + "disallowed_STD3_mapped", + [ + 40, + 108, + 41 + ] + ], + [ + [ + 9384, + 9384 + ], + "disallowed_STD3_mapped", + [ + 40, + 109, + 41 + ] + ], + [ + [ + 9385, + 9385 + ], + "disallowed_STD3_mapped", + [ + 40, + 110, + 41 + ] + ], + [ + [ + 9386, + 9386 + ], + "disallowed_STD3_mapped", + [ + 40, + 111, + 41 + ] + ], + [ + [ + 9387, + 9387 + ], + "disallowed_STD3_mapped", + [ + 40, + 112, + 41 + ] + ], + [ + [ + 9388, + 9388 + ], + "disallowed_STD3_mapped", + [ + 40, + 113, + 41 + ] + ], + [ + [ + 9389, + 9389 + ], + "disallowed_STD3_mapped", + [ + 40, + 114, + 41 + ] + ], + [ + [ + 9390, + 9390 + ], + "disallowed_STD3_mapped", + [ + 40, + 115, + 41 + ] + ], + [ + [ + 9391, + 9391 + ], + "disallowed_STD3_mapped", + [ + 40, + 116, + 41 + ] + ], + [ + [ + 9392, + 9392 + ], + "disallowed_STD3_mapped", + [ + 40, + 117, + 41 + ] + ], + [ + [ + 9393, + 9393 + ], + "disallowed_STD3_mapped", + [ + 40, + 118, + 41 + ] + ], + [ + [ + 9394, + 9394 + ], + "disallowed_STD3_mapped", + [ + 40, + 119, + 41 + ] + ], + [ + [ + 9395, + 9395 + ], + "disallowed_STD3_mapped", + [ + 40, + 120, + 41 + ] + ], + [ + [ + 9396, + 9396 + ], + "disallowed_STD3_mapped", + [ + 40, + 121, + 41 + ] + ], + [ + [ + 9397, + 9397 + ], + "disallowed_STD3_mapped", + [ + 40, + 122, + 41 + ] + ], + [ + [ + 9398, + 9398 + ], + "mapped", + [ + 97 + ] + ], + [ + [ + 9399, + 9399 + ], + "mapped", + [ + 98 + ] + ], + [ + [ + 9400, + 9400 + ], + "mapped", + [ + 99 + ] + ], + [ + [ + 9401, + 9401 + ], + "mapped", + [ + 100 + ] + ], + [ + [ + 9402, + 9402 + ], + "mapped", + [ + 101 + ] + ], + [ + [ + 9403, + 9403 + ], + "mapped", + [ + 102 + ] + ], + [ + [ + 9404, + 9404 + ], + "mapped", + [ + 103 + ] + ], + [ + [ + 9405, + 9405 + ], + "mapped", + [ + 104 + ] + ], + [ + [ + 9406, + 9406 + ], + "mapped", + [ + 105 + ] + ], + [ + [ + 9407, + 9407 + ], + "mapped", + [ + 106 + ] + ], + [ + [ + 9408, + 9408 + ], + "mapped", + [ + 107 + ] + ], + [ + [ + 9409, + 9409 + ], + "mapped", + [ + 108 + ] + ], + [ + [ + 9410, + 9410 + ], + "mapped", + [ + 109 + ] + ], + [ + [ + 9411, + 9411 + ], + "mapped", + [ + 110 + ] + ], + [ + [ + 9412, + 9412 + ], + "mapped", + [ + 111 + ] + ], + [ + [ + 9413, + 9413 + ], + "mapped", + [ + 112 + ] + ], + [ + [ + 9414, + 9414 + ], + "mapped", + [ + 113 + ] + ], + [ + [ + 9415, + 9415 + ], + "mapped", + [ + 114 + ] + ], + [ + [ + 9416, + 9416 + ], + "mapped", + [ + 115 + ] + ], + [ + [ + 9417, + 9417 + ], + "mapped", + [ + 116 + ] + ], + [ + [ + 9418, + 9418 + ], + "mapped", + [ + 117 + ] + ], + [ + [ + 9419, + 9419 + ], + "mapped", + [ + 118 + ] + ], + [ + [ + 9420, + 9420 + ], + "mapped", + [ + 119 + ] + ], + [ + [ + 9421, + 9421 + ], + "mapped", + [ + 120 + ] + ], + [ + [ + 9422, + 9422 + ], + "mapped", + [ + 121 + ] + ], + [ + [ + 9423, + 9423 + ], + "mapped", + [ + 122 + ] + ], + [ + [ + 9424, + 9424 + ], + "mapped", + [ + 97 + ] + ], + [ + [ + 9425, + 9425 + ], + "mapped", + [ + 98 + ] + ], + [ + [ + 9426, + 9426 + ], + "mapped", + [ + 99 + ] + ], + [ + [ + 9427, + 9427 + ], + "mapped", + [ + 100 + ] + ], + [ + [ + 9428, + 9428 + ], + "mapped", + [ + 101 + ] + ], + [ + [ + 9429, + 9429 + ], + "mapped", + [ + 102 + ] + ], + [ + [ + 9430, + 9430 + ], + "mapped", + [ + 103 + ] + ], + [ + [ + 9431, + 9431 + ], + "mapped", + [ + 104 + ] + ], + [ + [ + 9432, + 9432 + ], + "mapped", + [ + 105 + ] + ], + [ + [ + 9433, + 9433 + ], + "mapped", + [ + 106 + ] + ], + [ + [ + 9434, + 9434 + ], + "mapped", + [ + 107 + ] + ], + [ + [ + 9435, + 9435 + ], + "mapped", + [ + 108 + ] + ], + [ + [ + 9436, + 9436 + ], + "mapped", + [ + 109 + ] + ], + [ + [ + 9437, + 9437 + ], + "mapped", + [ + 110 + ] + ], + [ + [ + 9438, + 9438 + ], + "mapped", + [ + 111 + ] + ], + [ + [ + 9439, + 9439 + ], + "mapped", + [ + 112 + ] + ], + [ + [ + 9440, + 9440 + ], + "mapped", + [ + 113 + ] + ], + [ + [ + 9441, + 9441 + ], + "mapped", + [ + 114 + ] + ], + [ + [ + 9442, + 9442 + ], + "mapped", + [ + 115 + ] + ], + [ + [ + 9443, + 9443 + ], + "mapped", + [ + 116 + ] + ], + [ + [ + 9444, + 9444 + ], + "mapped", + [ + 117 + ] + ], + [ + [ + 9445, + 9445 + ], + "mapped", + [ + 118 + ] + ], + [ + [ + 9446, + 9446 + ], + "mapped", + [ + 119 + ] + ], + [ + [ + 9447, + 9447 + ], + "mapped", + [ + 120 + ] + ], + [ + [ + 9448, + 9448 + ], + "mapped", + [ + 121 + ] + ], + [ + [ + 9449, + 9449 + ], + "mapped", + [ + 122 + ] + ], + [ + [ + 9450, + 9450 + ], + "mapped", + [ + 48 + ] + ], + [ + [ + 9451, + 9470 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 9471, + 9471 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 9472, + 9621 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 9622, + 9631 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 9632, + 9711 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 9712, + 9719 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 9720, + 9727 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 9728, + 9747 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 9748, + 9749 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 9750, + 9751 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 9752, + 9752 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 9753, + 9753 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 9754, + 9839 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 9840, + 9841 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 9842, + 9853 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 9854, + 9855 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 9856, + 9865 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 9866, + 9873 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 9874, + 9884 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 9885, + 9885 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 9886, + 9887 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 9888, + 9889 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 9890, + 9905 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 9906, + 9906 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 9907, + 9916 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 9917, + 9919 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 9920, + 9923 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 9924, + 9933 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 9934, + 9934 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 9935, + 9953 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 9954, + 9954 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 9955, + 9955 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 9956, + 9959 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 9960, + 9983 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 9984, + 9984 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 9985, + 9988 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 9989, + 9989 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 9990, + 9993 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 9994, + 9995 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 9996, + 10023 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 10024, + 10024 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 10025, + 10059 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 10060, + 10060 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 10061, + 10061 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 10062, + 10062 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 10063, + 10066 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 10067, + 10069 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 10070, + 10070 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 10071, + 10071 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 10072, + 10078 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 10079, + 10080 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 10081, + 10087 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 10088, + 10101 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 10102, + 10132 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 10133, + 10135 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 10136, + 10159 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 10160, + 10160 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 10161, + 10174 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 10175, + 10175 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 10176, + 10182 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 10183, + 10186 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 10187, + 10187 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 10188, + 10188 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 10189, + 10189 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 10190, + 10191 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 10192, + 10219 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 10220, + 10223 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 10224, + 10239 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 10240, + 10495 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 10496, + 10763 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 10764, + 10764 + ], + "mapped", + [ + 8747, + 8747, + 8747, + 8747 + ] + ], + [ + [ + 10765, + 10867 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 10868, + 10868 + ], + "disallowed_STD3_mapped", + [ + 58, + 58, + 61 + ] + ], + [ + [ + 10869, + 10869 + ], + "disallowed_STD3_mapped", + [ + 61, + 61 + ] + ], + [ + [ + 10870, + 10870 + ], + "disallowed_STD3_mapped", + [ + 61, + 61, + 61 + ] + ], + [ + [ + 10871, + 10971 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 10972, + 10972 + ], + "mapped", + [ + 10973, + 824 + ] + ], + [ + [ + 10973, + 11007 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 11008, + 11021 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 11022, + 11027 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 11028, + 11034 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 11035, + 11039 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 11040, + 11043 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 11044, + 11084 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 11085, + 11087 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 11088, + 11092 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 11093, + 11097 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 11098, + 11123 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 11124, + 11125 + ], + "disallowed" + ], + [ + [ + 11126, + 11157 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 11158, + 11159 + ], + "disallowed" + ], + [ + [ + 11160, + 11193 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 11194, + 11196 + ], + "disallowed" + ], + [ + [ + 11197, + 11208 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 11209, + 11209 + ], + "disallowed" + ], + [ + [ + 11210, + 11217 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 11218, + 11243 + ], + "disallowed" + ], + [ + [ + 11244, + 11247 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 11248, + 11263 + ], + "disallowed" + ], + [ + [ + 11264, + 11264 + ], + "mapped", + [ + 11312 + ] + ], + [ + [ + 11265, + 11265 + ], + "mapped", + [ + 11313 + ] + ], + [ + [ + 11266, + 11266 + ], + "mapped", + [ + 11314 + ] + ], + [ + [ + 11267, + 11267 + ], + "mapped", + [ + 11315 + ] + ], + [ + [ + 11268, + 11268 + ], + "mapped", + [ + 11316 + ] + ], + [ + [ + 11269, + 11269 + ], + "mapped", + [ + 11317 + ] + ], + [ + [ + 11270, + 11270 + ], + "mapped", + [ + 11318 + ] + ], + [ + [ + 11271, + 11271 + ], + "mapped", + [ + 11319 + ] + ], + [ + [ + 11272, + 11272 + ], + "mapped", + [ + 11320 + ] + ], + [ + [ + 11273, + 11273 + ], + "mapped", + [ + 11321 + ] + ], + [ + [ + 11274, + 11274 + ], + "mapped", + [ + 11322 + ] + ], + [ + [ + 11275, + 11275 + ], + "mapped", + [ + 11323 + ] + ], + [ + [ + 11276, + 11276 + ], + "mapped", + [ + 11324 + ] + ], + [ + [ + 11277, + 11277 + ], + "mapped", + [ + 11325 + ] + ], + [ + [ + 11278, + 11278 + ], + "mapped", + [ + 11326 + ] + ], + [ + [ + 11279, + 11279 + ], + "mapped", + [ + 11327 + ] + ], + [ + [ + 11280, + 11280 + ], + "mapped", + [ + 11328 + ] + ], + [ + [ + 11281, + 11281 + ], + "mapped", + [ + 11329 + ] + ], + [ + [ + 11282, + 11282 + ], + "mapped", + [ + 11330 + ] + ], + [ + [ + 11283, + 11283 + ], + "mapped", + [ + 11331 + ] + ], + [ + [ + 11284, + 11284 + ], + "mapped", + [ + 11332 + ] + ], + [ + [ + 11285, + 11285 + ], + "mapped", + [ + 11333 + ] + ], + [ + [ + 11286, + 11286 + ], + "mapped", + [ + 11334 + ] + ], + [ + [ + 11287, + 11287 + ], + "mapped", + [ + 11335 + ] + ], + [ + [ + 11288, + 11288 + ], + "mapped", + [ + 11336 + ] + ], + [ + [ + 11289, + 11289 + ], + "mapped", + [ + 11337 + ] + ], + [ + [ + 11290, + 11290 + ], + "mapped", + [ + 11338 + ] + ], + [ + [ + 11291, + 11291 + ], + "mapped", + [ + 11339 + ] + ], + [ + [ + 11292, + 11292 + ], + "mapped", + [ + 11340 + ] + ], + [ + [ + 11293, + 11293 + ], + "mapped", + [ + 11341 + ] + ], + [ + [ + 11294, + 11294 + ], + "mapped", + [ + 11342 + ] + ], + [ + [ + 11295, + 11295 + ], + "mapped", + [ + 11343 + ] + ], + [ + [ + 11296, + 11296 + ], + "mapped", + [ + 11344 + ] + ], + [ + [ + 11297, + 11297 + ], + "mapped", + [ + 11345 + ] + ], + [ + [ + 11298, + 11298 + ], + "mapped", + [ + 11346 + ] + ], + [ + [ + 11299, + 11299 + ], + "mapped", + [ + 11347 + ] + ], + [ + [ + 11300, + 11300 + ], + "mapped", + [ + 11348 + ] + ], + [ + [ + 11301, + 11301 + ], + "mapped", + [ + 11349 + ] + ], + [ + [ + 11302, + 11302 + ], + "mapped", + [ + 11350 + ] + ], + [ + [ + 11303, + 11303 + ], + "mapped", + [ + 11351 + ] + ], + [ + [ + 11304, + 11304 + ], + "mapped", + [ + 11352 + ] + ], + [ + [ + 11305, + 11305 + ], + "mapped", + [ + 11353 + ] + ], + [ + [ + 11306, + 11306 + ], + "mapped", + [ + 11354 + ] + ], + [ + [ + 11307, + 11307 + ], + "mapped", + [ + 11355 + ] + ], + [ + [ + 11308, + 11308 + ], + "mapped", + [ + 11356 + ] + ], + [ + [ + 11309, + 11309 + ], + "mapped", + [ + 11357 + ] + ], + [ + [ + 11310, + 11310 + ], + "mapped", + [ + 11358 + ] + ], + [ + [ + 11311, + 11311 + ], + "disallowed" + ], + [ + [ + 11312, + 11358 + ], + "valid" + ], + [ + [ + 11359, + 11359 + ], + "disallowed" + ], + [ + [ + 11360, + 11360 + ], + "mapped", + [ + 11361 + ] + ], + [ + [ + 11361, + 11361 + ], + "valid" + ], + [ + [ + 11362, + 11362 + ], + "mapped", + [ + 619 + ] + ], + [ + [ + 11363, + 11363 + ], + "mapped", + [ + 7549 + ] + ], + [ + [ + 11364, + 11364 + ], + "mapped", + [ + 637 + ] + ], + [ + [ + 11365, + 11366 + ], + "valid" + ], + [ + [ + 11367, + 11367 + ], + "mapped", + [ + 11368 + ] + ], + [ + [ + 11368, + 11368 + ], + "valid" + ], + [ + [ + 11369, + 11369 + ], + "mapped", + [ + 11370 + ] + ], + [ + [ + 11370, + 11370 + ], + "valid" + ], + [ + [ + 11371, + 11371 + ], + "mapped", + [ + 11372 + ] + ], + [ + [ + 11372, + 11372 + ], + "valid" + ], + [ + [ + 11373, + 11373 + ], + "mapped", + [ + 593 + ] + ], + [ + [ + 11374, + 11374 + ], + "mapped", + [ + 625 + ] + ], + [ + [ + 11375, + 11375 + ], + "mapped", + [ + 592 + ] + ], + [ + [ + 11376, + 11376 + ], + "mapped", + [ + 594 + ] + ], + [ + [ + 11377, + 11377 + ], + "valid" + ], + [ + [ + 11378, + 11378 + ], + "mapped", + [ + 11379 + ] + ], + [ + [ + 11379, + 11379 + ], + "valid" + ], + [ + [ + 11380, + 11380 + ], + "valid" + ], + [ + [ + 11381, + 11381 + ], + "mapped", + [ + 11382 + ] + ], + [ + [ + 11382, + 11383 + ], + "valid" + ], + [ + [ + 11384, + 11387 + ], + "valid" + ], + [ + [ + 11388, + 11388 + ], + "mapped", + [ + 106 + ] + ], + [ + [ + 11389, + 11389 + ], + "mapped", + [ + 118 + ] + ], + [ + [ + 11390, + 11390 + ], + "mapped", + [ + 575 + ] + ], + [ + [ + 11391, + 11391 + ], + "mapped", + [ + 576 + ] + ], + [ + [ + 11392, + 11392 + ], + "mapped", + [ + 11393 + ] + ], + [ + [ + 11393, + 11393 + ], + "valid" + ], + [ + [ + 11394, + 11394 + ], + "mapped", + [ + 11395 + ] + ], + [ + [ + 11395, + 11395 + ], + "valid" + ], + [ + [ + 11396, + 11396 + ], + "mapped", + [ + 11397 + ] + ], + [ + [ + 11397, + 11397 + ], + "valid" + ], + [ + [ + 11398, + 11398 + ], + "mapped", + [ + 11399 + ] + ], + [ + [ + 11399, + 11399 + ], + "valid" + ], + [ + [ + 11400, + 11400 + ], + "mapped", + [ + 11401 + ] + ], + [ + [ + 11401, + 11401 + ], + "valid" + ], + [ + [ + 11402, + 11402 + ], + "mapped", + [ + 11403 + ] + ], + [ + [ + 11403, + 11403 + ], + "valid" + ], + [ + [ + 11404, + 11404 + ], + "mapped", + [ + 11405 + ] + ], + [ + [ + 11405, + 11405 + ], + "valid" + ], + [ + [ + 11406, + 11406 + ], + "mapped", + [ + 11407 + ] + ], + [ + [ + 11407, + 11407 + ], + "valid" + ], + [ + [ + 11408, + 11408 + ], + "mapped", + [ + 11409 + ] + ], + [ + [ + 11409, + 11409 + ], + "valid" + ], + [ + [ + 11410, + 11410 + ], + "mapped", + [ + 11411 + ] + ], + [ + [ + 11411, + 11411 + ], + "valid" + ], + [ + [ + 11412, + 11412 + ], + "mapped", + [ + 11413 + ] + ], + [ + [ + 11413, + 11413 + ], + "valid" + ], + [ + [ + 11414, + 11414 + ], + "mapped", + [ + 11415 + ] + ], + [ + [ + 11415, + 11415 + ], + "valid" + ], + [ + [ + 11416, + 11416 + ], + "mapped", + [ + 11417 + ] + ], + [ + [ + 11417, + 11417 + ], + "valid" + ], + [ + [ + 11418, + 11418 + ], + "mapped", + [ + 11419 + ] + ], + [ + [ + 11419, + 11419 + ], + "valid" + ], + [ + [ + 11420, + 11420 + ], + "mapped", + [ + 11421 + ] + ], + [ + [ + 11421, + 11421 + ], + "valid" + ], + [ + [ + 11422, + 11422 + ], + "mapped", + [ + 11423 + ] + ], + [ + [ + 11423, + 11423 + ], + "valid" + ], + [ + [ + 11424, + 11424 + ], + "mapped", + [ + 11425 + ] + ], + [ + [ + 11425, + 11425 + ], + "valid" + ], + [ + [ + 11426, + 11426 + ], + "mapped", + [ + 11427 + ] + ], + [ + [ + 11427, + 11427 + ], + "valid" + ], + [ + [ + 11428, + 11428 + ], + "mapped", + [ + 11429 + ] + ], + [ + [ + 11429, + 11429 + ], + "valid" + ], + [ + [ + 11430, + 11430 + ], + "mapped", + [ + 11431 + ] + ], + [ + [ + 11431, + 11431 + ], + "valid" + ], + [ + [ + 11432, + 11432 + ], + "mapped", + [ + 11433 + ] + ], + [ + [ + 11433, + 11433 + ], + "valid" + ], + [ + [ + 11434, + 11434 + ], + "mapped", + [ + 11435 + ] + ], + [ + [ + 11435, + 11435 + ], + "valid" + ], + [ + [ + 11436, + 11436 + ], + "mapped", + [ + 11437 + ] + ], + [ + [ + 11437, + 11437 + ], + "valid" + ], + [ + [ + 11438, + 11438 + ], + "mapped", + [ + 11439 + ] + ], + [ + [ + 11439, + 11439 + ], + "valid" + ], + [ + [ + 11440, + 11440 + ], + "mapped", + [ + 11441 + ] + ], + [ + [ + 11441, + 11441 + ], + "valid" + ], + [ + [ + 11442, + 11442 + ], + "mapped", + [ + 11443 + ] + ], + [ + [ + 11443, + 11443 + ], + "valid" + ], + [ + [ + 11444, + 11444 + ], + "mapped", + [ + 11445 + ] + ], + [ + [ + 11445, + 11445 + ], + "valid" + ], + [ + [ + 11446, + 11446 + ], + "mapped", + [ + 11447 + ] + ], + [ + [ + 11447, + 11447 + ], + "valid" + ], + [ + [ + 11448, + 11448 + ], + "mapped", + [ + 11449 + ] + ], + [ + [ + 11449, + 11449 + ], + "valid" + ], + [ + [ + 11450, + 11450 + ], + "mapped", + [ + 11451 + ] + ], + [ + [ + 11451, + 11451 + ], + "valid" + ], + [ + [ + 11452, + 11452 + ], + "mapped", + [ + 11453 + ] + ], + [ + [ + 11453, + 11453 + ], + "valid" + ], + [ + [ + 11454, + 11454 + ], + "mapped", + [ + 11455 + ] + ], + [ + [ + 11455, + 11455 + ], + "valid" + ], + [ + [ + 11456, + 11456 + ], + "mapped", + [ + 11457 + ] + ], + [ + [ + 11457, + 11457 + ], + "valid" + ], + [ + [ + 11458, + 11458 + ], + "mapped", + [ + 11459 + ] + ], + [ + [ + 11459, + 11459 + ], + "valid" + ], + [ + [ + 11460, + 11460 + ], + "mapped", + [ + 11461 + ] + ], + [ + [ + 11461, + 11461 + ], + "valid" + ], + [ + [ + 11462, + 11462 + ], + "mapped", + [ + 11463 + ] + ], + [ + [ + 11463, + 11463 + ], + "valid" + ], + [ + [ + 11464, + 11464 + ], + "mapped", + [ + 11465 + ] + ], + [ + [ + 11465, + 11465 + ], + "valid" + ], + [ + [ + 11466, + 11466 + ], + "mapped", + [ + 11467 + ] + ], + [ + [ + 11467, + 11467 + ], + "valid" + ], + [ + [ + 11468, + 11468 + ], + "mapped", + [ + 11469 + ] + ], + [ + [ + 11469, + 11469 + ], + "valid" + ], + [ + [ + 11470, + 11470 + ], + "mapped", + [ + 11471 + ] + ], + [ + [ + 11471, + 11471 + ], + "valid" + ], + [ + [ + 11472, + 11472 + ], + "mapped", + [ + 11473 + ] + ], + [ + [ + 11473, + 11473 + ], + "valid" + ], + [ + [ + 11474, + 11474 + ], + "mapped", + [ + 11475 + ] + ], + [ + [ + 11475, + 11475 + ], + "valid" + ], + [ + [ + 11476, + 11476 + ], + "mapped", + [ + 11477 + ] + ], + [ + [ + 11477, + 11477 + ], + "valid" + ], + [ + [ + 11478, + 11478 + ], + "mapped", + [ + 11479 + ] + ], + [ + [ + 11479, + 11479 + ], + "valid" + ], + [ + [ + 11480, + 11480 + ], + "mapped", + [ + 11481 + ] + ], + [ + [ + 11481, + 11481 + ], + "valid" + ], + [ + [ + 11482, + 11482 + ], + "mapped", + [ + 11483 + ] + ], + [ + [ + 11483, + 11483 + ], + "valid" + ], + [ + [ + 11484, + 11484 + ], + "mapped", + [ + 11485 + ] + ], + [ + [ + 11485, + 11485 + ], + "valid" + ], + [ + [ + 11486, + 11486 + ], + "mapped", + [ + 11487 + ] + ], + [ + [ + 11487, + 11487 + ], + "valid" + ], + [ + [ + 11488, + 11488 + ], + "mapped", + [ + 11489 + ] + ], + [ + [ + 11489, + 11489 + ], + "valid" + ], + [ + [ + 11490, + 11490 + ], + "mapped", + [ + 11491 + ] + ], + [ + [ + 11491, + 11492 + ], + "valid" + ], + [ + [ + 11493, + 11498 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 11499, + 11499 + ], + "mapped", + [ + 11500 + ] + ], + [ + [ + 11500, + 11500 + ], + "valid" + ], + [ + [ + 11501, + 11501 + ], + "mapped", + [ + 11502 + ] + ], + [ + [ + 11502, + 11505 + ], + "valid" + ], + [ + [ + 11506, + 11506 + ], + "mapped", + [ + 11507 + ] + ], + [ + [ + 11507, + 11507 + ], + "valid" + ], + [ + [ + 11508, + 11512 + ], + "disallowed" + ], + [ + [ + 11513, + 11519 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 11520, + 11557 + ], + "valid" + ], + [ + [ + 11558, + 11558 + ], + "disallowed" + ], + [ + [ + 11559, + 11559 + ], + "valid" + ], + [ + [ + 11560, + 11564 + ], + "disallowed" + ], + [ + [ + 11565, + 11565 + ], + "valid" + ], + [ + [ + 11566, + 11567 + ], + "disallowed" + ], + [ + [ + 11568, + 11621 + ], + "valid" + ], + [ + [ + 11622, + 11623 + ], + "valid" + ], + [ + [ + 11624, + 11630 + ], + "disallowed" + ], + [ + [ + 11631, + 11631 + ], + "mapped", + [ + 11617 + ] + ], + [ + [ + 11632, + 11632 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 11633, + 11646 + ], + "disallowed" + ], + [ + [ + 11647, + 11647 + ], + "valid" + ], + [ + [ + 11648, + 11670 + ], + "valid" + ], + [ + [ + 11671, + 11679 + ], + "disallowed" + ], + [ + [ + 11680, + 11686 + ], + "valid" + ], + [ + [ + 11687, + 11687 + ], + "disallowed" + ], + [ + [ + 11688, + 11694 + ], + "valid" + ], + [ + [ + 11695, + 11695 + ], + "disallowed" + ], + [ + [ + 11696, + 11702 + ], + "valid" + ], + [ + [ + 11703, + 11703 + ], + "disallowed" + ], + [ + [ + 11704, + 11710 + ], + "valid" + ], + [ + [ + 11711, + 11711 + ], + "disallowed" + ], + [ + [ + 11712, + 11718 + ], + "valid" + ], + [ + [ + 11719, + 11719 + ], + "disallowed" + ], + [ + [ + 11720, + 11726 + ], + "valid" + ], + [ + [ + 11727, + 11727 + ], + "disallowed" + ], + [ + [ + 11728, + 11734 + ], + "valid" + ], + [ + [ + 11735, + 11735 + ], + "disallowed" + ], + [ + [ + 11736, + 11742 + ], + "valid" + ], + [ + [ + 11743, + 11743 + ], + "disallowed" + ], + [ + [ + 11744, + 11775 + ], + "valid" + ], + [ + [ + 11776, + 11799 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 11800, + 11803 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 11804, + 11805 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 11806, + 11822 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 11823, + 11823 + ], + "valid" + ], + [ + [ + 11824, + 11824 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 11825, + 11825 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 11826, + 11835 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 11836, + 11842 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 11843, + 11903 + ], + "disallowed" + ], + [ + [ + 11904, + 11929 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 11930, + 11930 + ], + "disallowed" + ], + [ + [ + 11931, + 11934 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 11935, + 11935 + ], + "mapped", + [ + 27597 + ] + ], + [ + [ + 11936, + 12018 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 12019, + 12019 + ], + "mapped", + [ + 40863 + ] + ], + [ + [ + 12020, + 12031 + ], + "disallowed" + ], + [ + [ + 12032, + 12032 + ], + "mapped", + [ + 19968 + ] + ], + [ + [ + 12033, + 12033 + ], + "mapped", + [ + 20008 + ] + ], + [ + [ + 12034, + 12034 + ], + "mapped", + [ + 20022 + ] + ], + [ + [ + 12035, + 12035 + ], + "mapped", + [ + 20031 + ] + ], + [ + [ + 12036, + 12036 + ], + "mapped", + [ + 20057 + ] + ], + [ + [ + 12037, + 12037 + ], + "mapped", + [ + 20101 + ] + ], + [ + [ + 12038, + 12038 + ], + "mapped", + [ + 20108 + ] + ], + [ + [ + 12039, + 12039 + ], + "mapped", + [ + 20128 + ] + ], + [ + [ + 12040, + 12040 + ], + "mapped", + [ + 20154 + ] + ], + [ + [ + 12041, + 12041 + ], + "mapped", + [ + 20799 + ] + ], + [ + [ + 12042, + 12042 + ], + "mapped", + [ + 20837 + ] + ], + [ + [ + 12043, + 12043 + ], + "mapped", + [ + 20843 + ] + ], + [ + [ + 12044, + 12044 + ], + "mapped", + [ + 20866 + ] + ], + [ + [ + 12045, + 12045 + ], + "mapped", + [ + 20886 + ] + ], + [ + [ + 12046, + 12046 + ], + "mapped", + [ + 20907 + ] + ], + [ + [ + 12047, + 12047 + ], + "mapped", + [ + 20960 + ] + ], + [ + [ + 12048, + 12048 + ], + "mapped", + [ + 20981 + ] + ], + [ + [ + 12049, + 12049 + ], + "mapped", + [ + 20992 + ] + ], + [ + [ + 12050, + 12050 + ], + "mapped", + [ + 21147 + ] + ], + [ + [ + 12051, + 12051 + ], + "mapped", + [ + 21241 + ] + ], + [ + [ + 12052, + 12052 + ], + "mapped", + [ + 21269 + ] + ], + [ + [ + 12053, + 12053 + ], + "mapped", + [ + 21274 + ] + ], + [ + [ + 12054, + 12054 + ], + "mapped", + [ + 21304 + ] + ], + [ + [ + 12055, + 12055 + ], + "mapped", + [ + 21313 + ] + ], + [ + [ + 12056, + 12056 + ], + "mapped", + [ + 21340 + ] + ], + [ + [ + 12057, + 12057 + ], + "mapped", + [ + 21353 + ] + ], + [ + [ + 12058, + 12058 + ], + "mapped", + [ + 21378 + ] + ], + [ + [ + 12059, + 12059 + ], + "mapped", + [ + 21430 + ] + ], + [ + [ + 12060, + 12060 + ], + "mapped", + [ + 21448 + ] + ], + [ + [ + 12061, + 12061 + ], + "mapped", + [ + 21475 + ] + ], + [ + [ + 12062, + 12062 + ], + "mapped", + [ + 22231 + ] + ], + [ + [ + 12063, + 12063 + ], + "mapped", + [ + 22303 + ] + ], + [ + [ + 12064, + 12064 + ], + "mapped", + [ + 22763 + ] + ], + [ + [ + 12065, + 12065 + ], + "mapped", + [ + 22786 + ] + ], + [ + [ + 12066, + 12066 + ], + "mapped", + [ + 22794 + ] + ], + [ + [ + 12067, + 12067 + ], + "mapped", + [ + 22805 + ] + ], + [ + [ + 12068, + 12068 + ], + "mapped", + [ + 22823 + ] + ], + [ + [ + 12069, + 12069 + ], + "mapped", + [ + 22899 + ] + ], + [ + [ + 12070, + 12070 + ], + "mapped", + [ + 23376 + ] + ], + [ + [ + 12071, + 12071 + ], + "mapped", + [ + 23424 + ] + ], + [ + [ + 12072, + 12072 + ], + "mapped", + [ + 23544 + ] + ], + [ + [ + 12073, + 12073 + ], + "mapped", + [ + 23567 + ] + ], + [ + [ + 12074, + 12074 + ], + "mapped", + [ + 23586 + ] + ], + [ + [ + 12075, + 12075 + ], + "mapped", + [ + 23608 + ] + ], + [ + [ + 12076, + 12076 + ], + "mapped", + [ + 23662 + ] + ], + [ + [ + 12077, + 12077 + ], + "mapped", + [ + 23665 + ] + ], + [ + [ + 12078, + 12078 + ], + "mapped", + [ + 24027 + ] + ], + [ + [ + 12079, + 12079 + ], + "mapped", + [ + 24037 + ] + ], + [ + [ + 12080, + 12080 + ], + "mapped", + [ + 24049 + ] + ], + [ + [ + 12081, + 12081 + ], + "mapped", + [ + 24062 + ] + ], + [ + [ + 12082, + 12082 + ], + "mapped", + [ + 24178 + ] + ], + [ + [ + 12083, + 12083 + ], + "mapped", + [ + 24186 + ] + ], + [ + [ + 12084, + 12084 + ], + "mapped", + [ + 24191 + ] + ], + [ + [ + 12085, + 12085 + ], + "mapped", + [ + 24308 + ] + ], + [ + [ + 12086, + 12086 + ], + "mapped", + [ + 24318 + ] + ], + [ + [ + 12087, + 12087 + ], + "mapped", + [ + 24331 + ] + ], + [ + [ + 12088, + 12088 + ], + "mapped", + [ + 24339 + ] + ], + [ + [ + 12089, + 12089 + ], + "mapped", + [ + 24400 + ] + ], + [ + [ + 12090, + 12090 + ], + "mapped", + [ + 24417 + ] + ], + [ + [ + 12091, + 12091 + ], + "mapped", + [ + 24435 + ] + ], + [ + [ + 12092, + 12092 + ], + "mapped", + [ + 24515 + ] + ], + [ + [ + 12093, + 12093 + ], + "mapped", + [ + 25096 + ] + ], + [ + [ + 12094, + 12094 + ], + "mapped", + [ + 25142 + ] + ], + [ + [ + 12095, + 12095 + ], + "mapped", + [ + 25163 + ] + ], + [ + [ + 12096, + 12096 + ], + "mapped", + [ + 25903 + ] + ], + [ + [ + 12097, + 12097 + ], + "mapped", + [ + 25908 + ] + ], + [ + [ + 12098, + 12098 + ], + "mapped", + [ + 25991 + ] + ], + [ + [ + 12099, + 12099 + ], + "mapped", + [ + 26007 + ] + ], + [ + [ + 12100, + 12100 + ], + "mapped", + [ + 26020 + ] + ], + [ + [ + 12101, + 12101 + ], + "mapped", + [ + 26041 + ] + ], + [ + [ + 12102, + 12102 + ], + "mapped", + [ + 26080 + ] + ], + [ + [ + 12103, + 12103 + ], + "mapped", + [ + 26085 + ] + ], + [ + [ + 12104, + 12104 + ], + "mapped", + [ + 26352 + ] + ], + [ + [ + 12105, + 12105 + ], + "mapped", + [ + 26376 + ] + ], + [ + [ + 12106, + 12106 + ], + "mapped", + [ + 26408 + ] + ], + [ + [ + 12107, + 12107 + ], + "mapped", + [ + 27424 + ] + ], + [ + [ + 12108, + 12108 + ], + "mapped", + [ + 27490 + ] + ], + [ + [ + 12109, + 12109 + ], + "mapped", + [ + 27513 + ] + ], + [ + [ + 12110, + 12110 + ], + "mapped", + [ + 27571 + ] + ], + [ + [ + 12111, + 12111 + ], + "mapped", + [ + 27595 + ] + ], + [ + [ + 12112, + 12112 + ], + "mapped", + [ + 27604 + ] + ], + [ + [ + 12113, + 12113 + ], + "mapped", + [ + 27611 + ] + ], + [ + [ + 12114, + 12114 + ], + "mapped", + [ + 27663 + ] + ], + [ + [ + 12115, + 12115 + ], + "mapped", + [ + 27668 + ] + ], + [ + [ + 12116, + 12116 + ], + "mapped", + [ + 27700 + ] + ], + [ + [ + 12117, + 12117 + ], + "mapped", + [ + 28779 + ] + ], + [ + [ + 12118, + 12118 + ], + "mapped", + [ + 29226 + ] + ], + [ + [ + 12119, + 12119 + ], + "mapped", + [ + 29238 + ] + ], + [ + [ + 12120, + 12120 + ], + "mapped", + [ + 29243 + ] + ], + [ + [ + 12121, + 12121 + ], + "mapped", + [ + 29247 + ] + ], + [ + [ + 12122, + 12122 + ], + "mapped", + [ + 29255 + ] + ], + [ + [ + 12123, + 12123 + ], + "mapped", + [ + 29273 + ] + ], + [ + [ + 12124, + 12124 + ], + "mapped", + [ + 29275 + ] + ], + [ + [ + 12125, + 12125 + ], + "mapped", + [ + 29356 + ] + ], + [ + [ + 12126, + 12126 + ], + "mapped", + [ + 29572 + ] + ], + [ + [ + 12127, + 12127 + ], + "mapped", + [ + 29577 + ] + ], + [ + [ + 12128, + 12128 + ], + "mapped", + [ + 29916 + ] + ], + [ + [ + 12129, + 12129 + ], + "mapped", + [ + 29926 + ] + ], + [ + [ + 12130, + 12130 + ], + "mapped", + [ + 29976 + ] + ], + [ + [ + 12131, + 12131 + ], + "mapped", + [ + 29983 + ] + ], + [ + [ + 12132, + 12132 + ], + "mapped", + [ + 29992 + ] + ], + [ + [ + 12133, + 12133 + ], + "mapped", + [ + 30000 + ] + ], + [ + [ + 12134, + 12134 + ], + "mapped", + [ + 30091 + ] + ], + [ + [ + 12135, + 12135 + ], + "mapped", + [ + 30098 + ] + ], + [ + [ + 12136, + 12136 + ], + "mapped", + [ + 30326 + ] + ], + [ + [ + 12137, + 12137 + ], + "mapped", + [ + 30333 + ] + ], + [ + [ + 12138, + 12138 + ], + "mapped", + [ + 30382 + ] + ], + [ + [ + 12139, + 12139 + ], + "mapped", + [ + 30399 + ] + ], + [ + [ + 12140, + 12140 + ], + "mapped", + [ + 30446 + ] + ], + [ + [ + 12141, + 12141 + ], + "mapped", + [ + 30683 + ] + ], + [ + [ + 12142, + 12142 + ], + "mapped", + [ + 30690 + ] + ], + [ + [ + 12143, + 12143 + ], + "mapped", + [ + 30707 + ] + ], + [ + [ + 12144, + 12144 + ], + "mapped", + [ + 31034 + ] + ], + [ + [ + 12145, + 12145 + ], + "mapped", + [ + 31160 + ] + ], + [ + [ + 12146, + 12146 + ], + "mapped", + [ + 31166 + ] + ], + [ + [ + 12147, + 12147 + ], + "mapped", + [ + 31348 + ] + ], + [ + [ + 12148, + 12148 + ], + "mapped", + [ + 31435 + ] + ], + [ + [ + 12149, + 12149 + ], + "mapped", + [ + 31481 + ] + ], + [ + [ + 12150, + 12150 + ], + "mapped", + [ + 31859 + ] + ], + [ + [ + 12151, + 12151 + ], + "mapped", + [ + 31992 + ] + ], + [ + [ + 12152, + 12152 + ], + "mapped", + [ + 32566 + ] + ], + [ + [ + 12153, + 12153 + ], + "mapped", + [ + 32593 + ] + ], + [ + [ + 12154, + 12154 + ], + "mapped", + [ + 32650 + ] + ], + [ + [ + 12155, + 12155 + ], + "mapped", + [ + 32701 + ] + ], + [ + [ + 12156, + 12156 + ], + "mapped", + [ + 32769 + ] + ], + [ + [ + 12157, + 12157 + ], + "mapped", + [ + 32780 + ] + ], + [ + [ + 12158, + 12158 + ], + "mapped", + [ + 32786 + ] + ], + [ + [ + 12159, + 12159 + ], + "mapped", + [ + 32819 + ] + ], + [ + [ + 12160, + 12160 + ], + "mapped", + [ + 32895 + ] + ], + [ + [ + 12161, + 12161 + ], + "mapped", + [ + 32905 + ] + ], + [ + [ + 12162, + 12162 + ], + "mapped", + [ + 33251 + ] + ], + [ + [ + 12163, + 12163 + ], + "mapped", + [ + 33258 + ] + ], + [ + [ + 12164, + 12164 + ], + "mapped", + [ + 33267 + ] + ], + [ + [ + 12165, + 12165 + ], + "mapped", + [ + 33276 + ] + ], + [ + [ + 12166, + 12166 + ], + "mapped", + [ + 33292 + ] + ], + [ + [ + 12167, + 12167 + ], + "mapped", + [ + 33307 + ] + ], + [ + [ + 12168, + 12168 + ], + "mapped", + [ + 33311 + ] + ], + [ + [ + 12169, + 12169 + ], + "mapped", + [ + 33390 + ] + ], + [ + [ + 12170, + 12170 + ], + "mapped", + [ + 33394 + ] + ], + [ + [ + 12171, + 12171 + ], + "mapped", + [ + 33400 + ] + ], + [ + [ + 12172, + 12172 + ], + "mapped", + [ + 34381 + ] + ], + [ + [ + 12173, + 12173 + ], + "mapped", + [ + 34411 + ] + ], + [ + [ + 12174, + 12174 + ], + "mapped", + [ + 34880 + ] + ], + [ + [ + 12175, + 12175 + ], + "mapped", + [ + 34892 + ] + ], + [ + [ + 12176, + 12176 + ], + "mapped", + [ + 34915 + ] + ], + [ + [ + 12177, + 12177 + ], + "mapped", + [ + 35198 + ] + ], + [ + [ + 12178, + 12178 + ], + "mapped", + [ + 35211 + ] + ], + [ + [ + 12179, + 12179 + ], + "mapped", + [ + 35282 + ] + ], + [ + [ + 12180, + 12180 + ], + "mapped", + [ + 35328 + ] + ], + [ + [ + 12181, + 12181 + ], + "mapped", + [ + 35895 + ] + ], + [ + [ + 12182, + 12182 + ], + "mapped", + [ + 35910 + ] + ], + [ + [ + 12183, + 12183 + ], + "mapped", + [ + 35925 + ] + ], + [ + [ + 12184, + 12184 + ], + "mapped", + [ + 35960 + ] + ], + [ + [ + 12185, + 12185 + ], + "mapped", + [ + 35997 + ] + ], + [ + [ + 12186, + 12186 + ], + "mapped", + [ + 36196 + ] + ], + [ + [ + 12187, + 12187 + ], + "mapped", + [ + 36208 + ] + ], + [ + [ + 12188, + 12188 + ], + "mapped", + [ + 36275 + ] + ], + [ + [ + 12189, + 12189 + ], + "mapped", + [ + 36523 + ] + ], + [ + [ + 12190, + 12190 + ], + "mapped", + [ + 36554 + ] + ], + [ + [ + 12191, + 12191 + ], + "mapped", + [ + 36763 + ] + ], + [ + [ + 12192, + 12192 + ], + "mapped", + [ + 36784 + ] + ], + [ + [ + 12193, + 12193 + ], + "mapped", + [ + 36789 + ] + ], + [ + [ + 12194, + 12194 + ], + "mapped", + [ + 37009 + ] + ], + [ + [ + 12195, + 12195 + ], + "mapped", + [ + 37193 + ] + ], + [ + [ + 12196, + 12196 + ], + "mapped", + [ + 37318 + ] + ], + [ + [ + 12197, + 12197 + ], + "mapped", + [ + 37324 + ] + ], + [ + [ + 12198, + 12198 + ], + "mapped", + [ + 37329 + ] + ], + [ + [ + 12199, + 12199 + ], + "mapped", + [ + 38263 + ] + ], + [ + [ + 12200, + 12200 + ], + "mapped", + [ + 38272 + ] + ], + [ + [ + 12201, + 12201 + ], + "mapped", + [ + 38428 + ] + ], + [ + [ + 12202, + 12202 + ], + "mapped", + [ + 38582 + ] + ], + [ + [ + 12203, + 12203 + ], + "mapped", + [ + 38585 + ] + ], + [ + [ + 12204, + 12204 + ], + "mapped", + [ + 38632 + ] + ], + [ + [ + 12205, + 12205 + ], + "mapped", + [ + 38737 + ] + ], + [ + [ + 12206, + 12206 + ], + "mapped", + [ + 38750 + ] + ], + [ + [ + 12207, + 12207 + ], + "mapped", + [ + 38754 + ] + ], + [ + [ + 12208, + 12208 + ], + "mapped", + [ + 38761 + ] + ], + [ + [ + 12209, + 12209 + ], + "mapped", + [ + 38859 + ] + ], + [ + [ + 12210, + 12210 + ], + "mapped", + [ + 38893 + ] + ], + [ + [ + 12211, + 12211 + ], + "mapped", + [ + 38899 + ] + ], + [ + [ + 12212, + 12212 + ], + "mapped", + [ + 38913 + ] + ], + [ + [ + 12213, + 12213 + ], + "mapped", + [ + 39080 + ] + ], + [ + [ + 12214, + 12214 + ], + "mapped", + [ + 39131 + ] + ], + [ + [ + 12215, + 12215 + ], + "mapped", + [ + 39135 + ] + ], + [ + [ + 12216, + 12216 + ], + "mapped", + [ + 39318 + ] + ], + [ + [ + 12217, + 12217 + ], + "mapped", + [ + 39321 + ] + ], + [ + [ + 12218, + 12218 + ], + "mapped", + [ + 39340 + ] + ], + [ + [ + 12219, + 12219 + ], + "mapped", + [ + 39592 + ] + ], + [ + [ + 12220, + 12220 + ], + "mapped", + [ + 39640 + ] + ], + [ + [ + 12221, + 12221 + ], + "mapped", + [ + 39647 + ] + ], + [ + [ + 12222, + 12222 + ], + "mapped", + [ + 39717 + ] + ], + [ + [ + 12223, + 12223 + ], + "mapped", + [ + 39727 + ] + ], + [ + [ + 12224, + 12224 + ], + "mapped", + [ + 39730 + ] + ], + [ + [ + 12225, + 12225 + ], + "mapped", + [ + 39740 + ] + ], + [ + [ + 12226, + 12226 + ], + "mapped", + [ + 39770 + ] + ], + [ + [ + 12227, + 12227 + ], + "mapped", + [ + 40165 + ] + ], + [ + [ + 12228, + 12228 + ], + "mapped", + [ + 40565 + ] + ], + [ + [ + 12229, + 12229 + ], + "mapped", + [ + 40575 + ] + ], + [ + [ + 12230, + 12230 + ], + "mapped", + [ + 40613 + ] + ], + [ + [ + 12231, + 12231 + ], + "mapped", + [ + 40635 + ] + ], + [ + [ + 12232, + 12232 + ], + "mapped", + [ + 40643 + ] + ], + [ + [ + 12233, + 12233 + ], + "mapped", + [ + 40653 + ] + ], + [ + [ + 12234, + 12234 + ], + "mapped", + [ + 40657 + ] + ], + [ + [ + 12235, + 12235 + ], + "mapped", + [ + 40697 + ] + ], + [ + [ + 12236, + 12236 + ], + "mapped", + [ + 40701 + ] + ], + [ + [ + 12237, + 12237 + ], + "mapped", + [ + 40718 + ] + ], + [ + [ + 12238, + 12238 + ], + "mapped", + [ + 40723 + ] + ], + [ + [ + 12239, + 12239 + ], + "mapped", + [ + 40736 + ] + ], + [ + [ + 12240, + 12240 + ], + "mapped", + [ + 40763 + ] + ], + [ + [ + 12241, + 12241 + ], + "mapped", + [ + 40778 + ] + ], + [ + [ + 12242, + 12242 + ], + "mapped", + [ + 40786 + ] + ], + [ + [ + 12243, + 12243 + ], + "mapped", + [ + 40845 + ] + ], + [ + [ + 12244, + 12244 + ], + "mapped", + [ + 40860 + ] + ], + [ + [ + 12245, + 12245 + ], + "mapped", + [ + 40864 + ] + ], + [ + [ + 12246, + 12271 + ], + "disallowed" + ], + [ + [ + 12272, + 12283 + ], + "disallowed" + ], + [ + [ + 12284, + 12287 + ], + "disallowed" + ], + [ + [ + 12288, + 12288 + ], + "disallowed_STD3_mapped", + [ + 32 + ] + ], + [ + [ + 12289, + 12289 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 12290, + 12290 + ], + "mapped", + [ + 46 + ] + ], + [ + [ + 12291, + 12292 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 12293, + 12295 + ], + "valid" + ], + [ + [ + 12296, + 12329 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 12330, + 12333 + ], + "valid" + ], + [ + [ + 12334, + 12341 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 12342, + 12342 + ], + "mapped", + [ + 12306 + ] + ], + [ + [ + 12343, + 12343 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 12344, + 12344 + ], + "mapped", + [ + 21313 + ] + ], + [ + [ + 12345, + 12345 + ], + "mapped", + [ + 21316 + ] + ], + [ + [ + 12346, + 12346 + ], + "mapped", + [ + 21317 + ] + ], + [ + [ + 12347, + 12347 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 12348, + 12348 + ], + "valid" + ], + [ + [ + 12349, + 12349 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 12350, + 12350 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 12351, + 12351 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 12352, + 12352 + ], + "disallowed" + ], + [ + [ + 12353, + 12436 + ], + "valid" + ], + [ + [ + 12437, + 12438 + ], + "valid" + ], + [ + [ + 12439, + 12440 + ], + "disallowed" + ], + [ + [ + 12441, + 12442 + ], + "valid" + ], + [ + [ + 12443, + 12443 + ], + "disallowed_STD3_mapped", + [ + 32, + 12441 + ] + ], + [ + [ + 12444, + 12444 + ], + "disallowed_STD3_mapped", + [ + 32, + 12442 + ] + ], + [ + [ + 12445, + 12446 + ], + "valid" + ], + [ + [ + 12447, + 12447 + ], + "mapped", + [ + 12424, + 12426 + ] + ], + [ + [ + 12448, + 12448 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 12449, + 12542 + ], + "valid" + ], + [ + [ + 12543, + 12543 + ], + "mapped", + [ + 12467, + 12488 + ] + ], + [ + [ + 12544, + 12548 + ], + "disallowed" + ], + [ + [ + 12549, + 12588 + ], + "valid" + ], + [ + [ + 12589, + 12589 + ], + "valid" + ], + [ + [ + 12590, + 12592 + ], + "disallowed" + ], + [ + [ + 12593, + 12593 + ], + "mapped", + [ + 4352 + ] + ], + [ + [ + 12594, + 12594 + ], + "mapped", + [ + 4353 + ] + ], + [ + [ + 12595, + 12595 + ], + "mapped", + [ + 4522 + ] + ], + [ + [ + 12596, + 12596 + ], + "mapped", + [ + 4354 + ] + ], + [ + [ + 12597, + 12597 + ], + "mapped", + [ + 4524 + ] + ], + [ + [ + 12598, + 12598 + ], + "mapped", + [ + 4525 + ] + ], + [ + [ + 12599, + 12599 + ], + "mapped", + [ + 4355 + ] + ], + [ + [ + 12600, + 12600 + ], + "mapped", + [ + 4356 + ] + ], + [ + [ + 12601, + 12601 + ], + "mapped", + [ + 4357 + ] + ], + [ + [ + 12602, + 12602 + ], + "mapped", + [ + 4528 + ] + ], + [ + [ + 12603, + 12603 + ], + "mapped", + [ + 4529 + ] + ], + [ + [ + 12604, + 12604 + ], + "mapped", + [ + 4530 + ] + ], + [ + [ + 12605, + 12605 + ], + "mapped", + [ + 4531 + ] + ], + [ + [ + 12606, + 12606 + ], + "mapped", + [ + 4532 + ] + ], + [ + [ + 12607, + 12607 + ], + "mapped", + [ + 4533 + ] + ], + [ + [ + 12608, + 12608 + ], + "mapped", + [ + 4378 + ] + ], + [ + [ + 12609, + 12609 + ], + "mapped", + [ + 4358 + ] + ], + [ + [ + 12610, + 12610 + ], + "mapped", + [ + 4359 + ] + ], + [ + [ + 12611, + 12611 + ], + "mapped", + [ + 4360 + ] + ], + [ + [ + 12612, + 12612 + ], + "mapped", + [ + 4385 + ] + ], + [ + [ + 12613, + 12613 + ], + "mapped", + [ + 4361 + ] + ], + [ + [ + 12614, + 12614 + ], + "mapped", + [ + 4362 + ] + ], + [ + [ + 12615, + 12615 + ], + "mapped", + [ + 4363 + ] + ], + [ + [ + 12616, + 12616 + ], + "mapped", + [ + 4364 + ] + ], + [ + [ + 12617, + 12617 + ], + "mapped", + [ + 4365 + ] + ], + [ + [ + 12618, + 12618 + ], + "mapped", + [ + 4366 + ] + ], + [ + [ + 12619, + 12619 + ], + "mapped", + [ + 4367 + ] + ], + [ + [ + 12620, + 12620 + ], + "mapped", + [ + 4368 + ] + ], + [ + [ + 12621, + 12621 + ], + "mapped", + [ + 4369 + ] + ], + [ + [ + 12622, + 12622 + ], + "mapped", + [ + 4370 + ] + ], + [ + [ + 12623, + 12623 + ], + "mapped", + [ + 4449 + ] + ], + [ + [ + 12624, + 12624 + ], + "mapped", + [ + 4450 + ] + ], + [ + [ + 12625, + 12625 + ], + "mapped", + [ + 4451 + ] + ], + [ + [ + 12626, + 12626 + ], + "mapped", + [ + 4452 + ] + ], + [ + [ + 12627, + 12627 + ], + "mapped", + [ + 4453 + ] + ], + [ + [ + 12628, + 12628 + ], + "mapped", + [ + 4454 + ] + ], + [ + [ + 12629, + 12629 + ], + "mapped", + [ + 4455 + ] + ], + [ + [ + 12630, + 12630 + ], + "mapped", + [ + 4456 + ] + ], + [ + [ + 12631, + 12631 + ], + "mapped", + [ + 4457 + ] + ], + [ + [ + 12632, + 12632 + ], + "mapped", + [ + 4458 + ] + ], + [ + [ + 12633, + 12633 + ], + "mapped", + [ + 4459 + ] + ], + [ + [ + 12634, + 12634 + ], + "mapped", + [ + 4460 + ] + ], + [ + [ + 12635, + 12635 + ], + "mapped", + [ + 4461 + ] + ], + [ + [ + 12636, + 12636 + ], + "mapped", + [ + 4462 + ] + ], + [ + [ + 12637, + 12637 + ], + "mapped", + [ + 4463 + ] + ], + [ + [ + 12638, + 12638 + ], + "mapped", + [ + 4464 + ] + ], + [ + [ + 12639, + 12639 + ], + "mapped", + [ + 4465 + ] + ], + [ + [ + 12640, + 12640 + ], + "mapped", + [ + 4466 + ] + ], + [ + [ + 12641, + 12641 + ], + "mapped", + [ + 4467 + ] + ], + [ + [ + 12642, + 12642 + ], + "mapped", + [ + 4468 + ] + ], + [ + [ + 12643, + 12643 + ], + "mapped", + [ + 4469 + ] + ], + [ + [ + 12644, + 12644 + ], + "disallowed" + ], + [ + [ + 12645, + 12645 + ], + "mapped", + [ + 4372 + ] + ], + [ + [ + 12646, + 12646 + ], + "mapped", + [ + 4373 + ] + ], + [ + [ + 12647, + 12647 + ], + "mapped", + [ + 4551 + ] + ], + [ + [ + 12648, + 12648 + ], + "mapped", + [ + 4552 + ] + ], + [ + [ + 12649, + 12649 + ], + "mapped", + [ + 4556 + ] + ], + [ + [ + 12650, + 12650 + ], + "mapped", + [ + 4558 + ] + ], + [ + [ + 12651, + 12651 + ], + "mapped", + [ + 4563 + ] + ], + [ + [ + 12652, + 12652 + ], + "mapped", + [ + 4567 + ] + ], + [ + [ + 12653, + 12653 + ], + "mapped", + [ + 4569 + ] + ], + [ + [ + 12654, + 12654 + ], + "mapped", + [ + 4380 + ] + ], + [ + [ + 12655, + 12655 + ], + "mapped", + [ + 4573 + ] + ], + [ + [ + 12656, + 12656 + ], + "mapped", + [ + 4575 + ] + ], + [ + [ + 12657, + 12657 + ], + "mapped", + [ + 4381 + ] + ], + [ + [ + 12658, + 12658 + ], + "mapped", + [ + 4382 + ] + ], + [ + [ + 12659, + 12659 + ], + "mapped", + [ + 4384 + ] + ], + [ + [ + 12660, + 12660 + ], + "mapped", + [ + 4386 + ] + ], + [ + [ + 12661, + 12661 + ], + "mapped", + [ + 4387 + ] + ], + [ + [ + 12662, + 12662 + ], + "mapped", + [ + 4391 + ] + ], + [ + [ + 12663, + 12663 + ], + "mapped", + [ + 4393 + ] + ], + [ + [ + 12664, + 12664 + ], + "mapped", + [ + 4395 + ] + ], + [ + [ + 12665, + 12665 + ], + "mapped", + [ + 4396 + ] + ], + [ + [ + 12666, + 12666 + ], + "mapped", + [ + 4397 + ] + ], + [ + [ + 12667, + 12667 + ], + "mapped", + [ + 4398 + ] + ], + [ + [ + 12668, + 12668 + ], + "mapped", + [ + 4399 + ] + ], + [ + [ + 12669, + 12669 + ], + "mapped", + [ + 4402 + ] + ], + [ + [ + 12670, + 12670 + ], + "mapped", + [ + 4406 + ] + ], + [ + [ + 12671, + 12671 + ], + "mapped", + [ + 4416 + ] + ], + [ + [ + 12672, + 12672 + ], + "mapped", + [ + 4423 + ] + ], + [ + [ + 12673, + 12673 + ], + "mapped", + [ + 4428 + ] + ], + [ + [ + 12674, + 12674 + ], + "mapped", + [ + 4593 + ] + ], + [ + [ + 12675, + 12675 + ], + "mapped", + [ + 4594 + ] + ], + [ + [ + 12676, + 12676 + ], + "mapped", + [ + 4439 + ] + ], + [ + [ + 12677, + 12677 + ], + "mapped", + [ + 4440 + ] + ], + [ + [ + 12678, + 12678 + ], + "mapped", + [ + 4441 + ] + ], + [ + [ + 12679, + 12679 + ], + "mapped", + [ + 4484 + ] + ], + [ + [ + 12680, + 12680 + ], + "mapped", + [ + 4485 + ] + ], + [ + [ + 12681, + 12681 + ], + "mapped", + [ + 4488 + ] + ], + [ + [ + 12682, + 12682 + ], + "mapped", + [ + 4497 + ] + ], + [ + [ + 12683, + 12683 + ], + "mapped", + [ + 4498 + ] + ], + [ + [ + 12684, + 12684 + ], + "mapped", + [ + 4500 + ] + ], + [ + [ + 12685, + 12685 + ], + "mapped", + [ + 4510 + ] + ], + [ + [ + 12686, + 12686 + ], + "mapped", + [ + 4513 + ] + ], + [ + [ + 12687, + 12687 + ], + "disallowed" + ], + [ + [ + 12688, + 12689 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 12690, + 12690 + ], + "mapped", + [ + 19968 + ] + ], + [ + [ + 12691, + 12691 + ], + "mapped", + [ + 20108 + ] + ], + [ + [ + 12692, + 12692 + ], + "mapped", + [ + 19977 + ] + ], + [ + [ + 12693, + 12693 + ], + "mapped", + [ + 22235 + ] + ], + [ + [ + 12694, + 12694 + ], + "mapped", + [ + 19978 + ] + ], + [ + [ + 12695, + 12695 + ], + "mapped", + [ + 20013 + ] + ], + [ + [ + 12696, + 12696 + ], + "mapped", + [ + 19979 + ] + ], + [ + [ + 12697, + 12697 + ], + "mapped", + [ + 30002 + ] + ], + [ + [ + 12698, + 12698 + ], + "mapped", + [ + 20057 + ] + ], + [ + [ + 12699, + 12699 + ], + "mapped", + [ + 19993 + ] + ], + [ + [ + 12700, + 12700 + ], + "mapped", + [ + 19969 + ] + ], + [ + [ + 12701, + 12701 + ], + "mapped", + [ + 22825 + ] + ], + [ + [ + 12702, + 12702 + ], + "mapped", + [ + 22320 + ] + ], + [ + [ + 12703, + 12703 + ], + "mapped", + [ + 20154 + ] + ], + [ + [ + 12704, + 12727 + ], + "valid" + ], + [ + [ + 12728, + 12730 + ], + "valid" + ], + [ + [ + 12731, + 12735 + ], + "disallowed" + ], + [ + [ + 12736, + 12751 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 12752, + 12771 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 12772, + 12783 + ], + "disallowed" + ], + [ + [ + 12784, + 12799 + ], + "valid" + ], + [ + [ + 12800, + 12800 + ], + "disallowed_STD3_mapped", + [ + 40, + 4352, + 41 + ] + ], + [ + [ + 12801, + 12801 + ], + "disallowed_STD3_mapped", + [ + 40, + 4354, + 41 + ] + ], + [ + [ + 12802, + 12802 + ], + "disallowed_STD3_mapped", + [ + 40, + 4355, + 41 + ] + ], + [ + [ + 12803, + 12803 + ], + "disallowed_STD3_mapped", + [ + 40, + 4357, + 41 + ] + ], + [ + [ + 12804, + 12804 + ], + "disallowed_STD3_mapped", + [ + 40, + 4358, + 41 + ] + ], + [ + [ + 12805, + 12805 + ], + "disallowed_STD3_mapped", + [ + 40, + 4359, + 41 + ] + ], + [ + [ + 12806, + 12806 + ], + "disallowed_STD3_mapped", + [ + 40, + 4361, + 41 + ] + ], + [ + [ + 12807, + 12807 + ], + "disallowed_STD3_mapped", + [ + 40, + 4363, + 41 + ] + ], + [ + [ + 12808, + 12808 + ], + "disallowed_STD3_mapped", + [ + 40, + 4364, + 41 + ] + ], + [ + [ + 12809, + 12809 + ], + "disallowed_STD3_mapped", + [ + 40, + 4366, + 41 + ] + ], + [ + [ + 12810, + 12810 + ], + "disallowed_STD3_mapped", + [ + 40, + 4367, + 41 + ] + ], + [ + [ + 12811, + 12811 + ], + "disallowed_STD3_mapped", + [ + 40, + 4368, + 41 + ] + ], + [ + [ + 12812, + 12812 + ], + "disallowed_STD3_mapped", + [ + 40, + 4369, + 41 + ] + ], + [ + [ + 12813, + 12813 + ], + "disallowed_STD3_mapped", + [ + 40, + 4370, + 41 + ] + ], + [ + [ + 12814, + 12814 + ], + "disallowed_STD3_mapped", + [ + 40, + 44032, + 41 + ] + ], + [ + [ + 12815, + 12815 + ], + "disallowed_STD3_mapped", + [ + 40, + 45208, + 41 + ] + ], + [ + [ + 12816, + 12816 + ], + "disallowed_STD3_mapped", + [ + 40, + 45796, + 41 + ] + ], + [ + [ + 12817, + 12817 + ], + "disallowed_STD3_mapped", + [ + 40, + 46972, + 41 + ] + ], + [ + [ + 12818, + 12818 + ], + "disallowed_STD3_mapped", + [ + 40, + 47560, + 41 + ] + ], + [ + [ + 12819, + 12819 + ], + "disallowed_STD3_mapped", + [ + 40, + 48148, + 41 + ] + ], + [ + [ + 12820, + 12820 + ], + "disallowed_STD3_mapped", + [ + 40, + 49324, + 41 + ] + ], + [ + [ + 12821, + 12821 + ], + "disallowed_STD3_mapped", + [ + 40, + 50500, + 41 + ] + ], + [ + [ + 12822, + 12822 + ], + "disallowed_STD3_mapped", + [ + 40, + 51088, + 41 + ] + ], + [ + [ + 12823, + 12823 + ], + "disallowed_STD3_mapped", + [ + 40, + 52264, + 41 + ] + ], + [ + [ + 12824, + 12824 + ], + "disallowed_STD3_mapped", + [ + 40, + 52852, + 41 + ] + ], + [ + [ + 12825, + 12825 + ], + "disallowed_STD3_mapped", + [ + 40, + 53440, + 41 + ] + ], + [ + [ + 12826, + 12826 + ], + "disallowed_STD3_mapped", + [ + 40, + 54028, + 41 + ] + ], + [ + [ + 12827, + 12827 + ], + "disallowed_STD3_mapped", + [ + 40, + 54616, + 41 + ] + ], + [ + [ + 12828, + 12828 + ], + "disallowed_STD3_mapped", + [ + 40, + 51452, + 41 + ] + ], + [ + [ + 12829, + 12829 + ], + "disallowed_STD3_mapped", + [ + 40, + 50724, + 51204, + 41 + ] + ], + [ + [ + 12830, + 12830 + ], + "disallowed_STD3_mapped", + [ + 40, + 50724, + 54980, + 41 + ] + ], + [ + [ + 12831, + 12831 + ], + "disallowed" + ], + [ + [ + 12832, + 12832 + ], + "disallowed_STD3_mapped", + [ + 40, + 19968, + 41 + ] + ], + [ + [ + 12833, + 12833 + ], + "disallowed_STD3_mapped", + [ + 40, + 20108, + 41 + ] + ], + [ + [ + 12834, + 12834 + ], + "disallowed_STD3_mapped", + [ + 40, + 19977, + 41 + ] + ], + [ + [ + 12835, + 12835 + ], + "disallowed_STD3_mapped", + [ + 40, + 22235, + 41 + ] + ], + [ + [ + 12836, + 12836 + ], + "disallowed_STD3_mapped", + [ + 40, + 20116, + 41 + ] + ], + [ + [ + 12837, + 12837 + ], + "disallowed_STD3_mapped", + [ + 40, + 20845, + 41 + ] + ], + [ + [ + 12838, + 12838 + ], + "disallowed_STD3_mapped", + [ + 40, + 19971, + 41 + ] + ], + [ + [ + 12839, + 12839 + ], + "disallowed_STD3_mapped", + [ + 40, + 20843, + 41 + ] + ], + [ + [ + 12840, + 12840 + ], + "disallowed_STD3_mapped", + [ + 40, + 20061, + 41 + ] + ], + [ + [ + 12841, + 12841 + ], + "disallowed_STD3_mapped", + [ + 40, + 21313, + 41 + ] + ], + [ + [ + 12842, + 12842 + ], + "disallowed_STD3_mapped", + [ + 40, + 26376, + 41 + ] + ], + [ + [ + 12843, + 12843 + ], + "disallowed_STD3_mapped", + [ + 40, + 28779, + 41 + ] + ], + [ + [ + 12844, + 12844 + ], + "disallowed_STD3_mapped", + [ + 40, + 27700, + 41 + ] + ], + [ + [ + 12845, + 12845 + ], + "disallowed_STD3_mapped", + [ + 40, + 26408, + 41 + ] + ], + [ + [ + 12846, + 12846 + ], + "disallowed_STD3_mapped", + [ + 40, + 37329, + 41 + ] + ], + [ + [ + 12847, + 12847 + ], + "disallowed_STD3_mapped", + [ + 40, + 22303, + 41 + ] + ], + [ + [ + 12848, + 12848 + ], + "disallowed_STD3_mapped", + [ + 40, + 26085, + 41 + ] + ], + [ + [ + 12849, + 12849 + ], + "disallowed_STD3_mapped", + [ + 40, + 26666, + 41 + ] + ], + [ + [ + 12850, + 12850 + ], + "disallowed_STD3_mapped", + [ + 40, + 26377, + 41 + ] + ], + [ + [ + 12851, + 12851 + ], + "disallowed_STD3_mapped", + [ + 40, + 31038, + 41 + ] + ], + [ + [ + 12852, + 12852 + ], + "disallowed_STD3_mapped", + [ + 40, + 21517, + 41 + ] + ], + [ + [ + 12853, + 12853 + ], + "disallowed_STD3_mapped", + [ + 40, + 29305, + 41 + ] + ], + [ + [ + 12854, + 12854 + ], + "disallowed_STD3_mapped", + [ + 40, + 36001, + 41 + ] + ], + [ + [ + 12855, + 12855 + ], + "disallowed_STD3_mapped", + [ + 40, + 31069, + 41 + ] + ], + [ + [ + 12856, + 12856 + ], + "disallowed_STD3_mapped", + [ + 40, + 21172, + 41 + ] + ], + [ + [ + 12857, + 12857 + ], + "disallowed_STD3_mapped", + [ + 40, + 20195, + 41 + ] + ], + [ + [ + 12858, + 12858 + ], + "disallowed_STD3_mapped", + [ + 40, + 21628, + 41 + ] + ], + [ + [ + 12859, + 12859 + ], + "disallowed_STD3_mapped", + [ + 40, + 23398, + 41 + ] + ], + [ + [ + 12860, + 12860 + ], + "disallowed_STD3_mapped", + [ + 40, + 30435, + 41 + ] + ], + [ + [ + 12861, + 12861 + ], + "disallowed_STD3_mapped", + [ + 40, + 20225, + 41 + ] + ], + [ + [ + 12862, + 12862 + ], + "disallowed_STD3_mapped", + [ + 40, + 36039, + 41 + ] + ], + [ + [ + 12863, + 12863 + ], + "disallowed_STD3_mapped", + [ + 40, + 21332, + 41 + ] + ], + [ + [ + 12864, + 12864 + ], + "disallowed_STD3_mapped", + [ + 40, + 31085, + 41 + ] + ], + [ + [ + 12865, + 12865 + ], + "disallowed_STD3_mapped", + [ + 40, + 20241, + 41 + ] + ], + [ + [ + 12866, + 12866 + ], + "disallowed_STD3_mapped", + [ + 40, + 33258, + 41 + ] + ], + [ + [ + 12867, + 12867 + ], + "disallowed_STD3_mapped", + [ + 40, + 33267, + 41 + ] + ], + [ + [ + 12868, + 12868 + ], + "mapped", + [ + 21839 + ] + ], + [ + [ + 12869, + 12869 + ], + "mapped", + [ + 24188 + ] + ], + [ + [ + 12870, + 12870 + ], + "mapped", + [ + 25991 + ] + ], + [ + [ + 12871, + 12871 + ], + "mapped", + [ + 31631 + ] + ], + [ + [ + 12872, + 12879 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 12880, + 12880 + ], + "mapped", + [ + 112, + 116, + 101 + ] + ], + [ + [ + 12881, + 12881 + ], + "mapped", + [ + 50, + 49 + ] + ], + [ + [ + 12882, + 12882 + ], + "mapped", + [ + 50, + 50 + ] + ], + [ + [ + 12883, + 12883 + ], + "mapped", + [ + 50, + 51 + ] + ], + [ + [ + 12884, + 12884 + ], + "mapped", + [ + 50, + 52 + ] + ], + [ + [ + 12885, + 12885 + ], + "mapped", + [ + 50, + 53 + ] + ], + [ + [ + 12886, + 12886 + ], + "mapped", + [ + 50, + 54 + ] + ], + [ + [ + 12887, + 12887 + ], + "mapped", + [ + 50, + 55 + ] + ], + [ + [ + 12888, + 12888 + ], + "mapped", + [ + 50, + 56 + ] + ], + [ + [ + 12889, + 12889 + ], + "mapped", + [ + 50, + 57 + ] + ], + [ + [ + 12890, + 12890 + ], + "mapped", + [ + 51, + 48 + ] + ], + [ + [ + 12891, + 12891 + ], + "mapped", + [ + 51, + 49 + ] + ], + [ + [ + 12892, + 12892 + ], + "mapped", + [ + 51, + 50 + ] + ], + [ + [ + 12893, + 12893 + ], + "mapped", + [ + 51, + 51 + ] + ], + [ + [ + 12894, + 12894 + ], + "mapped", + [ + 51, + 52 + ] + ], + [ + [ + 12895, + 12895 + ], + "mapped", + [ + 51, + 53 + ] + ], + [ + [ + 12896, + 12896 + ], + "mapped", + [ + 4352 + ] + ], + [ + [ + 12897, + 12897 + ], + "mapped", + [ + 4354 + ] + ], + [ + [ + 12898, + 12898 + ], + "mapped", + [ + 4355 + ] + ], + [ + [ + 12899, + 12899 + ], + "mapped", + [ + 4357 + ] + ], + [ + [ + 12900, + 12900 + ], + "mapped", + [ + 4358 + ] + ], + [ + [ + 12901, + 12901 + ], + "mapped", + [ + 4359 + ] + ], + [ + [ + 12902, + 12902 + ], + "mapped", + [ + 4361 + ] + ], + [ + [ + 12903, + 12903 + ], + "mapped", + [ + 4363 + ] + ], + [ + [ + 12904, + 12904 + ], + "mapped", + [ + 4364 + ] + ], + [ + [ + 12905, + 12905 + ], + "mapped", + [ + 4366 + ] + ], + [ + [ + 12906, + 12906 + ], + "mapped", + [ + 4367 + ] + ], + [ + [ + 12907, + 12907 + ], + "mapped", + [ + 4368 + ] + ], + [ + [ + 12908, + 12908 + ], + "mapped", + [ + 4369 + ] + ], + [ + [ + 12909, + 12909 + ], + "mapped", + [ + 4370 + ] + ], + [ + [ + 12910, + 12910 + ], + "mapped", + [ + 44032 + ] + ], + [ + [ + 12911, + 12911 + ], + "mapped", + [ + 45208 + ] + ], + [ + [ + 12912, + 12912 + ], + "mapped", + [ + 45796 + ] + ], + [ + [ + 12913, + 12913 + ], + "mapped", + [ + 46972 + ] + ], + [ + [ + 12914, + 12914 + ], + "mapped", + [ + 47560 + ] + ], + [ + [ + 12915, + 12915 + ], + "mapped", + [ + 48148 + ] + ], + [ + [ + 12916, + 12916 + ], + "mapped", + [ + 49324 + ] + ], + [ + [ + 12917, + 12917 + ], + "mapped", + [ + 50500 + ] + ], + [ + [ + 12918, + 12918 + ], + "mapped", + [ + 51088 + ] + ], + [ + [ + 12919, + 12919 + ], + "mapped", + [ + 52264 + ] + ], + [ + [ + 12920, + 12920 + ], + "mapped", + [ + 52852 + ] + ], + [ + [ + 12921, + 12921 + ], + "mapped", + [ + 53440 + ] + ], + [ + [ + 12922, + 12922 + ], + "mapped", + [ + 54028 + ] + ], + [ + [ + 12923, + 12923 + ], + "mapped", + [ + 54616 + ] + ], + [ + [ + 12924, + 12924 + ], + "mapped", + [ + 52280, + 44256 + ] + ], + [ + [ + 12925, + 12925 + ], + "mapped", + [ + 51452, + 51032 + ] + ], + [ + [ + 12926, + 12926 + ], + "mapped", + [ + 50864 + ] + ], + [ + [ + 12927, + 12927 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 12928, + 12928 + ], + "mapped", + [ + 19968 + ] + ], + [ + [ + 12929, + 12929 + ], + "mapped", + [ + 20108 + ] + ], + [ + [ + 12930, + 12930 + ], + "mapped", + [ + 19977 + ] + ], + [ + [ + 12931, + 12931 + ], + "mapped", + [ + 22235 + ] + ], + [ + [ + 12932, + 12932 + ], + "mapped", + [ + 20116 + ] + ], + [ + [ + 12933, + 12933 + ], + "mapped", + [ + 20845 + ] + ], + [ + [ + 12934, + 12934 + ], + "mapped", + [ + 19971 + ] + ], + [ + [ + 12935, + 12935 + ], + "mapped", + [ + 20843 + ] + ], + [ + [ + 12936, + 12936 + ], + "mapped", + [ + 20061 + ] + ], + [ + [ + 12937, + 12937 + ], + "mapped", + [ + 21313 + ] + ], + [ + [ + 12938, + 12938 + ], + "mapped", + [ + 26376 + ] + ], + [ + [ + 12939, + 12939 + ], + "mapped", + [ + 28779 + ] + ], + [ + [ + 12940, + 12940 + ], + "mapped", + [ + 27700 + ] + ], + [ + [ + 12941, + 12941 + ], + "mapped", + [ + 26408 + ] + ], + [ + [ + 12942, + 12942 + ], + "mapped", + [ + 37329 + ] + ], + [ + [ + 12943, + 12943 + ], + "mapped", + [ + 22303 + ] + ], + [ + [ + 12944, + 12944 + ], + "mapped", + [ + 26085 + ] + ], + [ + [ + 12945, + 12945 + ], + "mapped", + [ + 26666 + ] + ], + [ + [ + 12946, + 12946 + ], + "mapped", + [ + 26377 + ] + ], + [ + [ + 12947, + 12947 + ], + "mapped", + [ + 31038 + ] + ], + [ + [ + 12948, + 12948 + ], + "mapped", + [ + 21517 + ] + ], + [ + [ + 12949, + 12949 + ], + "mapped", + [ + 29305 + ] + ], + [ + [ + 12950, + 12950 + ], + "mapped", + [ + 36001 + ] + ], + [ + [ + 12951, + 12951 + ], + "mapped", + [ + 31069 + ] + ], + [ + [ + 12952, + 12952 + ], + "mapped", + [ + 21172 + ] + ], + [ + [ + 12953, + 12953 + ], + "mapped", + [ + 31192 + ] + ], + [ + [ + 12954, + 12954 + ], + "mapped", + [ + 30007 + ] + ], + [ + [ + 12955, + 12955 + ], + "mapped", + [ + 22899 + ] + ], + [ + [ + 12956, + 12956 + ], + "mapped", + [ + 36969 + ] + ], + [ + [ + 12957, + 12957 + ], + "mapped", + [ + 20778 + ] + ], + [ + [ + 12958, + 12958 + ], + "mapped", + [ + 21360 + ] + ], + [ + [ + 12959, + 12959 + ], + "mapped", + [ + 27880 + ] + ], + [ + [ + 12960, + 12960 + ], + "mapped", + [ + 38917 + ] + ], + [ + [ + 12961, + 12961 + ], + "mapped", + [ + 20241 + ] + ], + [ + [ + 12962, + 12962 + ], + "mapped", + [ + 20889 + ] + ], + [ + [ + 12963, + 12963 + ], + "mapped", + [ + 27491 + ] + ], + [ + [ + 12964, + 12964 + ], + "mapped", + [ + 19978 + ] + ], + [ + [ + 12965, + 12965 + ], + "mapped", + [ + 20013 + ] + ], + [ + [ + 12966, + 12966 + ], + "mapped", + [ + 19979 + ] + ], + [ + [ + 12967, + 12967 + ], + "mapped", + [ + 24038 + ] + ], + [ + [ + 12968, + 12968 + ], + "mapped", + [ + 21491 + ] + ], + [ + [ + 12969, + 12969 + ], + "mapped", + [ + 21307 + ] + ], + [ + [ + 12970, + 12970 + ], + "mapped", + [ + 23447 + ] + ], + [ + [ + 12971, + 12971 + ], + "mapped", + [ + 23398 + ] + ], + [ + [ + 12972, + 12972 + ], + "mapped", + [ + 30435 + ] + ], + [ + [ + 12973, + 12973 + ], + "mapped", + [ + 20225 + ] + ], + [ + [ + 12974, + 12974 + ], + "mapped", + [ + 36039 + ] + ], + [ + [ + 12975, + 12975 + ], + "mapped", + [ + 21332 + ] + ], + [ + [ + 12976, + 12976 + ], + "mapped", + [ + 22812 + ] + ], + [ + [ + 12977, + 12977 + ], + "mapped", + [ + 51, + 54 + ] + ], + [ + [ + 12978, + 12978 + ], + "mapped", + [ + 51, + 55 + ] + ], + [ + [ + 12979, + 12979 + ], + "mapped", + [ + 51, + 56 + ] + ], + [ + [ + 12980, + 12980 + ], + "mapped", + [ + 51, + 57 + ] + ], + [ + [ + 12981, + 12981 + ], + "mapped", + [ + 52, + 48 + ] + ], + [ + [ + 12982, + 12982 + ], + "mapped", + [ + 52, + 49 + ] + ], + [ + [ + 12983, + 12983 + ], + "mapped", + [ + 52, + 50 + ] + ], + [ + [ + 12984, + 12984 + ], + "mapped", + [ + 52, + 51 + ] + ], + [ + [ + 12985, + 12985 + ], + "mapped", + [ + 52, + 52 + ] + ], + [ + [ + 12986, + 12986 + ], + "mapped", + [ + 52, + 53 + ] + ], + [ + [ + 12987, + 12987 + ], + "mapped", + [ + 52, + 54 + ] + ], + [ + [ + 12988, + 12988 + ], + "mapped", + [ + 52, + 55 + ] + ], + [ + [ + 12989, + 12989 + ], + "mapped", + [ + 52, + 56 + ] + ], + [ + [ + 12990, + 12990 + ], + "mapped", + [ + 52, + 57 + ] + ], + [ + [ + 12991, + 12991 + ], + "mapped", + [ + 53, + 48 + ] + ], + [ + [ + 12992, + 12992 + ], + "mapped", + [ + 49, + 26376 + ] + ], + [ + [ + 12993, + 12993 + ], + "mapped", + [ + 50, + 26376 + ] + ], + [ + [ + 12994, + 12994 + ], + "mapped", + [ + 51, + 26376 + ] + ], + [ + [ + 12995, + 12995 + ], + "mapped", + [ + 52, + 26376 + ] + ], + [ + [ + 12996, + 12996 + ], + "mapped", + [ + 53, + 26376 + ] + ], + [ + [ + 12997, + 12997 + ], + "mapped", + [ + 54, + 26376 + ] + ], + [ + [ + 12998, + 12998 + ], + "mapped", + [ + 55, + 26376 + ] + ], + [ + [ + 12999, + 12999 + ], + "mapped", + [ + 56, + 26376 + ] + ], + [ + [ + 13000, + 13000 + ], + "mapped", + [ + 57, + 26376 + ] + ], + [ + [ + 13001, + 13001 + ], + "mapped", + [ + 49, + 48, + 26376 + ] + ], + [ + [ + 13002, + 13002 + ], + "mapped", + [ + 49, + 49, + 26376 + ] + ], + [ + [ + 13003, + 13003 + ], + "mapped", + [ + 49, + 50, + 26376 + ] + ], + [ + [ + 13004, + 13004 + ], + "mapped", + [ + 104, + 103 + ] + ], + [ + [ + 13005, + 13005 + ], + "mapped", + [ + 101, + 114, + 103 + ] + ], + [ + [ + 13006, + 13006 + ], + "mapped", + [ + 101, + 118 + ] + ], + [ + [ + 13007, + 13007 + ], + "mapped", + [ + 108, + 116, + 100 + ] + ], + [ + [ + 13008, + 13008 + ], + "mapped", + [ + 12450 + ] + ], + [ + [ + 13009, + 13009 + ], + "mapped", + [ + 12452 + ] + ], + [ + [ + 13010, + 13010 + ], + "mapped", + [ + 12454 + ] + ], + [ + [ + 13011, + 13011 + ], + "mapped", + [ + 12456 + ] + ], + [ + [ + 13012, + 13012 + ], + "mapped", + [ + 12458 + ] + ], + [ + [ + 13013, + 13013 + ], + "mapped", + [ + 12459 + ] + ], + [ + [ + 13014, + 13014 + ], + "mapped", + [ + 12461 + ] + ], + [ + [ + 13015, + 13015 + ], + "mapped", + [ + 12463 + ] + ], + [ + [ + 13016, + 13016 + ], + "mapped", + [ + 12465 + ] + ], + [ + [ + 13017, + 13017 + ], + "mapped", + [ + 12467 + ] + ], + [ + [ + 13018, + 13018 + ], + "mapped", + [ + 12469 + ] + ], + [ + [ + 13019, + 13019 + ], + "mapped", + [ + 12471 + ] + ], + [ + [ + 13020, + 13020 + ], + "mapped", + [ + 12473 + ] + ], + [ + [ + 13021, + 13021 + ], + "mapped", + [ + 12475 + ] + ], + [ + [ + 13022, + 13022 + ], + "mapped", + [ + 12477 + ] + ], + [ + [ + 13023, + 13023 + ], + "mapped", + [ + 12479 + ] + ], + [ + [ + 13024, + 13024 + ], + "mapped", + [ + 12481 + ] + ], + [ + [ + 13025, + 13025 + ], + "mapped", + [ + 12484 + ] + ], + [ + [ + 13026, + 13026 + ], + "mapped", + [ + 12486 + ] + ], + [ + [ + 13027, + 13027 + ], + "mapped", + [ + 12488 + ] + ], + [ + [ + 13028, + 13028 + ], + "mapped", + [ + 12490 + ] + ], + [ + [ + 13029, + 13029 + ], + "mapped", + [ + 12491 + ] + ], + [ + [ + 13030, + 13030 + ], + "mapped", + [ + 12492 + ] + ], + [ + [ + 13031, + 13031 + ], + "mapped", + [ + 12493 + ] + ], + [ + [ + 13032, + 13032 + ], + "mapped", + [ + 12494 + ] + ], + [ + [ + 13033, + 13033 + ], + "mapped", + [ + 12495 + ] + ], + [ + [ + 13034, + 13034 + ], + "mapped", + [ + 12498 + ] + ], + [ + [ + 13035, + 13035 + ], + "mapped", + [ + 12501 + ] + ], + [ + [ + 13036, + 13036 + ], + "mapped", + [ + 12504 + ] + ], + [ + [ + 13037, + 13037 + ], + "mapped", + [ + 12507 + ] + ], + [ + [ + 13038, + 13038 + ], + "mapped", + [ + 12510 + ] + ], + [ + [ + 13039, + 13039 + ], + "mapped", + [ + 12511 + ] + ], + [ + [ + 13040, + 13040 + ], + "mapped", + [ + 12512 + ] + ], + [ + [ + 13041, + 13041 + ], + "mapped", + [ + 12513 + ] + ], + [ + [ + 13042, + 13042 + ], + "mapped", + [ + 12514 + ] + ], + [ + [ + 13043, + 13043 + ], + "mapped", + [ + 12516 + ] + ], + [ + [ + 13044, + 13044 + ], + "mapped", + [ + 12518 + ] + ], + [ + [ + 13045, + 13045 + ], + "mapped", + [ + 12520 + ] + ], + [ + [ + 13046, + 13046 + ], + "mapped", + [ + 12521 + ] + ], + [ + [ + 13047, + 13047 + ], + "mapped", + [ + 12522 + ] + ], + [ + [ + 13048, + 13048 + ], + "mapped", + [ + 12523 + ] + ], + [ + [ + 13049, + 13049 + ], + "mapped", + [ + 12524 + ] + ], + [ + [ + 13050, + 13050 + ], + "mapped", + [ + 12525 + ] + ], + [ + [ + 13051, + 13051 + ], + "mapped", + [ + 12527 + ] + ], + [ + [ + 13052, + 13052 + ], + "mapped", + [ + 12528 + ] + ], + [ + [ + 13053, + 13053 + ], + "mapped", + [ + 12529 + ] + ], + [ + [ + 13054, + 13054 + ], + "mapped", + [ + 12530 + ] + ], + [ + [ + 13055, + 13055 + ], + "disallowed" + ], + [ + [ + 13056, + 13056 + ], + "mapped", + [ + 12450, + 12497, + 12540, + 12488 + ] + ], + [ + [ + 13057, + 13057 + ], + "mapped", + [ + 12450, + 12523, + 12501, + 12449 + ] + ], + [ + [ + 13058, + 13058 + ], + "mapped", + [ + 12450, + 12531, + 12506, + 12450 + ] + ], + [ + [ + 13059, + 13059 + ], + "mapped", + [ + 12450, + 12540, + 12523 + ] + ], + [ + [ + 13060, + 13060 + ], + "mapped", + [ + 12452, + 12491, + 12531, + 12464 + ] + ], + [ + [ + 13061, + 13061 + ], + "mapped", + [ + 12452, + 12531, + 12481 + ] + ], + [ + [ + 13062, + 13062 + ], + "mapped", + [ + 12454, + 12457, + 12531 + ] + ], + [ + [ + 13063, + 13063 + ], + "mapped", + [ + 12456, + 12473, + 12463, + 12540, + 12489 + ] + ], + [ + [ + 13064, + 13064 + ], + "mapped", + [ + 12456, + 12540, + 12459, + 12540 + ] + ], + [ + [ + 13065, + 13065 + ], + "mapped", + [ + 12458, + 12531, + 12473 + ] + ], + [ + [ + 13066, + 13066 + ], + "mapped", + [ + 12458, + 12540, + 12512 + ] + ], + [ + [ + 13067, + 13067 + ], + "mapped", + [ + 12459, + 12452, + 12522 + ] + ], + [ + [ + 13068, + 13068 + ], + "mapped", + [ + 12459, + 12521, + 12483, + 12488 + ] + ], + [ + [ + 13069, + 13069 + ], + "mapped", + [ + 12459, + 12525, + 12522, + 12540 + ] + ], + [ + [ + 13070, + 13070 + ], + "mapped", + [ + 12460, + 12525, + 12531 + ] + ], + [ + [ + 13071, + 13071 + ], + "mapped", + [ + 12460, + 12531, + 12510 + ] + ], + [ + [ + 13072, + 13072 + ], + "mapped", + [ + 12462, + 12460 + ] + ], + [ + [ + 13073, + 13073 + ], + "mapped", + [ + 12462, + 12491, + 12540 + ] + ], + [ + [ + 13074, + 13074 + ], + "mapped", + [ + 12461, + 12517, + 12522, + 12540 + ] + ], + [ + [ + 13075, + 13075 + ], + "mapped", + [ + 12462, + 12523, + 12480, + 12540 + ] + ], + [ + [ + 13076, + 13076 + ], + "mapped", + [ + 12461, + 12525 + ] + ], + [ + [ + 13077, + 13077 + ], + "mapped", + [ + 12461, + 12525, + 12464, + 12521, + 12512 + ] + ], + [ + [ + 13078, + 13078 + ], + "mapped", + [ + 12461, + 12525, + 12513, + 12540, + 12488, + 12523 + ] + ], + [ + [ + 13079, + 13079 + ], + "mapped", + [ + 12461, + 12525, + 12527, + 12483, + 12488 + ] + ], + [ + [ + 13080, + 13080 + ], + "mapped", + [ + 12464, + 12521, + 12512 + ] + ], + [ + [ + 13081, + 13081 + ], + "mapped", + [ + 12464, + 12521, + 12512, + 12488, + 12531 + ] + ], + [ + [ + 13082, + 13082 + ], + "mapped", + [ + 12463, + 12523, + 12476, + 12452, + 12525 + ] + ], + [ + [ + 13083, + 13083 + ], + "mapped", + [ + 12463, + 12525, + 12540, + 12493 + ] + ], + [ + [ + 13084, + 13084 + ], + "mapped", + [ + 12465, + 12540, + 12473 + ] + ], + [ + [ + 13085, + 13085 + ], + "mapped", + [ + 12467, + 12523, + 12490 + ] + ], + [ + [ + 13086, + 13086 + ], + "mapped", + [ + 12467, + 12540, + 12509 + ] + ], + [ + [ + 13087, + 13087 + ], + "mapped", + [ + 12469, + 12452, + 12463, + 12523 + ] + ], + [ + [ + 13088, + 13088 + ], + "mapped", + [ + 12469, + 12531, + 12481, + 12540, + 12512 + ] + ], + [ + [ + 13089, + 13089 + ], + "mapped", + [ + 12471, + 12522, + 12531, + 12464 + ] + ], + [ + [ + 13090, + 13090 + ], + "mapped", + [ + 12475, + 12531, + 12481 + ] + ], + [ + [ + 13091, + 13091 + ], + "mapped", + [ + 12475, + 12531, + 12488 + ] + ], + [ + [ + 13092, + 13092 + ], + "mapped", + [ + 12480, + 12540, + 12473 + ] + ], + [ + [ + 13093, + 13093 + ], + "mapped", + [ + 12487, + 12471 + ] + ], + [ + [ + 13094, + 13094 + ], + "mapped", + [ + 12489, + 12523 + ] + ], + [ + [ + 13095, + 13095 + ], + "mapped", + [ + 12488, + 12531 + ] + ], + [ + [ + 13096, + 13096 + ], + "mapped", + [ + 12490, + 12494 + ] + ], + [ + [ + 13097, + 13097 + ], + "mapped", + [ + 12494, + 12483, + 12488 + ] + ], + [ + [ + 13098, + 13098 + ], + "mapped", + [ + 12495, + 12452, + 12484 + ] + ], + [ + [ + 13099, + 13099 + ], + "mapped", + [ + 12497, + 12540, + 12475, + 12531, + 12488 + ] + ], + [ + [ + 13100, + 13100 + ], + "mapped", + [ + 12497, + 12540, + 12484 + ] + ], + [ + [ + 13101, + 13101 + ], + "mapped", + [ + 12496, + 12540, + 12524, + 12523 + ] + ], + [ + [ + 13102, + 13102 + ], + "mapped", + [ + 12500, + 12450, + 12473, + 12488, + 12523 + ] + ], + [ + [ + 13103, + 13103 + ], + "mapped", + [ + 12500, + 12463, + 12523 + ] + ], + [ + [ + 13104, + 13104 + ], + "mapped", + [ + 12500, + 12467 + ] + ], + [ + [ + 13105, + 13105 + ], + "mapped", + [ + 12499, + 12523 + ] + ], + [ + [ + 13106, + 13106 + ], + "mapped", + [ + 12501, + 12449, + 12521, + 12483, + 12489 + ] + ], + [ + [ + 13107, + 13107 + ], + "mapped", + [ + 12501, + 12451, + 12540, + 12488 + ] + ], + [ + [ + 13108, + 13108 + ], + "mapped", + [ + 12502, + 12483, + 12471, + 12455, + 12523 + ] + ], + [ + [ + 13109, + 13109 + ], + "mapped", + [ + 12501, + 12521, + 12531 + ] + ], + [ + [ + 13110, + 13110 + ], + "mapped", + [ + 12504, + 12463, + 12479, + 12540, + 12523 + ] + ], + [ + [ + 13111, + 13111 + ], + "mapped", + [ + 12506, + 12477 + ] + ], + [ + [ + 13112, + 13112 + ], + "mapped", + [ + 12506, + 12491, + 12498 + ] + ], + [ + [ + 13113, + 13113 + ], + "mapped", + [ + 12504, + 12523, + 12484 + ] + ], + [ + [ + 13114, + 13114 + ], + "mapped", + [ + 12506, + 12531, + 12473 + ] + ], + [ + [ + 13115, + 13115 + ], + "mapped", + [ + 12506, + 12540, + 12472 + ] + ], + [ + [ + 13116, + 13116 + ], + "mapped", + [ + 12505, + 12540, + 12479 + ] + ], + [ + [ + 13117, + 13117 + ], + "mapped", + [ + 12509, + 12452, + 12531, + 12488 + ] + ], + [ + [ + 13118, + 13118 + ], + "mapped", + [ + 12508, + 12523, + 12488 + ] + ], + [ + [ + 13119, + 13119 + ], + "mapped", + [ + 12507, + 12531 + ] + ], + [ + [ + 13120, + 13120 + ], + "mapped", + [ + 12509, + 12531, + 12489 + ] + ], + [ + [ + 13121, + 13121 + ], + "mapped", + [ + 12507, + 12540, + 12523 + ] + ], + [ + [ + 13122, + 13122 + ], + "mapped", + [ + 12507, + 12540, + 12531 + ] + ], + [ + [ + 13123, + 13123 + ], + "mapped", + [ + 12510, + 12452, + 12463, + 12525 + ] + ], + [ + [ + 13124, + 13124 + ], + "mapped", + [ + 12510, + 12452, + 12523 + ] + ], + [ + [ + 13125, + 13125 + ], + "mapped", + [ + 12510, + 12483, + 12495 + ] + ], + [ + [ + 13126, + 13126 + ], + "mapped", + [ + 12510, + 12523, + 12463 + ] + ], + [ + [ + 13127, + 13127 + ], + "mapped", + [ + 12510, + 12531, + 12471, + 12519, + 12531 + ] + ], + [ + [ + 13128, + 13128 + ], + "mapped", + [ + 12511, + 12463, + 12525, + 12531 + ] + ], + [ + [ + 13129, + 13129 + ], + "mapped", + [ + 12511, + 12522 + ] + ], + [ + [ + 13130, + 13130 + ], + "mapped", + [ + 12511, + 12522, + 12496, + 12540, + 12523 + ] + ], + [ + [ + 13131, + 13131 + ], + "mapped", + [ + 12513, + 12460 + ] + ], + [ + [ + 13132, + 13132 + ], + "mapped", + [ + 12513, + 12460, + 12488, + 12531 + ] + ], + [ + [ + 13133, + 13133 + ], + "mapped", + [ + 12513, + 12540, + 12488, + 12523 + ] + ], + [ + [ + 13134, + 13134 + ], + "mapped", + [ + 12516, + 12540, + 12489 + ] + ], + [ + [ + 13135, + 13135 + ], + "mapped", + [ + 12516, + 12540, + 12523 + ] + ], + [ + [ + 13136, + 13136 + ], + "mapped", + [ + 12518, + 12450, + 12531 + ] + ], + [ + [ + 13137, + 13137 + ], + "mapped", + [ + 12522, + 12483, + 12488, + 12523 + ] + ], + [ + [ + 13138, + 13138 + ], + "mapped", + [ + 12522, + 12521 + ] + ], + [ + [ + 13139, + 13139 + ], + "mapped", + [ + 12523, + 12500, + 12540 + ] + ], + [ + [ + 13140, + 13140 + ], + "mapped", + [ + 12523, + 12540, + 12502, + 12523 + ] + ], + [ + [ + 13141, + 13141 + ], + "mapped", + [ + 12524, + 12512 + ] + ], + [ + [ + 13142, + 13142 + ], + "mapped", + [ + 12524, + 12531, + 12488, + 12466, + 12531 + ] + ], + [ + [ + 13143, + 13143 + ], + "mapped", + [ + 12527, + 12483, + 12488 + ] + ], + [ + [ + 13144, + 13144 + ], + "mapped", + [ + 48, + 28857 + ] + ], + [ + [ + 13145, + 13145 + ], + "mapped", + [ + 49, + 28857 + ] + ], + [ + [ + 13146, + 13146 + ], + "mapped", + [ + 50, + 28857 + ] + ], + [ + [ + 13147, + 13147 + ], + "mapped", + [ + 51, + 28857 + ] + ], + [ + [ + 13148, + 13148 + ], + "mapped", + [ + 52, + 28857 + ] + ], + [ + [ + 13149, + 13149 + ], + "mapped", + [ + 53, + 28857 + ] + ], + [ + [ + 13150, + 13150 + ], + "mapped", + [ + 54, + 28857 + ] + ], + [ + [ + 13151, + 13151 + ], + "mapped", + [ + 55, + 28857 + ] + ], + [ + [ + 13152, + 13152 + ], + "mapped", + [ + 56, + 28857 + ] + ], + [ + [ + 13153, + 13153 + ], + "mapped", + [ + 57, + 28857 + ] + ], + [ + [ + 13154, + 13154 + ], + "mapped", + [ + 49, + 48, + 28857 + ] + ], + [ + [ + 13155, + 13155 + ], + "mapped", + [ + 49, + 49, + 28857 + ] + ], + [ + [ + 13156, + 13156 + ], + "mapped", + [ + 49, + 50, + 28857 + ] + ], + [ + [ + 13157, + 13157 + ], + "mapped", + [ + 49, + 51, + 28857 + ] + ], + [ + [ + 13158, + 13158 + ], + "mapped", + [ + 49, + 52, + 28857 + ] + ], + [ + [ + 13159, + 13159 + ], + "mapped", + [ + 49, + 53, + 28857 + ] + ], + [ + [ + 13160, + 13160 + ], + "mapped", + [ + 49, + 54, + 28857 + ] + ], + [ + [ + 13161, + 13161 + ], + "mapped", + [ + 49, + 55, + 28857 + ] + ], + [ + [ + 13162, + 13162 + ], + "mapped", + [ + 49, + 56, + 28857 + ] + ], + [ + [ + 13163, + 13163 + ], + "mapped", + [ + 49, + 57, + 28857 + ] + ], + [ + [ + 13164, + 13164 + ], + "mapped", + [ + 50, + 48, + 28857 + ] + ], + [ + [ + 13165, + 13165 + ], + "mapped", + [ + 50, + 49, + 28857 + ] + ], + [ + [ + 13166, + 13166 + ], + "mapped", + [ + 50, + 50, + 28857 + ] + ], + [ + [ + 13167, + 13167 + ], + "mapped", + [ + 50, + 51, + 28857 + ] + ], + [ + [ + 13168, + 13168 + ], + "mapped", + [ + 50, + 52, + 28857 + ] + ], + [ + [ + 13169, + 13169 + ], + "mapped", + [ + 104, + 112, + 97 + ] + ], + [ + [ + 13170, + 13170 + ], + "mapped", + [ + 100, + 97 + ] + ], + [ + [ + 13171, + 13171 + ], + "mapped", + [ + 97, + 117 + ] + ], + [ + [ + 13172, + 13172 + ], + "mapped", + [ + 98, + 97, + 114 + ] + ], + [ + [ + 13173, + 13173 + ], + "mapped", + [ + 111, + 118 + ] + ], + [ + [ + 13174, + 13174 + ], + "mapped", + [ + 112, + 99 + ] + ], + [ + [ + 13175, + 13175 + ], + "mapped", + [ + 100, + 109 + ] + ], + [ + [ + 13176, + 13176 + ], + "mapped", + [ + 100, + 109, + 50 + ] + ], + [ + [ + 13177, + 13177 + ], + "mapped", + [ + 100, + 109, + 51 + ] + ], + [ + [ + 13178, + 13178 + ], + "mapped", + [ + 105, + 117 + ] + ], + [ + [ + 13179, + 13179 + ], + "mapped", + [ + 24179, + 25104 + ] + ], + [ + [ + 13180, + 13180 + ], + "mapped", + [ + 26157, + 21644 + ] + ], + [ + [ + 13181, + 13181 + ], + "mapped", + [ + 22823, + 27491 + ] + ], + [ + [ + 13182, + 13182 + ], + "mapped", + [ + 26126, + 27835 + ] + ], + [ + [ + 13183, + 13183 + ], + "mapped", + [ + 26666, + 24335, + 20250, + 31038 + ] + ], + [ + [ + 13184, + 13184 + ], + "mapped", + [ + 112, + 97 + ] + ], + [ + [ + 13185, + 13185 + ], + "mapped", + [ + 110, + 97 + ] + ], + [ + [ + 13186, + 13186 + ], + "mapped", + [ + 956, + 97 + ] + ], + [ + [ + 13187, + 13187 + ], + "mapped", + [ + 109, + 97 + ] + ], + [ + [ + 13188, + 13188 + ], + "mapped", + [ + 107, + 97 + ] + ], + [ + [ + 13189, + 13189 + ], + "mapped", + [ + 107, + 98 + ] + ], + [ + [ + 13190, + 13190 + ], + "mapped", + [ + 109, + 98 + ] + ], + [ + [ + 13191, + 13191 + ], + "mapped", + [ + 103, + 98 + ] + ], + [ + [ + 13192, + 13192 + ], + "mapped", + [ + 99, + 97, + 108 + ] + ], + [ + [ + 13193, + 13193 + ], + "mapped", + [ + 107, + 99, + 97, + 108 + ] + ], + [ + [ + 13194, + 13194 + ], + "mapped", + [ + 112, + 102 + ] + ], + [ + [ + 13195, + 13195 + ], + "mapped", + [ + 110, + 102 + ] + ], + [ + [ + 13196, + 13196 + ], + "mapped", + [ + 956, + 102 + ] + ], + [ + [ + 13197, + 13197 + ], + "mapped", + [ + 956, + 103 + ] + ], + [ + [ + 13198, + 13198 + ], + "mapped", + [ + 109, + 103 + ] + ], + [ + [ + 13199, + 13199 + ], + "mapped", + [ + 107, + 103 + ] + ], + [ + [ + 13200, + 13200 + ], + "mapped", + [ + 104, + 122 + ] + ], + [ + [ + 13201, + 13201 + ], + "mapped", + [ + 107, + 104, + 122 + ] + ], + [ + [ + 13202, + 13202 + ], + "mapped", + [ + 109, + 104, + 122 + ] + ], + [ + [ + 13203, + 13203 + ], + "mapped", + [ + 103, + 104, + 122 + ] + ], + [ + [ + 13204, + 13204 + ], + "mapped", + [ + 116, + 104, + 122 + ] + ], + [ + [ + 13205, + 13205 + ], + "mapped", + [ + 956, + 108 + ] + ], + [ + [ + 13206, + 13206 + ], + "mapped", + [ + 109, + 108 + ] + ], + [ + [ + 13207, + 13207 + ], + "mapped", + [ + 100, + 108 + ] + ], + [ + [ + 13208, + 13208 + ], + "mapped", + [ + 107, + 108 + ] + ], + [ + [ + 13209, + 13209 + ], + "mapped", + [ + 102, + 109 + ] + ], + [ + [ + 13210, + 13210 + ], + "mapped", + [ + 110, + 109 + ] + ], + [ + [ + 13211, + 13211 + ], + "mapped", + [ + 956, + 109 + ] + ], + [ + [ + 13212, + 13212 + ], + "mapped", + [ + 109, + 109 + ] + ], + [ + [ + 13213, + 13213 + ], + "mapped", + [ + 99, + 109 + ] + ], + [ + [ + 13214, + 13214 + ], + "mapped", + [ + 107, + 109 + ] + ], + [ + [ + 13215, + 13215 + ], + "mapped", + [ + 109, + 109, + 50 + ] + ], + [ + [ + 13216, + 13216 + ], + "mapped", + [ + 99, + 109, + 50 + ] + ], + [ + [ + 13217, + 13217 + ], + "mapped", + [ + 109, + 50 + ] + ], + [ + [ + 13218, + 13218 + ], + "mapped", + [ + 107, + 109, + 50 + ] + ], + [ + [ + 13219, + 13219 + ], + "mapped", + [ + 109, + 109, + 51 + ] + ], + [ + [ + 13220, + 13220 + ], + "mapped", + [ + 99, + 109, + 51 + ] + ], + [ + [ + 13221, + 13221 + ], + "mapped", + [ + 109, + 51 + ] + ], + [ + [ + 13222, + 13222 + ], + "mapped", + [ + 107, + 109, + 51 + ] + ], + [ + [ + 13223, + 13223 + ], + "mapped", + [ + 109, + 8725, + 115 + ] + ], + [ + [ + 13224, + 13224 + ], + "mapped", + [ + 109, + 8725, + 115, + 50 + ] + ], + [ + [ + 13225, + 13225 + ], + "mapped", + [ + 112, + 97 + ] + ], + [ + [ + 13226, + 13226 + ], + "mapped", + [ + 107, + 112, + 97 + ] + ], + [ + [ + 13227, + 13227 + ], + "mapped", + [ + 109, + 112, + 97 + ] + ], + [ + [ + 13228, + 13228 + ], + "mapped", + [ + 103, + 112, + 97 + ] + ], + [ + [ + 13229, + 13229 + ], + "mapped", + [ + 114, + 97, + 100 + ] + ], + [ + [ + 13230, + 13230 + ], + "mapped", + [ + 114, + 97, + 100, + 8725, + 115 + ] + ], + [ + [ + 13231, + 13231 + ], + "mapped", + [ + 114, + 97, + 100, + 8725, + 115, + 50 + ] + ], + [ + [ + 13232, + 13232 + ], + "mapped", + [ + 112, + 115 + ] + ], + [ + [ + 13233, + 13233 + ], + "mapped", + [ + 110, + 115 + ] + ], + [ + [ + 13234, + 13234 + ], + "mapped", + [ + 956, + 115 + ] + ], + [ + [ + 13235, + 13235 + ], + "mapped", + [ + 109, + 115 + ] + ], + [ + [ + 13236, + 13236 + ], + "mapped", + [ + 112, + 118 + ] + ], + [ + [ + 13237, + 13237 + ], + "mapped", + [ + 110, + 118 + ] + ], + [ + [ + 13238, + 13238 + ], + "mapped", + [ + 956, + 118 + ] + ], + [ + [ + 13239, + 13239 + ], + "mapped", + [ + 109, + 118 + ] + ], + [ + [ + 13240, + 13240 + ], + "mapped", + [ + 107, + 118 + ] + ], + [ + [ + 13241, + 13241 + ], + "mapped", + [ + 109, + 118 + ] + ], + [ + [ + 13242, + 13242 + ], + "mapped", + [ + 112, + 119 + ] + ], + [ + [ + 13243, + 13243 + ], + "mapped", + [ + 110, + 119 + ] + ], + [ + [ + 13244, + 13244 + ], + "mapped", + [ + 956, + 119 + ] + ], + [ + [ + 13245, + 13245 + ], + "mapped", + [ + 109, + 119 + ] + ], + [ + [ + 13246, + 13246 + ], + "mapped", + [ + 107, + 119 + ] + ], + [ + [ + 13247, + 13247 + ], + "mapped", + [ + 109, + 119 + ] + ], + [ + [ + 13248, + 13248 + ], + "mapped", + [ + 107, + 969 + ] + ], + [ + [ + 13249, + 13249 + ], + "mapped", + [ + 109, + 969 + ] + ], + [ + [ + 13250, + 13250 + ], + "disallowed" + ], + [ + [ + 13251, + 13251 + ], + "mapped", + [ + 98, + 113 + ] + ], + [ + [ + 13252, + 13252 + ], + "mapped", + [ + 99, + 99 + ] + ], + [ + [ + 13253, + 13253 + ], + "mapped", + [ + 99, + 100 + ] + ], + [ + [ + 13254, + 13254 + ], + "mapped", + [ + 99, + 8725, + 107, + 103 + ] + ], + [ + [ + 13255, + 13255 + ], + "disallowed" + ], + [ + [ + 13256, + 13256 + ], + "mapped", + [ + 100, + 98 + ] + ], + [ + [ + 13257, + 13257 + ], + "mapped", + [ + 103, + 121 + ] + ], + [ + [ + 13258, + 13258 + ], + "mapped", + [ + 104, + 97 + ] + ], + [ + [ + 13259, + 13259 + ], + "mapped", + [ + 104, + 112 + ] + ], + [ + [ + 13260, + 13260 + ], + "mapped", + [ + 105, + 110 + ] + ], + [ + [ + 13261, + 13261 + ], + "mapped", + [ + 107, + 107 + ] + ], + [ + [ + 13262, + 13262 + ], + "mapped", + [ + 107, + 109 + ] + ], + [ + [ + 13263, + 13263 + ], + "mapped", + [ + 107, + 116 + ] + ], + [ + [ + 13264, + 13264 + ], + "mapped", + [ + 108, + 109 + ] + ], + [ + [ + 13265, + 13265 + ], + "mapped", + [ + 108, + 110 + ] + ], + [ + [ + 13266, + 13266 + ], + "mapped", + [ + 108, + 111, + 103 + ] + ], + [ + [ + 13267, + 13267 + ], + "mapped", + [ + 108, + 120 + ] + ], + [ + [ + 13268, + 13268 + ], + "mapped", + [ + 109, + 98 + ] + ], + [ + [ + 13269, + 13269 + ], + "mapped", + [ + 109, + 105, + 108 + ] + ], + [ + [ + 13270, + 13270 + ], + "mapped", + [ + 109, + 111, + 108 + ] + ], + [ + [ + 13271, + 13271 + ], + "mapped", + [ + 112, + 104 + ] + ], + [ + [ + 13272, + 13272 + ], + "disallowed" + ], + [ + [ + 13273, + 13273 + ], + "mapped", + [ + 112, + 112, + 109 + ] + ], + [ + [ + 13274, + 13274 + ], + "mapped", + [ + 112, + 114 + ] + ], + [ + [ + 13275, + 13275 + ], + "mapped", + [ + 115, + 114 + ] + ], + [ + [ + 13276, + 13276 + ], + "mapped", + [ + 115, + 118 + ] + ], + [ + [ + 13277, + 13277 + ], + "mapped", + [ + 119, + 98 + ] + ], + [ + [ + 13278, + 13278 + ], + "mapped", + [ + 118, + 8725, + 109 + ] + ], + [ + [ + 13279, + 13279 + ], + "mapped", + [ + 97, + 8725, + 109 + ] + ], + [ + [ + 13280, + 13280 + ], + "mapped", + [ + 49, + 26085 + ] + ], + [ + [ + 13281, + 13281 + ], + "mapped", + [ + 50, + 26085 + ] + ], + [ + [ + 13282, + 13282 + ], + "mapped", + [ + 51, + 26085 + ] + ], + [ + [ + 13283, + 13283 + ], + "mapped", + [ + 52, + 26085 + ] + ], + [ + [ + 13284, + 13284 + ], + "mapped", + [ + 53, + 26085 + ] + ], + [ + [ + 13285, + 13285 + ], + "mapped", + [ + 54, + 26085 + ] + ], + [ + [ + 13286, + 13286 + ], + "mapped", + [ + 55, + 26085 + ] + ], + [ + [ + 13287, + 13287 + ], + "mapped", + [ + 56, + 26085 + ] + ], + [ + [ + 13288, + 13288 + ], + "mapped", + [ + 57, + 26085 + ] + ], + [ + [ + 13289, + 13289 + ], + "mapped", + [ + 49, + 48, + 26085 + ] + ], + [ + [ + 13290, + 13290 + ], + "mapped", + [ + 49, + 49, + 26085 + ] + ], + [ + [ + 13291, + 13291 + ], + "mapped", + [ + 49, + 50, + 26085 + ] + ], + [ + [ + 13292, + 13292 + ], + "mapped", + [ + 49, + 51, + 26085 + ] + ], + [ + [ + 13293, + 13293 + ], + "mapped", + [ + 49, + 52, + 26085 + ] + ], + [ + [ + 13294, + 13294 + ], + "mapped", + [ + 49, + 53, + 26085 + ] + ], + [ + [ + 13295, + 13295 + ], + "mapped", + [ + 49, + 54, + 26085 + ] + ], + [ + [ + 13296, + 13296 + ], + "mapped", + [ + 49, + 55, + 26085 + ] + ], + [ + [ + 13297, + 13297 + ], + "mapped", + [ + 49, + 56, + 26085 + ] + ], + [ + [ + 13298, + 13298 + ], + "mapped", + [ + 49, + 57, + 26085 + ] + ], + [ + [ + 13299, + 13299 + ], + "mapped", + [ + 50, + 48, + 26085 + ] + ], + [ + [ + 13300, + 13300 + ], + "mapped", + [ + 50, + 49, + 26085 + ] + ], + [ + [ + 13301, + 13301 + ], + "mapped", + [ + 50, + 50, + 26085 + ] + ], + [ + [ + 13302, + 13302 + ], + "mapped", + [ + 50, + 51, + 26085 + ] + ], + [ + [ + 13303, + 13303 + ], + "mapped", + [ + 50, + 52, + 26085 + ] + ], + [ + [ + 13304, + 13304 + ], + "mapped", + [ + 50, + 53, + 26085 + ] + ], + [ + [ + 13305, + 13305 + ], + "mapped", + [ + 50, + 54, + 26085 + ] + ], + [ + [ + 13306, + 13306 + ], + "mapped", + [ + 50, + 55, + 26085 + ] + ], + [ + [ + 13307, + 13307 + ], + "mapped", + [ + 50, + 56, + 26085 + ] + ], + [ + [ + 13308, + 13308 + ], + "mapped", + [ + 50, + 57, + 26085 + ] + ], + [ + [ + 13309, + 13309 + ], + "mapped", + [ + 51, + 48, + 26085 + ] + ], + [ + [ + 13310, + 13310 + ], + "mapped", + [ + 51, + 49, + 26085 + ] + ], + [ + [ + 13311, + 13311 + ], + "mapped", + [ + 103, + 97, + 108 + ] + ], + [ + [ + 13312, + 19893 + ], + "valid" + ], + [ + [ + 19894, + 19903 + ], + "disallowed" + ], + [ + [ + 19904, + 19967 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 19968, + 40869 + ], + "valid" + ], + [ + [ + 40870, + 40891 + ], + "valid" + ], + [ + [ + 40892, + 40899 + ], + "valid" + ], + [ + [ + 40900, + 40907 + ], + "valid" + ], + [ + [ + 40908, + 40908 + ], + "valid" + ], + [ + [ + 40909, + 40917 + ], + "valid" + ], + [ + [ + 40918, + 40959 + ], + "disallowed" + ], + [ + [ + 40960, + 42124 + ], + "valid" + ], + [ + [ + 42125, + 42127 + ], + "disallowed" + ], + [ + [ + 42128, + 42145 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 42146, + 42147 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 42148, + 42163 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 42164, + 42164 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 42165, + 42176 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 42177, + 42177 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 42178, + 42180 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 42181, + 42181 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 42182, + 42182 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 42183, + 42191 + ], + "disallowed" + ], + [ + [ + 42192, + 42237 + ], + "valid" + ], + [ + [ + 42238, + 42239 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 42240, + 42508 + ], + "valid" + ], + [ + [ + 42509, + 42511 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 42512, + 42539 + ], + "valid" + ], + [ + [ + 42540, + 42559 + ], + "disallowed" + ], + [ + [ + 42560, + 42560 + ], + "mapped", + [ + 42561 + ] + ], + [ + [ + 42561, + 42561 + ], + "valid" + ], + [ + [ + 42562, + 42562 + ], + "mapped", + [ + 42563 + ] + ], + [ + [ + 42563, + 42563 + ], + "valid" + ], + [ + [ + 42564, + 42564 + ], + "mapped", + [ + 42565 + ] + ], + [ + [ + 42565, + 42565 + ], + "valid" + ], + [ + [ + 42566, + 42566 + ], + "mapped", + [ + 42567 + ] + ], + [ + [ + 42567, + 42567 + ], + "valid" + ], + [ + [ + 42568, + 42568 + ], + "mapped", + [ + 42569 + ] + ], + [ + [ + 42569, + 42569 + ], + "valid" + ], + [ + [ + 42570, + 42570 + ], + "mapped", + [ + 42571 + ] + ], + [ + [ + 42571, + 42571 + ], + "valid" + ], + [ + [ + 42572, + 42572 + ], + "mapped", + [ + 42573 + ] + ], + [ + [ + 42573, + 42573 + ], + "valid" + ], + [ + [ + 42574, + 42574 + ], + "mapped", + [ + 42575 + ] + ], + [ + [ + 42575, + 42575 + ], + "valid" + ], + [ + [ + 42576, + 42576 + ], + "mapped", + [ + 42577 + ] + ], + [ + [ + 42577, + 42577 + ], + "valid" + ], + [ + [ + 42578, + 42578 + ], + "mapped", + [ + 42579 + ] + ], + [ + [ + 42579, + 42579 + ], + "valid" + ], + [ + [ + 42580, + 42580 + ], + "mapped", + [ + 42581 + ] + ], + [ + [ + 42581, + 42581 + ], + "valid" + ], + [ + [ + 42582, + 42582 + ], + "mapped", + [ + 42583 + ] + ], + [ + [ + 42583, + 42583 + ], + "valid" + ], + [ + [ + 42584, + 42584 + ], + "mapped", + [ + 42585 + ] + ], + [ + [ + 42585, + 42585 + ], + "valid" + ], + [ + [ + 42586, + 42586 + ], + "mapped", + [ + 42587 + ] + ], + [ + [ + 42587, + 42587 + ], + "valid" + ], + [ + [ + 42588, + 42588 + ], + "mapped", + [ + 42589 + ] + ], + [ + [ + 42589, + 42589 + ], + "valid" + ], + [ + [ + 42590, + 42590 + ], + "mapped", + [ + 42591 + ] + ], + [ + [ + 42591, + 42591 + ], + "valid" + ], + [ + [ + 42592, + 42592 + ], + "mapped", + [ + 42593 + ] + ], + [ + [ + 42593, + 42593 + ], + "valid" + ], + [ + [ + 42594, + 42594 + ], + "mapped", + [ + 42595 + ] + ], + [ + [ + 42595, + 42595 + ], + "valid" + ], + [ + [ + 42596, + 42596 + ], + "mapped", + [ + 42597 + ] + ], + [ + [ + 42597, + 42597 + ], + "valid" + ], + [ + [ + 42598, + 42598 + ], + "mapped", + [ + 42599 + ] + ], + [ + [ + 42599, + 42599 + ], + "valid" + ], + [ + [ + 42600, + 42600 + ], + "mapped", + [ + 42601 + ] + ], + [ + [ + 42601, + 42601 + ], + "valid" + ], + [ + [ + 42602, + 42602 + ], + "mapped", + [ + 42603 + ] + ], + [ + [ + 42603, + 42603 + ], + "valid" + ], + [ + [ + 42604, + 42604 + ], + "mapped", + [ + 42605 + ] + ], + [ + [ + 42605, + 42607 + ], + "valid" + ], + [ + [ + 42608, + 42611 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 42612, + 42619 + ], + "valid" + ], + [ + [ + 42620, + 42621 + ], + "valid" + ], + [ + [ + 42622, + 42622 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 42623, + 42623 + ], + "valid" + ], + [ + [ + 42624, + 42624 + ], + "mapped", + [ + 42625 + ] + ], + [ + [ + 42625, + 42625 + ], + "valid" + ], + [ + [ + 42626, + 42626 + ], + "mapped", + [ + 42627 + ] + ], + [ + [ + 42627, + 42627 + ], + "valid" + ], + [ + [ + 42628, + 42628 + ], + "mapped", + [ + 42629 + ] + ], + [ + [ + 42629, + 42629 + ], + "valid" + ], + [ + [ + 42630, + 42630 + ], + "mapped", + [ + 42631 + ] + ], + [ + [ + 42631, + 42631 + ], + "valid" + ], + [ + [ + 42632, + 42632 + ], + "mapped", + [ + 42633 + ] + ], + [ + [ + 42633, + 42633 + ], + "valid" + ], + [ + [ + 42634, + 42634 + ], + "mapped", + [ + 42635 + ] + ], + [ + [ + 42635, + 42635 + ], + "valid" + ], + [ + [ + 42636, + 42636 + ], + "mapped", + [ + 42637 + ] + ], + [ + [ + 42637, + 42637 + ], + "valid" + ], + [ + [ + 42638, + 42638 + ], + "mapped", + [ + 42639 + ] + ], + [ + [ + 42639, + 42639 + ], + "valid" + ], + [ + [ + 42640, + 42640 + ], + "mapped", + [ + 42641 + ] + ], + [ + [ + 42641, + 42641 + ], + "valid" + ], + [ + [ + 42642, + 42642 + ], + "mapped", + [ + 42643 + ] + ], + [ + [ + 42643, + 42643 + ], + "valid" + ], + [ + [ + 42644, + 42644 + ], + "mapped", + [ + 42645 + ] + ], + [ + [ + 42645, + 42645 + ], + "valid" + ], + [ + [ + 42646, + 42646 + ], + "mapped", + [ + 42647 + ] + ], + [ + [ + 42647, + 42647 + ], + "valid" + ], + [ + [ + 42648, + 42648 + ], + "mapped", + [ + 42649 + ] + ], + [ + [ + 42649, + 42649 + ], + "valid" + ], + [ + [ + 42650, + 42650 + ], + "mapped", + [ + 42651 + ] + ], + [ + [ + 42651, + 42651 + ], + "valid" + ], + [ + [ + 42652, + 42652 + ], + "mapped", + [ + 1098 + ] + ], + [ + [ + 42653, + 42653 + ], + "mapped", + [ + 1100 + ] + ], + [ + [ + 42654, + 42654 + ], + "valid" + ], + [ + [ + 42655, + 42655 + ], + "valid" + ], + [ + [ + 42656, + 42725 + ], + "valid" + ], + [ + [ + 42726, + 42735 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 42736, + 42737 + ], + "valid" + ], + [ + [ + 42738, + 42743 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 42744, + 42751 + ], + "disallowed" + ], + [ + [ + 42752, + 42774 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 42775, + 42778 + ], + "valid" + ], + [ + [ + 42779, + 42783 + ], + "valid" + ], + [ + [ + 42784, + 42785 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 42786, + 42786 + ], + "mapped", + [ + 42787 + ] + ], + [ + [ + 42787, + 42787 + ], + "valid" + ], + [ + [ + 42788, + 42788 + ], + "mapped", + [ + 42789 + ] + ], + [ + [ + 42789, + 42789 + ], + "valid" + ], + [ + [ + 42790, + 42790 + ], + "mapped", + [ + 42791 + ] + ], + [ + [ + 42791, + 42791 + ], + "valid" + ], + [ + [ + 42792, + 42792 + ], + "mapped", + [ + 42793 + ] + ], + [ + [ + 42793, + 42793 + ], + "valid" + ], + [ + [ + 42794, + 42794 + ], + "mapped", + [ + 42795 + ] + ], + [ + [ + 42795, + 42795 + ], + "valid" + ], + [ + [ + 42796, + 42796 + ], + "mapped", + [ + 42797 + ] + ], + [ + [ + 42797, + 42797 + ], + "valid" + ], + [ + [ + 42798, + 42798 + ], + "mapped", + [ + 42799 + ] + ], + [ + [ + 42799, + 42801 + ], + "valid" + ], + [ + [ + 42802, + 42802 + ], + "mapped", + [ + 42803 + ] + ], + [ + [ + 42803, + 42803 + ], + "valid" + ], + [ + [ + 42804, + 42804 + ], + "mapped", + [ + 42805 + ] + ], + [ + [ + 42805, + 42805 + ], + "valid" + ], + [ + [ + 42806, + 42806 + ], + "mapped", + [ + 42807 + ] + ], + [ + [ + 42807, + 42807 + ], + "valid" + ], + [ + [ + 42808, + 42808 + ], + "mapped", + [ + 42809 + ] + ], + [ + [ + 42809, + 42809 + ], + "valid" + ], + [ + [ + 42810, + 42810 + ], + "mapped", + [ + 42811 + ] + ], + [ + [ + 42811, + 42811 + ], + "valid" + ], + [ + [ + 42812, + 42812 + ], + "mapped", + [ + 42813 + ] + ], + [ + [ + 42813, + 42813 + ], + "valid" + ], + [ + [ + 42814, + 42814 + ], + "mapped", + [ + 42815 + ] + ], + [ + [ + 42815, + 42815 + ], + "valid" + ], + [ + [ + 42816, + 42816 + ], + "mapped", + [ + 42817 + ] + ], + [ + [ + 42817, + 42817 + ], + "valid" + ], + [ + [ + 42818, + 42818 + ], + "mapped", + [ + 42819 + ] + ], + [ + [ + 42819, + 42819 + ], + "valid" + ], + [ + [ + 42820, + 42820 + ], + "mapped", + [ + 42821 + ] + ], + [ + [ + 42821, + 42821 + ], + "valid" + ], + [ + [ + 42822, + 42822 + ], + "mapped", + [ + 42823 + ] + ], + [ + [ + 42823, + 42823 + ], + "valid" + ], + [ + [ + 42824, + 42824 + ], + "mapped", + [ + 42825 + ] + ], + [ + [ + 42825, + 42825 + ], + "valid" + ], + [ + [ + 42826, + 42826 + ], + "mapped", + [ + 42827 + ] + ], + [ + [ + 42827, + 42827 + ], + "valid" + ], + [ + [ + 42828, + 42828 + ], + "mapped", + [ + 42829 + ] + ], + [ + [ + 42829, + 42829 + ], + "valid" + ], + [ + [ + 42830, + 42830 + ], + "mapped", + [ + 42831 + ] + ], + [ + [ + 42831, + 42831 + ], + "valid" + ], + [ + [ + 42832, + 42832 + ], + "mapped", + [ + 42833 + ] + ], + [ + [ + 42833, + 42833 + ], + "valid" + ], + [ + [ + 42834, + 42834 + ], + "mapped", + [ + 42835 + ] + ], + [ + [ + 42835, + 42835 + ], + "valid" + ], + [ + [ + 42836, + 42836 + ], + "mapped", + [ + 42837 + ] + ], + [ + [ + 42837, + 42837 + ], + "valid" + ], + [ + [ + 42838, + 42838 + ], + "mapped", + [ + 42839 + ] + ], + [ + [ + 42839, + 42839 + ], + "valid" + ], + [ + [ + 42840, + 42840 + ], + "mapped", + [ + 42841 + ] + ], + [ + [ + 42841, + 42841 + ], + "valid" + ], + [ + [ + 42842, + 42842 + ], + "mapped", + [ + 42843 + ] + ], + [ + [ + 42843, + 42843 + ], + "valid" + ], + [ + [ + 42844, + 42844 + ], + "mapped", + [ + 42845 + ] + ], + [ + [ + 42845, + 42845 + ], + "valid" + ], + [ + [ + 42846, + 42846 + ], + "mapped", + [ + 42847 + ] + ], + [ + [ + 42847, + 42847 + ], + "valid" + ], + [ + [ + 42848, + 42848 + ], + "mapped", + [ + 42849 + ] + ], + [ + [ + 42849, + 42849 + ], + "valid" + ], + [ + [ + 42850, + 42850 + ], + "mapped", + [ + 42851 + ] + ], + [ + [ + 42851, + 42851 + ], + "valid" + ], + [ + [ + 42852, + 42852 + ], + "mapped", + [ + 42853 + ] + ], + [ + [ + 42853, + 42853 + ], + "valid" + ], + [ + [ + 42854, + 42854 + ], + "mapped", + [ + 42855 + ] + ], + [ + [ + 42855, + 42855 + ], + "valid" + ], + [ + [ + 42856, + 42856 + ], + "mapped", + [ + 42857 + ] + ], + [ + [ + 42857, + 42857 + ], + "valid" + ], + [ + [ + 42858, + 42858 + ], + "mapped", + [ + 42859 + ] + ], + [ + [ + 42859, + 42859 + ], + "valid" + ], + [ + [ + 42860, + 42860 + ], + "mapped", + [ + 42861 + ] + ], + [ + [ + 42861, + 42861 + ], + "valid" + ], + [ + [ + 42862, + 42862 + ], + "mapped", + [ + 42863 + ] + ], + [ + [ + 42863, + 42863 + ], + "valid" + ], + [ + [ + 42864, + 42864 + ], + "mapped", + [ + 42863 + ] + ], + [ + [ + 42865, + 42872 + ], + "valid" + ], + [ + [ + 42873, + 42873 + ], + "mapped", + [ + 42874 + ] + ], + [ + [ + 42874, + 42874 + ], + "valid" + ], + [ + [ + 42875, + 42875 + ], + "mapped", + [ + 42876 + ] + ], + [ + [ + 42876, + 42876 + ], + "valid" + ], + [ + [ + 42877, + 42877 + ], + "mapped", + [ + 7545 + ] + ], + [ + [ + 42878, + 42878 + ], + "mapped", + [ + 42879 + ] + ], + [ + [ + 42879, + 42879 + ], + "valid" + ], + [ + [ + 42880, + 42880 + ], + "mapped", + [ + 42881 + ] + ], + [ + [ + 42881, + 42881 + ], + "valid" + ], + [ + [ + 42882, + 42882 + ], + "mapped", + [ + 42883 + ] + ], + [ + [ + 42883, + 42883 + ], + "valid" + ], + [ + [ + 42884, + 42884 + ], + "mapped", + [ + 42885 + ] + ], + [ + [ + 42885, + 42885 + ], + "valid" + ], + [ + [ + 42886, + 42886 + ], + "mapped", + [ + 42887 + ] + ], + [ + [ + 42887, + 42888 + ], + "valid" + ], + [ + [ + 42889, + 42890 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 42891, + 42891 + ], + "mapped", + [ + 42892 + ] + ], + [ + [ + 42892, + 42892 + ], + "valid" + ], + [ + [ + 42893, + 42893 + ], + "mapped", + [ + 613 + ] + ], + [ + [ + 42894, + 42894 + ], + "valid" + ], + [ + [ + 42895, + 42895 + ], + "valid" + ], + [ + [ + 42896, + 42896 + ], + "mapped", + [ + 42897 + ] + ], + [ + [ + 42897, + 42897 + ], + "valid" + ], + [ + [ + 42898, + 42898 + ], + "mapped", + [ + 42899 + ] + ], + [ + [ + 42899, + 42899 + ], + "valid" + ], + [ + [ + 42900, + 42901 + ], + "valid" + ], + [ + [ + 42902, + 42902 + ], + "mapped", + [ + 42903 + ] + ], + [ + [ + 42903, + 42903 + ], + "valid" + ], + [ + [ + 42904, + 42904 + ], + "mapped", + [ + 42905 + ] + ], + [ + [ + 42905, + 42905 + ], + "valid" + ], + [ + [ + 42906, + 42906 + ], + "mapped", + [ + 42907 + ] + ], + [ + [ + 42907, + 42907 + ], + "valid" + ], + [ + [ + 42908, + 42908 + ], + "mapped", + [ + 42909 + ] + ], + [ + [ + 42909, + 42909 + ], + "valid" + ], + [ + [ + 42910, + 42910 + ], + "mapped", + [ + 42911 + ] + ], + [ + [ + 42911, + 42911 + ], + "valid" + ], + [ + [ + 42912, + 42912 + ], + "mapped", + [ + 42913 + ] + ], + [ + [ + 42913, + 42913 + ], + "valid" + ], + [ + [ + 42914, + 42914 + ], + "mapped", + [ + 42915 + ] + ], + [ + [ + 42915, + 42915 + ], + "valid" + ], + [ + [ + 42916, + 42916 + ], + "mapped", + [ + 42917 + ] + ], + [ + [ + 42917, + 42917 + ], + "valid" + ], + [ + [ + 42918, + 42918 + ], + "mapped", + [ + 42919 + ] + ], + [ + [ + 42919, + 42919 + ], + "valid" + ], + [ + [ + 42920, + 42920 + ], + "mapped", + [ + 42921 + ] + ], + [ + [ + 42921, + 42921 + ], + "valid" + ], + [ + [ + 42922, + 42922 + ], + "mapped", + [ + 614 + ] + ], + [ + [ + 42923, + 42923 + ], + "mapped", + [ + 604 + ] + ], + [ + [ + 42924, + 42924 + ], + "mapped", + [ + 609 + ] + ], + [ + [ + 42925, + 42925 + ], + "mapped", + [ + 620 + ] + ], + [ + [ + 42926, + 42927 + ], + "disallowed" + ], + [ + [ + 42928, + 42928 + ], + "mapped", + [ + 670 + ] + ], + [ + [ + 42929, + 42929 + ], + "mapped", + [ + 647 + ] + ], + [ + [ + 42930, + 42930 + ], + "mapped", + [ + 669 + ] + ], + [ + [ + 42931, + 42931 + ], + "mapped", + [ + 43859 + ] + ], + [ + [ + 42932, + 42932 + ], + "mapped", + [ + 42933 + ] + ], + [ + [ + 42933, + 42933 + ], + "valid" + ], + [ + [ + 42934, + 42934 + ], + "mapped", + [ + 42935 + ] + ], + [ + [ + 42935, + 42935 + ], + "valid" + ], + [ + [ + 42936, + 42998 + ], + "disallowed" + ], + [ + [ + 42999, + 42999 + ], + "valid" + ], + [ + [ + 43000, + 43000 + ], + "mapped", + [ + 295 + ] + ], + [ + [ + 43001, + 43001 + ], + "mapped", + [ + 339 + ] + ], + [ + [ + 43002, + 43002 + ], + "valid" + ], + [ + [ + 43003, + 43007 + ], + "valid" + ], + [ + [ + 43008, + 43047 + ], + "valid" + ], + [ + [ + 43048, + 43051 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 43052, + 43055 + ], + "disallowed" + ], + [ + [ + 43056, + 43065 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 43066, + 43071 + ], + "disallowed" + ], + [ + [ + 43072, + 43123 + ], + "valid" + ], + [ + [ + 43124, + 43127 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 43128, + 43135 + ], + "disallowed" + ], + [ + [ + 43136, + 43204 + ], + "valid" + ], + [ + [ + 43205, + 43213 + ], + "disallowed" + ], + [ + [ + 43214, + 43215 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 43216, + 43225 + ], + "valid" + ], + [ + [ + 43226, + 43231 + ], + "disallowed" + ], + [ + [ + 43232, + 43255 + ], + "valid" + ], + [ + [ + 43256, + 43258 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 43259, + 43259 + ], + "valid" + ], + [ + [ + 43260, + 43260 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 43261, + 43261 + ], + "valid" + ], + [ + [ + 43262, + 43263 + ], + "disallowed" + ], + [ + [ + 43264, + 43309 + ], + "valid" + ], + [ + [ + 43310, + 43311 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 43312, + 43347 + ], + "valid" + ], + [ + [ + 43348, + 43358 + ], + "disallowed" + ], + [ + [ + 43359, + 43359 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 43360, + 43388 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 43389, + 43391 + ], + "disallowed" + ], + [ + [ + 43392, + 43456 + ], + "valid" + ], + [ + [ + 43457, + 43469 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 43470, + 43470 + ], + "disallowed" + ], + [ + [ + 43471, + 43481 + ], + "valid" + ], + [ + [ + 43482, + 43485 + ], + "disallowed" + ], + [ + [ + 43486, + 43487 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 43488, + 43518 + ], + "valid" + ], + [ + [ + 43519, + 43519 + ], + "disallowed" + ], + [ + [ + 43520, + 43574 + ], + "valid" + ], + [ + [ + 43575, + 43583 + ], + "disallowed" + ], + [ + [ + 43584, + 43597 + ], + "valid" + ], + [ + [ + 43598, + 43599 + ], + "disallowed" + ], + [ + [ + 43600, + 43609 + ], + "valid" + ], + [ + [ + 43610, + 43611 + ], + "disallowed" + ], + [ + [ + 43612, + 43615 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 43616, + 43638 + ], + "valid" + ], + [ + [ + 43639, + 43641 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 43642, + 43643 + ], + "valid" + ], + [ + [ + 43644, + 43647 + ], + "valid" + ], + [ + [ + 43648, + 43714 + ], + "valid" + ], + [ + [ + 43715, + 43738 + ], + "disallowed" + ], + [ + [ + 43739, + 43741 + ], + "valid" + ], + [ + [ + 43742, + 43743 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 43744, + 43759 + ], + "valid" + ], + [ + [ + 43760, + 43761 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 43762, + 43766 + ], + "valid" + ], + [ + [ + 43767, + 43776 + ], + "disallowed" + ], + [ + [ + 43777, + 43782 + ], + "valid" + ], + [ + [ + 43783, + 43784 + ], + "disallowed" + ], + [ + [ + 43785, + 43790 + ], + "valid" + ], + [ + [ + 43791, + 43792 + ], + "disallowed" + ], + [ + [ + 43793, + 43798 + ], + "valid" + ], + [ + [ + 43799, + 43807 + ], + "disallowed" + ], + [ + [ + 43808, + 43814 + ], + "valid" + ], + [ + [ + 43815, + 43815 + ], + "disallowed" + ], + [ + [ + 43816, + 43822 + ], + "valid" + ], + [ + [ + 43823, + 43823 + ], + "disallowed" + ], + [ + [ + 43824, + 43866 + ], + "valid" + ], + [ + [ + 43867, + 43867 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 43868, + 43868 + ], + "mapped", + [ + 42791 + ] + ], + [ + [ + 43869, + 43869 + ], + "mapped", + [ + 43831 + ] + ], + [ + [ + 43870, + 43870 + ], + "mapped", + [ + 619 + ] + ], + [ + [ + 43871, + 43871 + ], + "mapped", + [ + 43858 + ] + ], + [ + [ + 43872, + 43875 + ], + "valid" + ], + [ + [ + 43876, + 43877 + ], + "valid" + ], + [ + [ + 43878, + 43887 + ], + "disallowed" + ], + [ + [ + 43888, + 43888 + ], + "mapped", + [ + 5024 + ] + ], + [ + [ + 43889, + 43889 + ], + "mapped", + [ + 5025 + ] + ], + [ + [ + 43890, + 43890 + ], + "mapped", + [ + 5026 + ] + ], + [ + [ + 43891, + 43891 + ], + "mapped", + [ + 5027 + ] + ], + [ + [ + 43892, + 43892 + ], + "mapped", + [ + 5028 + ] + ], + [ + [ + 43893, + 43893 + ], + "mapped", + [ + 5029 + ] + ], + [ + [ + 43894, + 43894 + ], + "mapped", + [ + 5030 + ] + ], + [ + [ + 43895, + 43895 + ], + "mapped", + [ + 5031 + ] + ], + [ + [ + 43896, + 43896 + ], + "mapped", + [ + 5032 + ] + ], + [ + [ + 43897, + 43897 + ], + "mapped", + [ + 5033 + ] + ], + [ + [ + 43898, + 43898 + ], + "mapped", + [ + 5034 + ] + ], + [ + [ + 43899, + 43899 + ], + "mapped", + [ + 5035 + ] + ], + [ + [ + 43900, + 43900 + ], + "mapped", + [ + 5036 + ] + ], + [ + [ + 43901, + 43901 + ], + "mapped", + [ + 5037 + ] + ], + [ + [ + 43902, + 43902 + ], + "mapped", + [ + 5038 + ] + ], + [ + [ + 43903, + 43903 + ], + "mapped", + [ + 5039 + ] + ], + [ + [ + 43904, + 43904 + ], + "mapped", + [ + 5040 + ] + ], + [ + [ + 43905, + 43905 + ], + "mapped", + [ + 5041 + ] + ], + [ + [ + 43906, + 43906 + ], + "mapped", + [ + 5042 + ] + ], + [ + [ + 43907, + 43907 + ], + "mapped", + [ + 5043 + ] + ], + [ + [ + 43908, + 43908 + ], + "mapped", + [ + 5044 + ] + ], + [ + [ + 43909, + 43909 + ], + "mapped", + [ + 5045 + ] + ], + [ + [ + 43910, + 43910 + ], + "mapped", + [ + 5046 + ] + ], + [ + [ + 43911, + 43911 + ], + "mapped", + [ + 5047 + ] + ], + [ + [ + 43912, + 43912 + ], + "mapped", + [ + 5048 + ] + ], + [ + [ + 43913, + 43913 + ], + "mapped", + [ + 5049 + ] + ], + [ + [ + 43914, + 43914 + ], + "mapped", + [ + 5050 + ] + ], + [ + [ + 43915, + 43915 + ], + "mapped", + [ + 5051 + ] + ], + [ + [ + 43916, + 43916 + ], + "mapped", + [ + 5052 + ] + ], + [ + [ + 43917, + 43917 + ], + "mapped", + [ + 5053 + ] + ], + [ + [ + 43918, + 43918 + ], + "mapped", + [ + 5054 + ] + ], + [ + [ + 43919, + 43919 + ], + "mapped", + [ + 5055 + ] + ], + [ + [ + 43920, + 43920 + ], + "mapped", + [ + 5056 + ] + ], + [ + [ + 43921, + 43921 + ], + "mapped", + [ + 5057 + ] + ], + [ + [ + 43922, + 43922 + ], + "mapped", + [ + 5058 + ] + ], + [ + [ + 43923, + 43923 + ], + "mapped", + [ + 5059 + ] + ], + [ + [ + 43924, + 43924 + ], + "mapped", + [ + 5060 + ] + ], + [ + [ + 43925, + 43925 + ], + "mapped", + [ + 5061 + ] + ], + [ + [ + 43926, + 43926 + ], + "mapped", + [ + 5062 + ] + ], + [ + [ + 43927, + 43927 + ], + "mapped", + [ + 5063 + ] + ], + [ + [ + 43928, + 43928 + ], + "mapped", + [ + 5064 + ] + ], + [ + [ + 43929, + 43929 + ], + "mapped", + [ + 5065 + ] + ], + [ + [ + 43930, + 43930 + ], + "mapped", + [ + 5066 + ] + ], + [ + [ + 43931, + 43931 + ], + "mapped", + [ + 5067 + ] + ], + [ + [ + 43932, + 43932 + ], + "mapped", + [ + 5068 + ] + ], + [ + [ + 43933, + 43933 + ], + "mapped", + [ + 5069 + ] + ], + [ + [ + 43934, + 43934 + ], + "mapped", + [ + 5070 + ] + ], + [ + [ + 43935, + 43935 + ], + "mapped", + [ + 5071 + ] + ], + [ + [ + 43936, + 43936 + ], + "mapped", + [ + 5072 + ] + ], + [ + [ + 43937, + 43937 + ], + "mapped", + [ + 5073 + ] + ], + [ + [ + 43938, + 43938 + ], + "mapped", + [ + 5074 + ] + ], + [ + [ + 43939, + 43939 + ], + "mapped", + [ + 5075 + ] + ], + [ + [ + 43940, + 43940 + ], + "mapped", + [ + 5076 + ] + ], + [ + [ + 43941, + 43941 + ], + "mapped", + [ + 5077 + ] + ], + [ + [ + 43942, + 43942 + ], + "mapped", + [ + 5078 + ] + ], + [ + [ + 43943, + 43943 + ], + "mapped", + [ + 5079 + ] + ], + [ + [ + 43944, + 43944 + ], + "mapped", + [ + 5080 + ] + ], + [ + [ + 43945, + 43945 + ], + "mapped", + [ + 5081 + ] + ], + [ + [ + 43946, + 43946 + ], + "mapped", + [ + 5082 + ] + ], + [ + [ + 43947, + 43947 + ], + "mapped", + [ + 5083 + ] + ], + [ + [ + 43948, + 43948 + ], + "mapped", + [ + 5084 + ] + ], + [ + [ + 43949, + 43949 + ], + "mapped", + [ + 5085 + ] + ], + [ + [ + 43950, + 43950 + ], + "mapped", + [ + 5086 + ] + ], + [ + [ + 43951, + 43951 + ], + "mapped", + [ + 5087 + ] + ], + [ + [ + 43952, + 43952 + ], + "mapped", + [ + 5088 + ] + ], + [ + [ + 43953, + 43953 + ], + "mapped", + [ + 5089 + ] + ], + [ + [ + 43954, + 43954 + ], + "mapped", + [ + 5090 + ] + ], + [ + [ + 43955, + 43955 + ], + "mapped", + [ + 5091 + ] + ], + [ + [ + 43956, + 43956 + ], + "mapped", + [ + 5092 + ] + ], + [ + [ + 43957, + 43957 + ], + "mapped", + [ + 5093 + ] + ], + [ + [ + 43958, + 43958 + ], + "mapped", + [ + 5094 + ] + ], + [ + [ + 43959, + 43959 + ], + "mapped", + [ + 5095 + ] + ], + [ + [ + 43960, + 43960 + ], + "mapped", + [ + 5096 + ] + ], + [ + [ + 43961, + 43961 + ], + "mapped", + [ + 5097 + ] + ], + [ + [ + 43962, + 43962 + ], + "mapped", + [ + 5098 + ] + ], + [ + [ + 43963, + 43963 + ], + "mapped", + [ + 5099 + ] + ], + [ + [ + 43964, + 43964 + ], + "mapped", + [ + 5100 + ] + ], + [ + [ + 43965, + 43965 + ], + "mapped", + [ + 5101 + ] + ], + [ + [ + 43966, + 43966 + ], + "mapped", + [ + 5102 + ] + ], + [ + [ + 43967, + 43967 + ], + "mapped", + [ + 5103 + ] + ], + [ + [ + 43968, + 44010 + ], + "valid" + ], + [ + [ + 44011, + 44011 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 44012, + 44013 + ], + "valid" + ], + [ + [ + 44014, + 44015 + ], + "disallowed" + ], + [ + [ + 44016, + 44025 + ], + "valid" + ], + [ + [ + 44026, + 44031 + ], + "disallowed" + ], + [ + [ + 44032, + 55203 + ], + "valid" + ], + [ + [ + 55204, + 55215 + ], + "disallowed" + ], + [ + [ + 55216, + 55238 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 55239, + 55242 + ], + "disallowed" + ], + [ + [ + 55243, + 55291 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 55292, + 55295 + ], + "disallowed" + ], + [ + [ + 55296, + 57343 + ], + "disallowed" + ], + [ + [ + 57344, + 63743 + ], + "disallowed" + ], + [ + [ + 63744, + 63744 + ], + "mapped", + [ + 35912 + ] + ], + [ + [ + 63745, + 63745 + ], + "mapped", + [ + 26356 + ] + ], + [ + [ + 63746, + 63746 + ], + "mapped", + [ + 36554 + ] + ], + [ + [ + 63747, + 63747 + ], + "mapped", + [ + 36040 + ] + ], + [ + [ + 63748, + 63748 + ], + "mapped", + [ + 28369 + ] + ], + [ + [ + 63749, + 63749 + ], + "mapped", + [ + 20018 + ] + ], + [ + [ + 63750, + 63750 + ], + "mapped", + [ + 21477 + ] + ], + [ + [ + 63751, + 63752 + ], + "mapped", + [ + 40860 + ] + ], + [ + [ + 63753, + 63753 + ], + "mapped", + [ + 22865 + ] + ], + [ + [ + 63754, + 63754 + ], + "mapped", + [ + 37329 + ] + ], + [ + [ + 63755, + 63755 + ], + "mapped", + [ + 21895 + ] + ], + [ + [ + 63756, + 63756 + ], + "mapped", + [ + 22856 + ] + ], + [ + [ + 63757, + 63757 + ], + "mapped", + [ + 25078 + ] + ], + [ + [ + 63758, + 63758 + ], + "mapped", + [ + 30313 + ] + ], + [ + [ + 63759, + 63759 + ], + "mapped", + [ + 32645 + ] + ], + [ + [ + 63760, + 63760 + ], + "mapped", + [ + 34367 + ] + ], + [ + [ + 63761, + 63761 + ], + "mapped", + [ + 34746 + ] + ], + [ + [ + 63762, + 63762 + ], + "mapped", + [ + 35064 + ] + ], + [ + [ + 63763, + 63763 + ], + "mapped", + [ + 37007 + ] + ], + [ + [ + 63764, + 63764 + ], + "mapped", + [ + 27138 + ] + ], + [ + [ + 63765, + 63765 + ], + "mapped", + [ + 27931 + ] + ], + [ + [ + 63766, + 63766 + ], + "mapped", + [ + 28889 + ] + ], + [ + [ + 63767, + 63767 + ], + "mapped", + [ + 29662 + ] + ], + [ + [ + 63768, + 63768 + ], + "mapped", + [ + 33853 + ] + ], + [ + [ + 63769, + 63769 + ], + "mapped", + [ + 37226 + ] + ], + [ + [ + 63770, + 63770 + ], + "mapped", + [ + 39409 + ] + ], + [ + [ + 63771, + 63771 + ], + "mapped", + [ + 20098 + ] + ], + [ + [ + 63772, + 63772 + ], + "mapped", + [ + 21365 + ] + ], + [ + [ + 63773, + 63773 + ], + "mapped", + [ + 27396 + ] + ], + [ + [ + 63774, + 63774 + ], + "mapped", + [ + 29211 + ] + ], + [ + [ + 63775, + 63775 + ], + "mapped", + [ + 34349 + ] + ], + [ + [ + 63776, + 63776 + ], + "mapped", + [ + 40478 + ] + ], + [ + [ + 63777, + 63777 + ], + "mapped", + [ + 23888 + ] + ], + [ + [ + 63778, + 63778 + ], + "mapped", + [ + 28651 + ] + ], + [ + [ + 63779, + 63779 + ], + "mapped", + [ + 34253 + ] + ], + [ + [ + 63780, + 63780 + ], + "mapped", + [ + 35172 + ] + ], + [ + [ + 63781, + 63781 + ], + "mapped", + [ + 25289 + ] + ], + [ + [ + 63782, + 63782 + ], + "mapped", + [ + 33240 + ] + ], + [ + [ + 63783, + 63783 + ], + "mapped", + [ + 34847 + ] + ], + [ + [ + 63784, + 63784 + ], + "mapped", + [ + 24266 + ] + ], + [ + [ + 63785, + 63785 + ], + "mapped", + [ + 26391 + ] + ], + [ + [ + 63786, + 63786 + ], + "mapped", + [ + 28010 + ] + ], + [ + [ + 63787, + 63787 + ], + "mapped", + [ + 29436 + ] + ], + [ + [ + 63788, + 63788 + ], + "mapped", + [ + 37070 + ] + ], + [ + [ + 63789, + 63789 + ], + "mapped", + [ + 20358 + ] + ], + [ + [ + 63790, + 63790 + ], + "mapped", + [ + 20919 + ] + ], + [ + [ + 63791, + 63791 + ], + "mapped", + [ + 21214 + ] + ], + [ + [ + 63792, + 63792 + ], + "mapped", + [ + 25796 + ] + ], + [ + [ + 63793, + 63793 + ], + "mapped", + [ + 27347 + ] + ], + [ + [ + 63794, + 63794 + ], + "mapped", + [ + 29200 + ] + ], + [ + [ + 63795, + 63795 + ], + "mapped", + [ + 30439 + ] + ], + [ + [ + 63796, + 63796 + ], + "mapped", + [ + 32769 + ] + ], + [ + [ + 63797, + 63797 + ], + "mapped", + [ + 34310 + ] + ], + [ + [ + 63798, + 63798 + ], + "mapped", + [ + 34396 + ] + ], + [ + [ + 63799, + 63799 + ], + "mapped", + [ + 36335 + ] + ], + [ + [ + 63800, + 63800 + ], + "mapped", + [ + 38706 + ] + ], + [ + [ + 63801, + 63801 + ], + "mapped", + [ + 39791 + ] + ], + [ + [ + 63802, + 63802 + ], + "mapped", + [ + 40442 + ] + ], + [ + [ + 63803, + 63803 + ], + "mapped", + [ + 30860 + ] + ], + [ + [ + 63804, + 63804 + ], + "mapped", + [ + 31103 + ] + ], + [ + [ + 63805, + 63805 + ], + "mapped", + [ + 32160 + ] + ], + [ + [ + 63806, + 63806 + ], + "mapped", + [ + 33737 + ] + ], + [ + [ + 63807, + 63807 + ], + "mapped", + [ + 37636 + ] + ], + [ + [ + 63808, + 63808 + ], + "mapped", + [ + 40575 + ] + ], + [ + [ + 63809, + 63809 + ], + "mapped", + [ + 35542 + ] + ], + [ + [ + 63810, + 63810 + ], + "mapped", + [ + 22751 + ] + ], + [ + [ + 63811, + 63811 + ], + "mapped", + [ + 24324 + ] + ], + [ + [ + 63812, + 63812 + ], + "mapped", + [ + 31840 + ] + ], + [ + [ + 63813, + 63813 + ], + "mapped", + [ + 32894 + ] + ], + [ + [ + 63814, + 63814 + ], + "mapped", + [ + 29282 + ] + ], + [ + [ + 63815, + 63815 + ], + "mapped", + [ + 30922 + ] + ], + [ + [ + 63816, + 63816 + ], + "mapped", + [ + 36034 + ] + ], + [ + [ + 63817, + 63817 + ], + "mapped", + [ + 38647 + ] + ], + [ + [ + 63818, + 63818 + ], + "mapped", + [ + 22744 + ] + ], + [ + [ + 63819, + 63819 + ], + "mapped", + [ + 23650 + ] + ], + [ + [ + 63820, + 63820 + ], + "mapped", + [ + 27155 + ] + ], + [ + [ + 63821, + 63821 + ], + "mapped", + [ + 28122 + ] + ], + [ + [ + 63822, + 63822 + ], + "mapped", + [ + 28431 + ] + ], + [ + [ + 63823, + 63823 + ], + "mapped", + [ + 32047 + ] + ], + [ + [ + 63824, + 63824 + ], + "mapped", + [ + 32311 + ] + ], + [ + [ + 63825, + 63825 + ], + "mapped", + [ + 38475 + ] + ], + [ + [ + 63826, + 63826 + ], + "mapped", + [ + 21202 + ] + ], + [ + [ + 63827, + 63827 + ], + "mapped", + [ + 32907 + ] + ], + [ + [ + 63828, + 63828 + ], + "mapped", + [ + 20956 + ] + ], + [ + [ + 63829, + 63829 + ], + "mapped", + [ + 20940 + ] + ], + [ + [ + 63830, + 63830 + ], + "mapped", + [ + 31260 + ] + ], + [ + [ + 63831, + 63831 + ], + "mapped", + [ + 32190 + ] + ], + [ + [ + 63832, + 63832 + ], + "mapped", + [ + 33777 + ] + ], + [ + [ + 63833, + 63833 + ], + "mapped", + [ + 38517 + ] + ], + [ + [ + 63834, + 63834 + ], + "mapped", + [ + 35712 + ] + ], + [ + [ + 63835, + 63835 + ], + "mapped", + [ + 25295 + ] + ], + [ + [ + 63836, + 63836 + ], + "mapped", + [ + 27138 + ] + ], + [ + [ + 63837, + 63837 + ], + "mapped", + [ + 35582 + ] + ], + [ + [ + 63838, + 63838 + ], + "mapped", + [ + 20025 + ] + ], + [ + [ + 63839, + 63839 + ], + "mapped", + [ + 23527 + ] + ], + [ + [ + 63840, + 63840 + ], + "mapped", + [ + 24594 + ] + ], + [ + [ + 63841, + 63841 + ], + "mapped", + [ + 29575 + ] + ], + [ + [ + 63842, + 63842 + ], + "mapped", + [ + 30064 + ] + ], + [ + [ + 63843, + 63843 + ], + "mapped", + [ + 21271 + ] + ], + [ + [ + 63844, + 63844 + ], + "mapped", + [ + 30971 + ] + ], + [ + [ + 63845, + 63845 + ], + "mapped", + [ + 20415 + ] + ], + [ + [ + 63846, + 63846 + ], + "mapped", + [ + 24489 + ] + ], + [ + [ + 63847, + 63847 + ], + "mapped", + [ + 19981 + ] + ], + [ + [ + 63848, + 63848 + ], + "mapped", + [ + 27852 + ] + ], + [ + [ + 63849, + 63849 + ], + "mapped", + [ + 25976 + ] + ], + [ + [ + 63850, + 63850 + ], + "mapped", + [ + 32034 + ] + ], + [ + [ + 63851, + 63851 + ], + "mapped", + [ + 21443 + ] + ], + [ + [ + 63852, + 63852 + ], + "mapped", + [ + 22622 + ] + ], + [ + [ + 63853, + 63853 + ], + "mapped", + [ + 30465 + ] + ], + [ + [ + 63854, + 63854 + ], + "mapped", + [ + 33865 + ] + ], + [ + [ + 63855, + 63855 + ], + "mapped", + [ + 35498 + ] + ], + [ + [ + 63856, + 63856 + ], + "mapped", + [ + 27578 + ] + ], + [ + [ + 63857, + 63857 + ], + "mapped", + [ + 36784 + ] + ], + [ + [ + 63858, + 63858 + ], + "mapped", + [ + 27784 + ] + ], + [ + [ + 63859, + 63859 + ], + "mapped", + [ + 25342 + ] + ], + [ + [ + 63860, + 63860 + ], + "mapped", + [ + 33509 + ] + ], + [ + [ + 63861, + 63861 + ], + "mapped", + [ + 25504 + ] + ], + [ + [ + 63862, + 63862 + ], + "mapped", + [ + 30053 + ] + ], + [ + [ + 63863, + 63863 + ], + "mapped", + [ + 20142 + ] + ], + [ + [ + 63864, + 63864 + ], + "mapped", + [ + 20841 + ] + ], + [ + [ + 63865, + 63865 + ], + "mapped", + [ + 20937 + ] + ], + [ + [ + 63866, + 63866 + ], + "mapped", + [ + 26753 + ] + ], + [ + [ + 63867, + 63867 + ], + "mapped", + [ + 31975 + ] + ], + [ + [ + 63868, + 63868 + ], + "mapped", + [ + 33391 + ] + ], + [ + [ + 63869, + 63869 + ], + "mapped", + [ + 35538 + ] + ], + [ + [ + 63870, + 63870 + ], + "mapped", + [ + 37327 + ] + ], + [ + [ + 63871, + 63871 + ], + "mapped", + [ + 21237 + ] + ], + [ + [ + 63872, + 63872 + ], + "mapped", + [ + 21570 + ] + ], + [ + [ + 63873, + 63873 + ], + "mapped", + [ + 22899 + ] + ], + [ + [ + 63874, + 63874 + ], + "mapped", + [ + 24300 + ] + ], + [ + [ + 63875, + 63875 + ], + "mapped", + [ + 26053 + ] + ], + [ + [ + 63876, + 63876 + ], + "mapped", + [ + 28670 + ] + ], + [ + [ + 63877, + 63877 + ], + "mapped", + [ + 31018 + ] + ], + [ + [ + 63878, + 63878 + ], + "mapped", + [ + 38317 + ] + ], + [ + [ + 63879, + 63879 + ], + "mapped", + [ + 39530 + ] + ], + [ + [ + 63880, + 63880 + ], + "mapped", + [ + 40599 + ] + ], + [ + [ + 63881, + 63881 + ], + "mapped", + [ + 40654 + ] + ], + [ + [ + 63882, + 63882 + ], + "mapped", + [ + 21147 + ] + ], + [ + [ + 63883, + 63883 + ], + "mapped", + [ + 26310 + ] + ], + [ + [ + 63884, + 63884 + ], + "mapped", + [ + 27511 + ] + ], + [ + [ + 63885, + 63885 + ], + "mapped", + [ + 36706 + ] + ], + [ + [ + 63886, + 63886 + ], + "mapped", + [ + 24180 + ] + ], + [ + [ + 63887, + 63887 + ], + "mapped", + [ + 24976 + ] + ], + [ + [ + 63888, + 63888 + ], + "mapped", + [ + 25088 + ] + ], + [ + [ + 63889, + 63889 + ], + "mapped", + [ + 25754 + ] + ], + [ + [ + 63890, + 63890 + ], + "mapped", + [ + 28451 + ] + ], + [ + [ + 63891, + 63891 + ], + "mapped", + [ + 29001 + ] + ], + [ + [ + 63892, + 63892 + ], + "mapped", + [ + 29833 + ] + ], + [ + [ + 63893, + 63893 + ], + "mapped", + [ + 31178 + ] + ], + [ + [ + 63894, + 63894 + ], + "mapped", + [ + 32244 + ] + ], + [ + [ + 63895, + 63895 + ], + "mapped", + [ + 32879 + ] + ], + [ + [ + 63896, + 63896 + ], + "mapped", + [ + 36646 + ] + ], + [ + [ + 63897, + 63897 + ], + "mapped", + [ + 34030 + ] + ], + [ + [ + 63898, + 63898 + ], + "mapped", + [ + 36899 + ] + ], + [ + [ + 63899, + 63899 + ], + "mapped", + [ + 37706 + ] + ], + [ + [ + 63900, + 63900 + ], + "mapped", + [ + 21015 + ] + ], + [ + [ + 63901, + 63901 + ], + "mapped", + [ + 21155 + ] + ], + [ + [ + 63902, + 63902 + ], + "mapped", + [ + 21693 + ] + ], + [ + [ + 63903, + 63903 + ], + "mapped", + [ + 28872 + ] + ], + [ + [ + 63904, + 63904 + ], + "mapped", + [ + 35010 + ] + ], + [ + [ + 63905, + 63905 + ], + "mapped", + [ + 35498 + ] + ], + [ + [ + 63906, + 63906 + ], + "mapped", + [ + 24265 + ] + ], + [ + [ + 63907, + 63907 + ], + "mapped", + [ + 24565 + ] + ], + [ + [ + 63908, + 63908 + ], + "mapped", + [ + 25467 + ] + ], + [ + [ + 63909, + 63909 + ], + "mapped", + [ + 27566 + ] + ], + [ + [ + 63910, + 63910 + ], + "mapped", + [ + 31806 + ] + ], + [ + [ + 63911, + 63911 + ], + "mapped", + [ + 29557 + ] + ], + [ + [ + 63912, + 63912 + ], + "mapped", + [ + 20196 + ] + ], + [ + [ + 63913, + 63913 + ], + "mapped", + [ + 22265 + ] + ], + [ + [ + 63914, + 63914 + ], + "mapped", + [ + 23527 + ] + ], + [ + [ + 63915, + 63915 + ], + "mapped", + [ + 23994 + ] + ], + [ + [ + 63916, + 63916 + ], + "mapped", + [ + 24604 + ] + ], + [ + [ + 63917, + 63917 + ], + "mapped", + [ + 29618 + ] + ], + [ + [ + 63918, + 63918 + ], + "mapped", + [ + 29801 + ] + ], + [ + [ + 63919, + 63919 + ], + "mapped", + [ + 32666 + ] + ], + [ + [ + 63920, + 63920 + ], + "mapped", + [ + 32838 + ] + ], + [ + [ + 63921, + 63921 + ], + "mapped", + [ + 37428 + ] + ], + [ + [ + 63922, + 63922 + ], + "mapped", + [ + 38646 + ] + ], + [ + [ + 63923, + 63923 + ], + "mapped", + [ + 38728 + ] + ], + [ + [ + 63924, + 63924 + ], + "mapped", + [ + 38936 + ] + ], + [ + [ + 63925, + 63925 + ], + "mapped", + [ + 20363 + ] + ], + [ + [ + 63926, + 63926 + ], + "mapped", + [ + 31150 + ] + ], + [ + [ + 63927, + 63927 + ], + "mapped", + [ + 37300 + ] + ], + [ + [ + 63928, + 63928 + ], + "mapped", + [ + 38584 + ] + ], + [ + [ + 63929, + 63929 + ], + "mapped", + [ + 24801 + ] + ], + [ + [ + 63930, + 63930 + ], + "mapped", + [ + 20102 + ] + ], + [ + [ + 63931, + 63931 + ], + "mapped", + [ + 20698 + ] + ], + [ + [ + 63932, + 63932 + ], + "mapped", + [ + 23534 + ] + ], + [ + [ + 63933, + 63933 + ], + "mapped", + [ + 23615 + ] + ], + [ + [ + 63934, + 63934 + ], + "mapped", + [ + 26009 + ] + ], + [ + [ + 63935, + 63935 + ], + "mapped", + [ + 27138 + ] + ], + [ + [ + 63936, + 63936 + ], + "mapped", + [ + 29134 + ] + ], + [ + [ + 63937, + 63937 + ], + "mapped", + [ + 30274 + ] + ], + [ + [ + 63938, + 63938 + ], + "mapped", + [ + 34044 + ] + ], + [ + [ + 63939, + 63939 + ], + "mapped", + [ + 36988 + ] + ], + [ + [ + 63940, + 63940 + ], + "mapped", + [ + 40845 + ] + ], + [ + [ + 63941, + 63941 + ], + "mapped", + [ + 26248 + ] + ], + [ + [ + 63942, + 63942 + ], + "mapped", + [ + 38446 + ] + ], + [ + [ + 63943, + 63943 + ], + "mapped", + [ + 21129 + ] + ], + [ + [ + 63944, + 63944 + ], + "mapped", + [ + 26491 + ] + ], + [ + [ + 63945, + 63945 + ], + "mapped", + [ + 26611 + ] + ], + [ + [ + 63946, + 63946 + ], + "mapped", + [ + 27969 + ] + ], + [ + [ + 63947, + 63947 + ], + "mapped", + [ + 28316 + ] + ], + [ + [ + 63948, + 63948 + ], + "mapped", + [ + 29705 + ] + ], + [ + [ + 63949, + 63949 + ], + "mapped", + [ + 30041 + ] + ], + [ + [ + 63950, + 63950 + ], + "mapped", + [ + 30827 + ] + ], + [ + [ + 63951, + 63951 + ], + "mapped", + [ + 32016 + ] + ], + [ + [ + 63952, + 63952 + ], + "mapped", + [ + 39006 + ] + ], + [ + [ + 63953, + 63953 + ], + "mapped", + [ + 20845 + ] + ], + [ + [ + 63954, + 63954 + ], + "mapped", + [ + 25134 + ] + ], + [ + [ + 63955, + 63955 + ], + "mapped", + [ + 38520 + ] + ], + [ + [ + 63956, + 63956 + ], + "mapped", + [ + 20523 + ] + ], + [ + [ + 63957, + 63957 + ], + "mapped", + [ + 23833 + ] + ], + [ + [ + 63958, + 63958 + ], + "mapped", + [ + 28138 + ] + ], + [ + [ + 63959, + 63959 + ], + "mapped", + [ + 36650 + ] + ], + [ + [ + 63960, + 63960 + ], + "mapped", + [ + 24459 + ] + ], + [ + [ + 63961, + 63961 + ], + "mapped", + [ + 24900 + ] + ], + [ + [ + 63962, + 63962 + ], + "mapped", + [ + 26647 + ] + ], + [ + [ + 63963, + 63963 + ], + "mapped", + [ + 29575 + ] + ], + [ + [ + 63964, + 63964 + ], + "mapped", + [ + 38534 + ] + ], + [ + [ + 63965, + 63965 + ], + "mapped", + [ + 21033 + ] + ], + [ + [ + 63966, + 63966 + ], + "mapped", + [ + 21519 + ] + ], + [ + [ + 63967, + 63967 + ], + "mapped", + [ + 23653 + ] + ], + [ + [ + 63968, + 63968 + ], + "mapped", + [ + 26131 + ] + ], + [ + [ + 63969, + 63969 + ], + "mapped", + [ + 26446 + ] + ], + [ + [ + 63970, + 63970 + ], + "mapped", + [ + 26792 + ] + ], + [ + [ + 63971, + 63971 + ], + "mapped", + [ + 27877 + ] + ], + [ + [ + 63972, + 63972 + ], + "mapped", + [ + 29702 + ] + ], + [ + [ + 63973, + 63973 + ], + "mapped", + [ + 30178 + ] + ], + [ + [ + 63974, + 63974 + ], + "mapped", + [ + 32633 + ] + ], + [ + [ + 63975, + 63975 + ], + "mapped", + [ + 35023 + ] + ], + [ + [ + 63976, + 63976 + ], + "mapped", + [ + 35041 + ] + ], + [ + [ + 63977, + 63977 + ], + "mapped", + [ + 37324 + ] + ], + [ + [ + 63978, + 63978 + ], + "mapped", + [ + 38626 + ] + ], + [ + [ + 63979, + 63979 + ], + "mapped", + [ + 21311 + ] + ], + [ + [ + 63980, + 63980 + ], + "mapped", + [ + 28346 + ] + ], + [ + [ + 63981, + 63981 + ], + "mapped", + [ + 21533 + ] + ], + [ + [ + 63982, + 63982 + ], + "mapped", + [ + 29136 + ] + ], + [ + [ + 63983, + 63983 + ], + "mapped", + [ + 29848 + ] + ], + [ + [ + 63984, + 63984 + ], + "mapped", + [ + 34298 + ] + ], + [ + [ + 63985, + 63985 + ], + "mapped", + [ + 38563 + ] + ], + [ + [ + 63986, + 63986 + ], + "mapped", + [ + 40023 + ] + ], + [ + [ + 63987, + 63987 + ], + "mapped", + [ + 40607 + ] + ], + [ + [ + 63988, + 63988 + ], + "mapped", + [ + 26519 + ] + ], + [ + [ + 63989, + 63989 + ], + "mapped", + [ + 28107 + ] + ], + [ + [ + 63990, + 63990 + ], + "mapped", + [ + 33256 + ] + ], + [ + [ + 63991, + 63991 + ], + "mapped", + [ + 31435 + ] + ], + [ + [ + 63992, + 63992 + ], + "mapped", + [ + 31520 + ] + ], + [ + [ + 63993, + 63993 + ], + "mapped", + [ + 31890 + ] + ], + [ + [ + 63994, + 63994 + ], + "mapped", + [ + 29376 + ] + ], + [ + [ + 63995, + 63995 + ], + "mapped", + [ + 28825 + ] + ], + [ + [ + 63996, + 63996 + ], + "mapped", + [ + 35672 + ] + ], + [ + [ + 63997, + 63997 + ], + "mapped", + [ + 20160 + ] + ], + [ + [ + 63998, + 63998 + ], + "mapped", + [ + 33590 + ] + ], + [ + [ + 63999, + 63999 + ], + "mapped", + [ + 21050 + ] + ], + [ + [ + 64000, + 64000 + ], + "mapped", + [ + 20999 + ] + ], + [ + [ + 64001, + 64001 + ], + "mapped", + [ + 24230 + ] + ], + [ + [ + 64002, + 64002 + ], + "mapped", + [ + 25299 + ] + ], + [ + [ + 64003, + 64003 + ], + "mapped", + [ + 31958 + ] + ], + [ + [ + 64004, + 64004 + ], + "mapped", + [ + 23429 + ] + ], + [ + [ + 64005, + 64005 + ], + "mapped", + [ + 27934 + ] + ], + [ + [ + 64006, + 64006 + ], + "mapped", + [ + 26292 + ] + ], + [ + [ + 64007, + 64007 + ], + "mapped", + [ + 36667 + ] + ], + [ + [ + 64008, + 64008 + ], + "mapped", + [ + 34892 + ] + ], + [ + [ + 64009, + 64009 + ], + "mapped", + [ + 38477 + ] + ], + [ + [ + 64010, + 64010 + ], + "mapped", + [ + 35211 + ] + ], + [ + [ + 64011, + 64011 + ], + "mapped", + [ + 24275 + ] + ], + [ + [ + 64012, + 64012 + ], + "mapped", + [ + 20800 + ] + ], + [ + [ + 64013, + 64013 + ], + "mapped", + [ + 21952 + ] + ], + [ + [ + 64014, + 64015 + ], + "valid" + ], + [ + [ + 64016, + 64016 + ], + "mapped", + [ + 22618 + ] + ], + [ + [ + 64017, + 64017 + ], + "valid" + ], + [ + [ + 64018, + 64018 + ], + "mapped", + [ + 26228 + ] + ], + [ + [ + 64019, + 64020 + ], + "valid" + ], + [ + [ + 64021, + 64021 + ], + "mapped", + [ + 20958 + ] + ], + [ + [ + 64022, + 64022 + ], + "mapped", + [ + 29482 + ] + ], + [ + [ + 64023, + 64023 + ], + "mapped", + [ + 30410 + ] + ], + [ + [ + 64024, + 64024 + ], + "mapped", + [ + 31036 + ] + ], + [ + [ + 64025, + 64025 + ], + "mapped", + [ + 31070 + ] + ], + [ + [ + 64026, + 64026 + ], + "mapped", + [ + 31077 + ] + ], + [ + [ + 64027, + 64027 + ], + "mapped", + [ + 31119 + ] + ], + [ + [ + 64028, + 64028 + ], + "mapped", + [ + 38742 + ] + ], + [ + [ + 64029, + 64029 + ], + "mapped", + [ + 31934 + ] + ], + [ + [ + 64030, + 64030 + ], + "mapped", + [ + 32701 + ] + ], + [ + [ + 64031, + 64031 + ], + "valid" + ], + [ + [ + 64032, + 64032 + ], + "mapped", + [ + 34322 + ] + ], + [ + [ + 64033, + 64033 + ], + "valid" + ], + [ + [ + 64034, + 64034 + ], + "mapped", + [ + 35576 + ] + ], + [ + [ + 64035, + 64036 + ], + "valid" + ], + [ + [ + 64037, + 64037 + ], + "mapped", + [ + 36920 + ] + ], + [ + [ + 64038, + 64038 + ], + "mapped", + [ + 37117 + ] + ], + [ + [ + 64039, + 64041 + ], + "valid" + ], + [ + [ + 64042, + 64042 + ], + "mapped", + [ + 39151 + ] + ], + [ + [ + 64043, + 64043 + ], + "mapped", + [ + 39164 + ] + ], + [ + [ + 64044, + 64044 + ], + "mapped", + [ + 39208 + ] + ], + [ + [ + 64045, + 64045 + ], + "mapped", + [ + 40372 + ] + ], + [ + [ + 64046, + 64046 + ], + "mapped", + [ + 37086 + ] + ], + [ + [ + 64047, + 64047 + ], + "mapped", + [ + 38583 + ] + ], + [ + [ + 64048, + 64048 + ], + "mapped", + [ + 20398 + ] + ], + [ + [ + 64049, + 64049 + ], + "mapped", + [ + 20711 + ] + ], + [ + [ + 64050, + 64050 + ], + "mapped", + [ + 20813 + ] + ], + [ + [ + 64051, + 64051 + ], + "mapped", + [ + 21193 + ] + ], + [ + [ + 64052, + 64052 + ], + "mapped", + [ + 21220 + ] + ], + [ + [ + 64053, + 64053 + ], + "mapped", + [ + 21329 + ] + ], + [ + [ + 64054, + 64054 + ], + "mapped", + [ + 21917 + ] + ], + [ + [ + 64055, + 64055 + ], + "mapped", + [ + 22022 + ] + ], + [ + [ + 64056, + 64056 + ], + "mapped", + [ + 22120 + ] + ], + [ + [ + 64057, + 64057 + ], + "mapped", + [ + 22592 + ] + ], + [ + [ + 64058, + 64058 + ], + "mapped", + [ + 22696 + ] + ], + [ + [ + 64059, + 64059 + ], + "mapped", + [ + 23652 + ] + ], + [ + [ + 64060, + 64060 + ], + "mapped", + [ + 23662 + ] + ], + [ + [ + 64061, + 64061 + ], + "mapped", + [ + 24724 + ] + ], + [ + [ + 64062, + 64062 + ], + "mapped", + [ + 24936 + ] + ], + [ + [ + 64063, + 64063 + ], + "mapped", + [ + 24974 + ] + ], + [ + [ + 64064, + 64064 + ], + "mapped", + [ + 25074 + ] + ], + [ + [ + 64065, + 64065 + ], + "mapped", + [ + 25935 + ] + ], + [ + [ + 64066, + 64066 + ], + "mapped", + [ + 26082 + ] + ], + [ + [ + 64067, + 64067 + ], + "mapped", + [ + 26257 + ] + ], + [ + [ + 64068, + 64068 + ], + "mapped", + [ + 26757 + ] + ], + [ + [ + 64069, + 64069 + ], + "mapped", + [ + 28023 + ] + ], + [ + [ + 64070, + 64070 + ], + "mapped", + [ + 28186 + ] + ], + [ + [ + 64071, + 64071 + ], + "mapped", + [ + 28450 + ] + ], + [ + [ + 64072, + 64072 + ], + "mapped", + [ + 29038 + ] + ], + [ + [ + 64073, + 64073 + ], + "mapped", + [ + 29227 + ] + ], + [ + [ + 64074, + 64074 + ], + "mapped", + [ + 29730 + ] + ], + [ + [ + 64075, + 64075 + ], + "mapped", + [ + 30865 + ] + ], + [ + [ + 64076, + 64076 + ], + "mapped", + [ + 31038 + ] + ], + [ + [ + 64077, + 64077 + ], + "mapped", + [ + 31049 + ] + ], + [ + [ + 64078, + 64078 + ], + "mapped", + [ + 31048 + ] + ], + [ + [ + 64079, + 64079 + ], + "mapped", + [ + 31056 + ] + ], + [ + [ + 64080, + 64080 + ], + "mapped", + [ + 31062 + ] + ], + [ + [ + 64081, + 64081 + ], + "mapped", + [ + 31069 + ] + ], + [ + [ + 64082, + 64082 + ], + "mapped", + [ + 31117 + ] + ], + [ + [ + 64083, + 64083 + ], + "mapped", + [ + 31118 + ] + ], + [ + [ + 64084, + 64084 + ], + "mapped", + [ + 31296 + ] + ], + [ + [ + 64085, + 64085 + ], + "mapped", + [ + 31361 + ] + ], + [ + [ + 64086, + 64086 + ], + "mapped", + [ + 31680 + ] + ], + [ + [ + 64087, + 64087 + ], + "mapped", + [ + 32244 + ] + ], + [ + [ + 64088, + 64088 + ], + "mapped", + [ + 32265 + ] + ], + [ + [ + 64089, + 64089 + ], + "mapped", + [ + 32321 + ] + ], + [ + [ + 64090, + 64090 + ], + "mapped", + [ + 32626 + ] + ], + [ + [ + 64091, + 64091 + ], + "mapped", + [ + 32773 + ] + ], + [ + [ + 64092, + 64092 + ], + "mapped", + [ + 33261 + ] + ], + [ + [ + 64093, + 64094 + ], + "mapped", + [ + 33401 + ] + ], + [ + [ + 64095, + 64095 + ], + "mapped", + [ + 33879 + ] + ], + [ + [ + 64096, + 64096 + ], + "mapped", + [ + 35088 + ] + ], + [ + [ + 64097, + 64097 + ], + "mapped", + [ + 35222 + ] + ], + [ + [ + 64098, + 64098 + ], + "mapped", + [ + 35585 + ] + ], + [ + [ + 64099, + 64099 + ], + "mapped", + [ + 35641 + ] + ], + [ + [ + 64100, + 64100 + ], + "mapped", + [ + 36051 + ] + ], + [ + [ + 64101, + 64101 + ], + "mapped", + [ + 36104 + ] + ], + [ + [ + 64102, + 64102 + ], + "mapped", + [ + 36790 + ] + ], + [ + [ + 64103, + 64103 + ], + "mapped", + [ + 36920 + ] + ], + [ + [ + 64104, + 64104 + ], + "mapped", + [ + 38627 + ] + ], + [ + [ + 64105, + 64105 + ], + "mapped", + [ + 38911 + ] + ], + [ + [ + 64106, + 64106 + ], + "mapped", + [ + 38971 + ] + ], + [ + [ + 64107, + 64107 + ], + "mapped", + [ + 24693 + ] + ], + [ + [ + 64108, + 64108 + ], + "mapped", + [ + 148206 + ] + ], + [ + [ + 64109, + 64109 + ], + "mapped", + [ + 33304 + ] + ], + [ + [ + 64110, + 64111 + ], + "disallowed" + ], + [ + [ + 64112, + 64112 + ], + "mapped", + [ + 20006 + ] + ], + [ + [ + 64113, + 64113 + ], + "mapped", + [ + 20917 + ] + ], + [ + [ + 64114, + 64114 + ], + "mapped", + [ + 20840 + ] + ], + [ + [ + 64115, + 64115 + ], + "mapped", + [ + 20352 + ] + ], + [ + [ + 64116, + 64116 + ], + "mapped", + [ + 20805 + ] + ], + [ + [ + 64117, + 64117 + ], + "mapped", + [ + 20864 + ] + ], + [ + [ + 64118, + 64118 + ], + "mapped", + [ + 21191 + ] + ], + [ + [ + 64119, + 64119 + ], + "mapped", + [ + 21242 + ] + ], + [ + [ + 64120, + 64120 + ], + "mapped", + [ + 21917 + ] + ], + [ + [ + 64121, + 64121 + ], + "mapped", + [ + 21845 + ] + ], + [ + [ + 64122, + 64122 + ], + "mapped", + [ + 21913 + ] + ], + [ + [ + 64123, + 64123 + ], + "mapped", + [ + 21986 + ] + ], + [ + [ + 64124, + 64124 + ], + "mapped", + [ + 22618 + ] + ], + [ + [ + 64125, + 64125 + ], + "mapped", + [ + 22707 + ] + ], + [ + [ + 64126, + 64126 + ], + "mapped", + [ + 22852 + ] + ], + [ + [ + 64127, + 64127 + ], + "mapped", + [ + 22868 + ] + ], + [ + [ + 64128, + 64128 + ], + "mapped", + [ + 23138 + ] + ], + [ + [ + 64129, + 64129 + ], + "mapped", + [ + 23336 + ] + ], + [ + [ + 64130, + 64130 + ], + "mapped", + [ + 24274 + ] + ], + [ + [ + 64131, + 64131 + ], + "mapped", + [ + 24281 + ] + ], + [ + [ + 64132, + 64132 + ], + "mapped", + [ + 24425 + ] + ], + [ + [ + 64133, + 64133 + ], + "mapped", + [ + 24493 + ] + ], + [ + [ + 64134, + 64134 + ], + "mapped", + [ + 24792 + ] + ], + [ + [ + 64135, + 64135 + ], + "mapped", + [ + 24910 + ] + ], + [ + [ + 64136, + 64136 + ], + "mapped", + [ + 24840 + ] + ], + [ + [ + 64137, + 64137 + ], + "mapped", + [ + 24974 + ] + ], + [ + [ + 64138, + 64138 + ], + "mapped", + [ + 24928 + ] + ], + [ + [ + 64139, + 64139 + ], + "mapped", + [ + 25074 + ] + ], + [ + [ + 64140, + 64140 + ], + "mapped", + [ + 25140 + ] + ], + [ + [ + 64141, + 64141 + ], + "mapped", + [ + 25540 + ] + ], + [ + [ + 64142, + 64142 + ], + "mapped", + [ + 25628 + ] + ], + [ + [ + 64143, + 64143 + ], + "mapped", + [ + 25682 + ] + ], + [ + [ + 64144, + 64144 + ], + "mapped", + [ + 25942 + ] + ], + [ + [ + 64145, + 64145 + ], + "mapped", + [ + 26228 + ] + ], + [ + [ + 64146, + 64146 + ], + "mapped", + [ + 26391 + ] + ], + [ + [ + 64147, + 64147 + ], + "mapped", + [ + 26395 + ] + ], + [ + [ + 64148, + 64148 + ], + "mapped", + [ + 26454 + ] + ], + [ + [ + 64149, + 64149 + ], + "mapped", + [ + 27513 + ] + ], + [ + [ + 64150, + 64150 + ], + "mapped", + [ + 27578 + ] + ], + [ + [ + 64151, + 64151 + ], + "mapped", + [ + 27969 + ] + ], + [ + [ + 64152, + 64152 + ], + "mapped", + [ + 28379 + ] + ], + [ + [ + 64153, + 64153 + ], + "mapped", + [ + 28363 + ] + ], + [ + [ + 64154, + 64154 + ], + "mapped", + [ + 28450 + ] + ], + [ + [ + 64155, + 64155 + ], + "mapped", + [ + 28702 + ] + ], + [ + [ + 64156, + 64156 + ], + "mapped", + [ + 29038 + ] + ], + [ + [ + 64157, + 64157 + ], + "mapped", + [ + 30631 + ] + ], + [ + [ + 64158, + 64158 + ], + "mapped", + [ + 29237 + ] + ], + [ + [ + 64159, + 64159 + ], + "mapped", + [ + 29359 + ] + ], + [ + [ + 64160, + 64160 + ], + "mapped", + [ + 29482 + ] + ], + [ + [ + 64161, + 64161 + ], + "mapped", + [ + 29809 + ] + ], + [ + [ + 64162, + 64162 + ], + "mapped", + [ + 29958 + ] + ], + [ + [ + 64163, + 64163 + ], + "mapped", + [ + 30011 + ] + ], + [ + [ + 64164, + 64164 + ], + "mapped", + [ + 30237 + ] + ], + [ + [ + 64165, + 64165 + ], + "mapped", + [ + 30239 + ] + ], + [ + [ + 64166, + 64166 + ], + "mapped", + [ + 30410 + ] + ], + [ + [ + 64167, + 64167 + ], + "mapped", + [ + 30427 + ] + ], + [ + [ + 64168, + 64168 + ], + "mapped", + [ + 30452 + ] + ], + [ + [ + 64169, + 64169 + ], + "mapped", + [ + 30538 + ] + ], + [ + [ + 64170, + 64170 + ], + "mapped", + [ + 30528 + ] + ], + [ + [ + 64171, + 64171 + ], + "mapped", + [ + 30924 + ] + ], + [ + [ + 64172, + 64172 + ], + "mapped", + [ + 31409 + ] + ], + [ + [ + 64173, + 64173 + ], + "mapped", + [ + 31680 + ] + ], + [ + [ + 64174, + 64174 + ], + "mapped", + [ + 31867 + ] + ], + [ + [ + 64175, + 64175 + ], + "mapped", + [ + 32091 + ] + ], + [ + [ + 64176, + 64176 + ], + "mapped", + [ + 32244 + ] + ], + [ + [ + 64177, + 64177 + ], + "mapped", + [ + 32574 + ] + ], + [ + [ + 64178, + 64178 + ], + "mapped", + [ + 32773 + ] + ], + [ + [ + 64179, + 64179 + ], + "mapped", + [ + 33618 + ] + ], + [ + [ + 64180, + 64180 + ], + "mapped", + [ + 33775 + ] + ], + [ + [ + 64181, + 64181 + ], + "mapped", + [ + 34681 + ] + ], + [ + [ + 64182, + 64182 + ], + "mapped", + [ + 35137 + ] + ], + [ + [ + 64183, + 64183 + ], + "mapped", + [ + 35206 + ] + ], + [ + [ + 64184, + 64184 + ], + "mapped", + [ + 35222 + ] + ], + [ + [ + 64185, + 64185 + ], + "mapped", + [ + 35519 + ] + ], + [ + [ + 64186, + 64186 + ], + "mapped", + [ + 35576 + ] + ], + [ + [ + 64187, + 64187 + ], + "mapped", + [ + 35531 + ] + ], + [ + [ + 64188, + 64188 + ], + "mapped", + [ + 35585 + ] + ], + [ + [ + 64189, + 64189 + ], + "mapped", + [ + 35582 + ] + ], + [ + [ + 64190, + 64190 + ], + "mapped", + [ + 35565 + ] + ], + [ + [ + 64191, + 64191 + ], + "mapped", + [ + 35641 + ] + ], + [ + [ + 64192, + 64192 + ], + "mapped", + [ + 35722 + ] + ], + [ + [ + 64193, + 64193 + ], + "mapped", + [ + 36104 + ] + ], + [ + [ + 64194, + 64194 + ], + "mapped", + [ + 36664 + ] + ], + [ + [ + 64195, + 64195 + ], + "mapped", + [ + 36978 + ] + ], + [ + [ + 64196, + 64196 + ], + "mapped", + [ + 37273 + ] + ], + [ + [ + 64197, + 64197 + ], + "mapped", + [ + 37494 + ] + ], + [ + [ + 64198, + 64198 + ], + "mapped", + [ + 38524 + ] + ], + [ + [ + 64199, + 64199 + ], + "mapped", + [ + 38627 + ] + ], + [ + [ + 64200, + 64200 + ], + "mapped", + [ + 38742 + ] + ], + [ + [ + 64201, + 64201 + ], + "mapped", + [ + 38875 + ] + ], + [ + [ + 64202, + 64202 + ], + "mapped", + [ + 38911 + ] + ], + [ + [ + 64203, + 64203 + ], + "mapped", + [ + 38923 + ] + ], + [ + [ + 64204, + 64204 + ], + "mapped", + [ + 38971 + ] + ], + [ + [ + 64205, + 64205 + ], + "mapped", + [ + 39698 + ] + ], + [ + [ + 64206, + 64206 + ], + "mapped", + [ + 40860 + ] + ], + [ + [ + 64207, + 64207 + ], + "mapped", + [ + 141386 + ] + ], + [ + [ + 64208, + 64208 + ], + "mapped", + [ + 141380 + ] + ], + [ + [ + 64209, + 64209 + ], + "mapped", + [ + 144341 + ] + ], + [ + [ + 64210, + 64210 + ], + "mapped", + [ + 15261 + ] + ], + [ + [ + 64211, + 64211 + ], + "mapped", + [ + 16408 + ] + ], + [ + [ + 64212, + 64212 + ], + "mapped", + [ + 16441 + ] + ], + [ + [ + 64213, + 64213 + ], + "mapped", + [ + 152137 + ] + ], + [ + [ + 64214, + 64214 + ], + "mapped", + [ + 154832 + ] + ], + [ + [ + 64215, + 64215 + ], + "mapped", + [ + 163539 + ] + ], + [ + [ + 64216, + 64216 + ], + "mapped", + [ + 40771 + ] + ], + [ + [ + 64217, + 64217 + ], + "mapped", + [ + 40846 + ] + ], + [ + [ + 64218, + 64255 + ], + "disallowed" + ], + [ + [ + 64256, + 64256 + ], + "mapped", + [ + 102, + 102 + ] + ], + [ + [ + 64257, + 64257 + ], + "mapped", + [ + 102, + 105 + ] + ], + [ + [ + 64258, + 64258 + ], + "mapped", + [ + 102, + 108 + ] + ], + [ + [ + 64259, + 64259 + ], + "mapped", + [ + 102, + 102, + 105 + ] + ], + [ + [ + 64260, + 64260 + ], + "mapped", + [ + 102, + 102, + 108 + ] + ], + [ + [ + 64261, + 64262 + ], + "mapped", + [ + 115, + 116 + ] + ], + [ + [ + 64263, + 64274 + ], + "disallowed" + ], + [ + [ + 64275, + 64275 + ], + "mapped", + [ + 1396, + 1398 + ] + ], + [ + [ + 64276, + 64276 + ], + "mapped", + [ + 1396, + 1381 + ] + ], + [ + [ + 64277, + 64277 + ], + "mapped", + [ + 1396, + 1387 + ] + ], + [ + [ + 64278, + 64278 + ], + "mapped", + [ + 1406, + 1398 + ] + ], + [ + [ + 64279, + 64279 + ], + "mapped", + [ + 1396, + 1389 + ] + ], + [ + [ + 64280, + 64284 + ], + "disallowed" + ], + [ + [ + 64285, + 64285 + ], + "mapped", + [ + 1497, + 1460 + ] + ], + [ + [ + 64286, + 64286 + ], + "valid" + ], + [ + [ + 64287, + 64287 + ], + "mapped", + [ + 1522, + 1463 + ] + ], + [ + [ + 64288, + 64288 + ], + "mapped", + [ + 1506 + ] + ], + [ + [ + 64289, + 64289 + ], + "mapped", + [ + 1488 + ] + ], + [ + [ + 64290, + 64290 + ], + "mapped", + [ + 1491 + ] + ], + [ + [ + 64291, + 64291 + ], + "mapped", + [ + 1492 + ] + ], + [ + [ + 64292, + 64292 + ], + "mapped", + [ + 1499 + ] + ], + [ + [ + 64293, + 64293 + ], + "mapped", + [ + 1500 + ] + ], + [ + [ + 64294, + 64294 + ], + "mapped", + [ + 1501 + ] + ], + [ + [ + 64295, + 64295 + ], + "mapped", + [ + 1512 + ] + ], + [ + [ + 64296, + 64296 + ], + "mapped", + [ + 1514 + ] + ], + [ + [ + 64297, + 64297 + ], + "disallowed_STD3_mapped", + [ + 43 + ] + ], + [ + [ + 64298, + 64298 + ], + "mapped", + [ + 1513, + 1473 + ] + ], + [ + [ + 64299, + 64299 + ], + "mapped", + [ + 1513, + 1474 + ] + ], + [ + [ + 64300, + 64300 + ], + "mapped", + [ + 1513, + 1468, + 1473 + ] + ], + [ + [ + 64301, + 64301 + ], + "mapped", + [ + 1513, + 1468, + 1474 + ] + ], + [ + [ + 64302, + 64302 + ], + "mapped", + [ + 1488, + 1463 + ] + ], + [ + [ + 64303, + 64303 + ], + "mapped", + [ + 1488, + 1464 + ] + ], + [ + [ + 64304, + 64304 + ], + "mapped", + [ + 1488, + 1468 + ] + ], + [ + [ + 64305, + 64305 + ], + "mapped", + [ + 1489, + 1468 + ] + ], + [ + [ + 64306, + 64306 + ], + "mapped", + [ + 1490, + 1468 + ] + ], + [ + [ + 64307, + 64307 + ], + "mapped", + [ + 1491, + 1468 + ] + ], + [ + [ + 64308, + 64308 + ], + "mapped", + [ + 1492, + 1468 + ] + ], + [ + [ + 64309, + 64309 + ], + "mapped", + [ + 1493, + 1468 + ] + ], + [ + [ + 64310, + 64310 + ], + "mapped", + [ + 1494, + 1468 + ] + ], + [ + [ + 64311, + 64311 + ], + "disallowed" + ], + [ + [ + 64312, + 64312 + ], + "mapped", + [ + 1496, + 1468 + ] + ], + [ + [ + 64313, + 64313 + ], + "mapped", + [ + 1497, + 1468 + ] + ], + [ + [ + 64314, + 64314 + ], + "mapped", + [ + 1498, + 1468 + ] + ], + [ + [ + 64315, + 64315 + ], + "mapped", + [ + 1499, + 1468 + ] + ], + [ + [ + 64316, + 64316 + ], + "mapped", + [ + 1500, + 1468 + ] + ], + [ + [ + 64317, + 64317 + ], + "disallowed" + ], + [ + [ + 64318, + 64318 + ], + "mapped", + [ + 1502, + 1468 + ] + ], + [ + [ + 64319, + 64319 + ], + "disallowed" + ], + [ + [ + 64320, + 64320 + ], + "mapped", + [ + 1504, + 1468 + ] + ], + [ + [ + 64321, + 64321 + ], + "mapped", + [ + 1505, + 1468 + ] + ], + [ + [ + 64322, + 64322 + ], + "disallowed" + ], + [ + [ + 64323, + 64323 + ], + "mapped", + [ + 1507, + 1468 + ] + ], + [ + [ + 64324, + 64324 + ], + "mapped", + [ + 1508, + 1468 + ] + ], + [ + [ + 64325, + 64325 + ], + "disallowed" + ], + [ + [ + 64326, + 64326 + ], + "mapped", + [ + 1510, + 1468 + ] + ], + [ + [ + 64327, + 64327 + ], + "mapped", + [ + 1511, + 1468 + ] + ], + [ + [ + 64328, + 64328 + ], + "mapped", + [ + 1512, + 1468 + ] + ], + [ + [ + 64329, + 64329 + ], + "mapped", + [ + 1513, + 1468 + ] + ], + [ + [ + 64330, + 64330 + ], + "mapped", + [ + 1514, + 1468 + ] + ], + [ + [ + 64331, + 64331 + ], + "mapped", + [ + 1493, + 1465 + ] + ], + [ + [ + 64332, + 64332 + ], + "mapped", + [ + 1489, + 1471 + ] + ], + [ + [ + 64333, + 64333 + ], + "mapped", + [ + 1499, + 1471 + ] + ], + [ + [ + 64334, + 64334 + ], + "mapped", + [ + 1508, + 1471 + ] + ], + [ + [ + 64335, + 64335 + ], + "mapped", + [ + 1488, + 1500 + ] + ], + [ + [ + 64336, + 64337 + ], + "mapped", + [ + 1649 + ] + ], + [ + [ + 64338, + 64341 + ], + "mapped", + [ + 1659 + ] + ], + [ + [ + 64342, + 64345 + ], + "mapped", + [ + 1662 + ] + ], + [ + [ + 64346, + 64349 + ], + "mapped", + [ + 1664 + ] + ], + [ + [ + 64350, + 64353 + ], + "mapped", + [ + 1658 + ] + ], + [ + [ + 64354, + 64357 + ], + "mapped", + [ + 1663 + ] + ], + [ + [ + 64358, + 64361 + ], + "mapped", + [ + 1657 + ] + ], + [ + [ + 64362, + 64365 + ], + "mapped", + [ + 1700 + ] + ], + [ + [ + 64366, + 64369 + ], + "mapped", + [ + 1702 + ] + ], + [ + [ + 64370, + 64373 + ], + "mapped", + [ + 1668 + ] + ], + [ + [ + 64374, + 64377 + ], + "mapped", + [ + 1667 + ] + ], + [ + [ + 64378, + 64381 + ], + "mapped", + [ + 1670 + ] + ], + [ + [ + 64382, + 64385 + ], + "mapped", + [ + 1671 + ] + ], + [ + [ + 64386, + 64387 + ], + "mapped", + [ + 1677 + ] + ], + [ + [ + 64388, + 64389 + ], + "mapped", + [ + 1676 + ] + ], + [ + [ + 64390, + 64391 + ], + "mapped", + [ + 1678 + ] + ], + [ + [ + 64392, + 64393 + ], + "mapped", + [ + 1672 + ] + ], + [ + [ + 64394, + 64395 + ], + "mapped", + [ + 1688 + ] + ], + [ + [ + 64396, + 64397 + ], + "mapped", + [ + 1681 + ] + ], + [ + [ + 64398, + 64401 + ], + "mapped", + [ + 1705 + ] + ], + [ + [ + 64402, + 64405 + ], + "mapped", + [ + 1711 + ] + ], + [ + [ + 64406, + 64409 + ], + "mapped", + [ + 1715 + ] + ], + [ + [ + 64410, + 64413 + ], + "mapped", + [ + 1713 + ] + ], + [ + [ + 64414, + 64415 + ], + "mapped", + [ + 1722 + ] + ], + [ + [ + 64416, + 64419 + ], + "mapped", + [ + 1723 + ] + ], + [ + [ + 64420, + 64421 + ], + "mapped", + [ + 1728 + ] + ], + [ + [ + 64422, + 64425 + ], + "mapped", + [ + 1729 + ] + ], + [ + [ + 64426, + 64429 + ], + "mapped", + [ + 1726 + ] + ], + [ + [ + 64430, + 64431 + ], + "mapped", + [ + 1746 + ] + ], + [ + [ + 64432, + 64433 + ], + "mapped", + [ + 1747 + ] + ], + [ + [ + 64434, + 64449 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 64450, + 64466 + ], + "disallowed" + ], + [ + [ + 64467, + 64470 + ], + "mapped", + [ + 1709 + ] + ], + [ + [ + 64471, + 64472 + ], + "mapped", + [ + 1735 + ] + ], + [ + [ + 64473, + 64474 + ], + "mapped", + [ + 1734 + ] + ], + [ + [ + 64475, + 64476 + ], + "mapped", + [ + 1736 + ] + ], + [ + [ + 64477, + 64477 + ], + "mapped", + [ + 1735, + 1652 + ] + ], + [ + [ + 64478, + 64479 + ], + "mapped", + [ + 1739 + ] + ], + [ + [ + 64480, + 64481 + ], + "mapped", + [ + 1733 + ] + ], + [ + [ + 64482, + 64483 + ], + "mapped", + [ + 1737 + ] + ], + [ + [ + 64484, + 64487 + ], + "mapped", + [ + 1744 + ] + ], + [ + [ + 64488, + 64489 + ], + "mapped", + [ + 1609 + ] + ], + [ + [ + 64490, + 64491 + ], + "mapped", + [ + 1574, + 1575 + ] + ], + [ + [ + 64492, + 64493 + ], + "mapped", + [ + 1574, + 1749 + ] + ], + [ + [ + 64494, + 64495 + ], + "mapped", + [ + 1574, + 1608 + ] + ], + [ + [ + 64496, + 64497 + ], + "mapped", + [ + 1574, + 1735 + ] + ], + [ + [ + 64498, + 64499 + ], + "mapped", + [ + 1574, + 1734 + ] + ], + [ + [ + 64500, + 64501 + ], + "mapped", + [ + 1574, + 1736 + ] + ], + [ + [ + 64502, + 64504 + ], + "mapped", + [ + 1574, + 1744 + ] + ], + [ + [ + 64505, + 64507 + ], + "mapped", + [ + 1574, + 1609 + ] + ], + [ + [ + 64508, + 64511 + ], + "mapped", + [ + 1740 + ] + ], + [ + [ + 64512, + 64512 + ], + "mapped", + [ + 1574, + 1580 + ] + ], + [ + [ + 64513, + 64513 + ], + "mapped", + [ + 1574, + 1581 + ] + ], + [ + [ + 64514, + 64514 + ], + "mapped", + [ + 1574, + 1605 + ] + ], + [ + [ + 64515, + 64515 + ], + "mapped", + [ + 1574, + 1609 + ] + ], + [ + [ + 64516, + 64516 + ], + "mapped", + [ + 1574, + 1610 + ] + ], + [ + [ + 64517, + 64517 + ], + "mapped", + [ + 1576, + 1580 + ] + ], + [ + [ + 64518, + 64518 + ], + "mapped", + [ + 1576, + 1581 + ] + ], + [ + [ + 64519, + 64519 + ], + "mapped", + [ + 1576, + 1582 + ] + ], + [ + [ + 64520, + 64520 + ], + "mapped", + [ + 1576, + 1605 + ] + ], + [ + [ + 64521, + 64521 + ], + "mapped", + [ + 1576, + 1609 + ] + ], + [ + [ + 64522, + 64522 + ], + "mapped", + [ + 1576, + 1610 + ] + ], + [ + [ + 64523, + 64523 + ], + "mapped", + [ + 1578, + 1580 + ] + ], + [ + [ + 64524, + 64524 + ], + "mapped", + [ + 1578, + 1581 + ] + ], + [ + [ + 64525, + 64525 + ], + "mapped", + [ + 1578, + 1582 + ] + ], + [ + [ + 64526, + 64526 + ], + "mapped", + [ + 1578, + 1605 + ] + ], + [ + [ + 64527, + 64527 + ], + "mapped", + [ + 1578, + 1609 + ] + ], + [ + [ + 64528, + 64528 + ], + "mapped", + [ + 1578, + 1610 + ] + ], + [ + [ + 64529, + 64529 + ], + "mapped", + [ + 1579, + 1580 + ] + ], + [ + [ + 64530, + 64530 + ], + "mapped", + [ + 1579, + 1605 + ] + ], + [ + [ + 64531, + 64531 + ], + "mapped", + [ + 1579, + 1609 + ] + ], + [ + [ + 64532, + 64532 + ], + "mapped", + [ + 1579, + 1610 + ] + ], + [ + [ + 64533, + 64533 + ], + "mapped", + [ + 1580, + 1581 + ] + ], + [ + [ + 64534, + 64534 + ], + "mapped", + [ + 1580, + 1605 + ] + ], + [ + [ + 64535, + 64535 + ], + "mapped", + [ + 1581, + 1580 + ] + ], + [ + [ + 64536, + 64536 + ], + "mapped", + [ + 1581, + 1605 + ] + ], + [ + [ + 64537, + 64537 + ], + "mapped", + [ + 1582, + 1580 + ] + ], + [ + [ + 64538, + 64538 + ], + "mapped", + [ + 1582, + 1581 + ] + ], + [ + [ + 64539, + 64539 + ], + "mapped", + [ + 1582, + 1605 + ] + ], + [ + [ + 64540, + 64540 + ], + "mapped", + [ + 1587, + 1580 + ] + ], + [ + [ + 64541, + 64541 + ], + "mapped", + [ + 1587, + 1581 + ] + ], + [ + [ + 64542, + 64542 + ], + "mapped", + [ + 1587, + 1582 + ] + ], + [ + [ + 64543, + 64543 + ], + "mapped", + [ + 1587, + 1605 + ] + ], + [ + [ + 64544, + 64544 + ], + "mapped", + [ + 1589, + 1581 + ] + ], + [ + [ + 64545, + 64545 + ], + "mapped", + [ + 1589, + 1605 + ] + ], + [ + [ + 64546, + 64546 + ], + "mapped", + [ + 1590, + 1580 + ] + ], + [ + [ + 64547, + 64547 + ], + "mapped", + [ + 1590, + 1581 + ] + ], + [ + [ + 64548, + 64548 + ], + "mapped", + [ + 1590, + 1582 + ] + ], + [ + [ + 64549, + 64549 + ], + "mapped", + [ + 1590, + 1605 + ] + ], + [ + [ + 64550, + 64550 + ], + "mapped", + [ + 1591, + 1581 + ] + ], + [ + [ + 64551, + 64551 + ], + "mapped", + [ + 1591, + 1605 + ] + ], + [ + [ + 64552, + 64552 + ], + "mapped", + [ + 1592, + 1605 + ] + ], + [ + [ + 64553, + 64553 + ], + "mapped", + [ + 1593, + 1580 + ] + ], + [ + [ + 64554, + 64554 + ], + "mapped", + [ + 1593, + 1605 + ] + ], + [ + [ + 64555, + 64555 + ], + "mapped", + [ + 1594, + 1580 + ] + ], + [ + [ + 64556, + 64556 + ], + "mapped", + [ + 1594, + 1605 + ] + ], + [ + [ + 64557, + 64557 + ], + "mapped", + [ + 1601, + 1580 + ] + ], + [ + [ + 64558, + 64558 + ], + "mapped", + [ + 1601, + 1581 + ] + ], + [ + [ + 64559, + 64559 + ], + "mapped", + [ + 1601, + 1582 + ] + ], + [ + [ + 64560, + 64560 + ], + "mapped", + [ + 1601, + 1605 + ] + ], + [ + [ + 64561, + 64561 + ], + "mapped", + [ + 1601, + 1609 + ] + ], + [ + [ + 64562, + 64562 + ], + "mapped", + [ + 1601, + 1610 + ] + ], + [ + [ + 64563, + 64563 + ], + "mapped", + [ + 1602, + 1581 + ] + ], + [ + [ + 64564, + 64564 + ], + "mapped", + [ + 1602, + 1605 + ] + ], + [ + [ + 64565, + 64565 + ], + "mapped", + [ + 1602, + 1609 + ] + ], + [ + [ + 64566, + 64566 + ], + "mapped", + [ + 1602, + 1610 + ] + ], + [ + [ + 64567, + 64567 + ], + "mapped", + [ + 1603, + 1575 + ] + ], + [ + [ + 64568, + 64568 + ], + "mapped", + [ + 1603, + 1580 + ] + ], + [ + [ + 64569, + 64569 + ], + "mapped", + [ + 1603, + 1581 + ] + ], + [ + [ + 64570, + 64570 + ], + "mapped", + [ + 1603, + 1582 + ] + ], + [ + [ + 64571, + 64571 + ], + "mapped", + [ + 1603, + 1604 + ] + ], + [ + [ + 64572, + 64572 + ], + "mapped", + [ + 1603, + 1605 + ] + ], + [ + [ + 64573, + 64573 + ], + "mapped", + [ + 1603, + 1609 + ] + ], + [ + [ + 64574, + 64574 + ], + "mapped", + [ + 1603, + 1610 + ] + ], + [ + [ + 64575, + 64575 + ], + "mapped", + [ + 1604, + 1580 + ] + ], + [ + [ + 64576, + 64576 + ], + "mapped", + [ + 1604, + 1581 + ] + ], + [ + [ + 64577, + 64577 + ], + "mapped", + [ + 1604, + 1582 + ] + ], + [ + [ + 64578, + 64578 + ], + "mapped", + [ + 1604, + 1605 + ] + ], + [ + [ + 64579, + 64579 + ], + "mapped", + [ + 1604, + 1609 + ] + ], + [ + [ + 64580, + 64580 + ], + "mapped", + [ + 1604, + 1610 + ] + ], + [ + [ + 64581, + 64581 + ], + "mapped", + [ + 1605, + 1580 + ] + ], + [ + [ + 64582, + 64582 + ], + "mapped", + [ + 1605, + 1581 + ] + ], + [ + [ + 64583, + 64583 + ], + "mapped", + [ + 1605, + 1582 + ] + ], + [ + [ + 64584, + 64584 + ], + "mapped", + [ + 1605, + 1605 + ] + ], + [ + [ + 64585, + 64585 + ], + "mapped", + [ + 1605, + 1609 + ] + ], + [ + [ + 64586, + 64586 + ], + "mapped", + [ + 1605, + 1610 + ] + ], + [ + [ + 64587, + 64587 + ], + "mapped", + [ + 1606, + 1580 + ] + ], + [ + [ + 64588, + 64588 + ], + "mapped", + [ + 1606, + 1581 + ] + ], + [ + [ + 64589, + 64589 + ], + "mapped", + [ + 1606, + 1582 + ] + ], + [ + [ + 64590, + 64590 + ], + "mapped", + [ + 1606, + 1605 + ] + ], + [ + [ + 64591, + 64591 + ], + "mapped", + [ + 1606, + 1609 + ] + ], + [ + [ + 64592, + 64592 + ], + "mapped", + [ + 1606, + 1610 + ] + ], + [ + [ + 64593, + 64593 + ], + "mapped", + [ + 1607, + 1580 + ] + ], + [ + [ + 64594, + 64594 + ], + "mapped", + [ + 1607, + 1605 + ] + ], + [ + [ + 64595, + 64595 + ], + "mapped", + [ + 1607, + 1609 + ] + ], + [ + [ + 64596, + 64596 + ], + "mapped", + [ + 1607, + 1610 + ] + ], + [ + [ + 64597, + 64597 + ], + "mapped", + [ + 1610, + 1580 + ] + ], + [ + [ + 64598, + 64598 + ], + "mapped", + [ + 1610, + 1581 + ] + ], + [ + [ + 64599, + 64599 + ], + "mapped", + [ + 1610, + 1582 + ] + ], + [ + [ + 64600, + 64600 + ], + "mapped", + [ + 1610, + 1605 + ] + ], + [ + [ + 64601, + 64601 + ], + "mapped", + [ + 1610, + 1609 + ] + ], + [ + [ + 64602, + 64602 + ], + "mapped", + [ + 1610, + 1610 + ] + ], + [ + [ + 64603, + 64603 + ], + "mapped", + [ + 1584, + 1648 + ] + ], + [ + [ + 64604, + 64604 + ], + "mapped", + [ + 1585, + 1648 + ] + ], + [ + [ + 64605, + 64605 + ], + "mapped", + [ + 1609, + 1648 + ] + ], + [ + [ + 64606, + 64606 + ], + "disallowed_STD3_mapped", + [ + 32, + 1612, + 1617 + ] + ], + [ + [ + 64607, + 64607 + ], + "disallowed_STD3_mapped", + [ + 32, + 1613, + 1617 + ] + ], + [ + [ + 64608, + 64608 + ], + "disallowed_STD3_mapped", + [ + 32, + 1614, + 1617 + ] + ], + [ + [ + 64609, + 64609 + ], + "disallowed_STD3_mapped", + [ + 32, + 1615, + 1617 + ] + ], + [ + [ + 64610, + 64610 + ], + "disallowed_STD3_mapped", + [ + 32, + 1616, + 1617 + ] + ], + [ + [ + 64611, + 64611 + ], + "disallowed_STD3_mapped", + [ + 32, + 1617, + 1648 + ] + ], + [ + [ + 64612, + 64612 + ], + "mapped", + [ + 1574, + 1585 + ] + ], + [ + [ + 64613, + 64613 + ], + "mapped", + [ + 1574, + 1586 + ] + ], + [ + [ + 64614, + 64614 + ], + "mapped", + [ + 1574, + 1605 + ] + ], + [ + [ + 64615, + 64615 + ], + "mapped", + [ + 1574, + 1606 + ] + ], + [ + [ + 64616, + 64616 + ], + "mapped", + [ + 1574, + 1609 + ] + ], + [ + [ + 64617, + 64617 + ], + "mapped", + [ + 1574, + 1610 + ] + ], + [ + [ + 64618, + 64618 + ], + "mapped", + [ + 1576, + 1585 + ] + ], + [ + [ + 64619, + 64619 + ], + "mapped", + [ + 1576, + 1586 + ] + ], + [ + [ + 64620, + 64620 + ], + "mapped", + [ + 1576, + 1605 + ] + ], + [ + [ + 64621, + 64621 + ], + "mapped", + [ + 1576, + 1606 + ] + ], + [ + [ + 64622, + 64622 + ], + "mapped", + [ + 1576, + 1609 + ] + ], + [ + [ + 64623, + 64623 + ], + "mapped", + [ + 1576, + 1610 + ] + ], + [ + [ + 64624, + 64624 + ], + "mapped", + [ + 1578, + 1585 + ] + ], + [ + [ + 64625, + 64625 + ], + "mapped", + [ + 1578, + 1586 + ] + ], + [ + [ + 64626, + 64626 + ], + "mapped", + [ + 1578, + 1605 + ] + ], + [ + [ + 64627, + 64627 + ], + "mapped", + [ + 1578, + 1606 + ] + ], + [ + [ + 64628, + 64628 + ], + "mapped", + [ + 1578, + 1609 + ] + ], + [ + [ + 64629, + 64629 + ], + "mapped", + [ + 1578, + 1610 + ] + ], + [ + [ + 64630, + 64630 + ], + "mapped", + [ + 1579, + 1585 + ] + ], + [ + [ + 64631, + 64631 + ], + "mapped", + [ + 1579, + 1586 + ] + ], + [ + [ + 64632, + 64632 + ], + "mapped", + [ + 1579, + 1605 + ] + ], + [ + [ + 64633, + 64633 + ], + "mapped", + [ + 1579, + 1606 + ] + ], + [ + [ + 64634, + 64634 + ], + "mapped", + [ + 1579, + 1609 + ] + ], + [ + [ + 64635, + 64635 + ], + "mapped", + [ + 1579, + 1610 + ] + ], + [ + [ + 64636, + 64636 + ], + "mapped", + [ + 1601, + 1609 + ] + ], + [ + [ + 64637, + 64637 + ], + "mapped", + [ + 1601, + 1610 + ] + ], + [ + [ + 64638, + 64638 + ], + "mapped", + [ + 1602, + 1609 + ] + ], + [ + [ + 64639, + 64639 + ], + "mapped", + [ + 1602, + 1610 + ] + ], + [ + [ + 64640, + 64640 + ], + "mapped", + [ + 1603, + 1575 + ] + ], + [ + [ + 64641, + 64641 + ], + "mapped", + [ + 1603, + 1604 + ] + ], + [ + [ + 64642, + 64642 + ], + "mapped", + [ + 1603, + 1605 + ] + ], + [ + [ + 64643, + 64643 + ], + "mapped", + [ + 1603, + 1609 + ] + ], + [ + [ + 64644, + 64644 + ], + "mapped", + [ + 1603, + 1610 + ] + ], + [ + [ + 64645, + 64645 + ], + "mapped", + [ + 1604, + 1605 + ] + ], + [ + [ + 64646, + 64646 + ], + "mapped", + [ + 1604, + 1609 + ] + ], + [ + [ + 64647, + 64647 + ], + "mapped", + [ + 1604, + 1610 + ] + ], + [ + [ + 64648, + 64648 + ], + "mapped", + [ + 1605, + 1575 + ] + ], + [ + [ + 64649, + 64649 + ], + "mapped", + [ + 1605, + 1605 + ] + ], + [ + [ + 64650, + 64650 + ], + "mapped", + [ + 1606, + 1585 + ] + ], + [ + [ + 64651, + 64651 + ], + "mapped", + [ + 1606, + 1586 + ] + ], + [ + [ + 64652, + 64652 + ], + "mapped", + [ + 1606, + 1605 + ] + ], + [ + [ + 64653, + 64653 + ], + "mapped", + [ + 1606, + 1606 + ] + ], + [ + [ + 64654, + 64654 + ], + "mapped", + [ + 1606, + 1609 + ] + ], + [ + [ + 64655, + 64655 + ], + "mapped", + [ + 1606, + 1610 + ] + ], + [ + [ + 64656, + 64656 + ], + "mapped", + [ + 1609, + 1648 + ] + ], + [ + [ + 64657, + 64657 + ], + "mapped", + [ + 1610, + 1585 + ] + ], + [ + [ + 64658, + 64658 + ], + "mapped", + [ + 1610, + 1586 + ] + ], + [ + [ + 64659, + 64659 + ], + "mapped", + [ + 1610, + 1605 + ] + ], + [ + [ + 64660, + 64660 + ], + "mapped", + [ + 1610, + 1606 + ] + ], + [ + [ + 64661, + 64661 + ], + "mapped", + [ + 1610, + 1609 + ] + ], + [ + [ + 64662, + 64662 + ], + "mapped", + [ + 1610, + 1610 + ] + ], + [ + [ + 64663, + 64663 + ], + "mapped", + [ + 1574, + 1580 + ] + ], + [ + [ + 64664, + 64664 + ], + "mapped", + [ + 1574, + 1581 + ] + ], + [ + [ + 64665, + 64665 + ], + "mapped", + [ + 1574, + 1582 + ] + ], + [ + [ + 64666, + 64666 + ], + "mapped", + [ + 1574, + 1605 + ] + ], + [ + [ + 64667, + 64667 + ], + "mapped", + [ + 1574, + 1607 + ] + ], + [ + [ + 64668, + 64668 + ], + "mapped", + [ + 1576, + 1580 + ] + ], + [ + [ + 64669, + 64669 + ], + "mapped", + [ + 1576, + 1581 + ] + ], + [ + [ + 64670, + 64670 + ], + "mapped", + [ + 1576, + 1582 + ] + ], + [ + [ + 64671, + 64671 + ], + "mapped", + [ + 1576, + 1605 + ] + ], + [ + [ + 64672, + 64672 + ], + "mapped", + [ + 1576, + 1607 + ] + ], + [ + [ + 64673, + 64673 + ], + "mapped", + [ + 1578, + 1580 + ] + ], + [ + [ + 64674, + 64674 + ], + "mapped", + [ + 1578, + 1581 + ] + ], + [ + [ + 64675, + 64675 + ], + "mapped", + [ + 1578, + 1582 + ] + ], + [ + [ + 64676, + 64676 + ], + "mapped", + [ + 1578, + 1605 + ] + ], + [ + [ + 64677, + 64677 + ], + "mapped", + [ + 1578, + 1607 + ] + ], + [ + [ + 64678, + 64678 + ], + "mapped", + [ + 1579, + 1605 + ] + ], + [ + [ + 64679, + 64679 + ], + "mapped", + [ + 1580, + 1581 + ] + ], + [ + [ + 64680, + 64680 + ], + "mapped", + [ + 1580, + 1605 + ] + ], + [ + [ + 64681, + 64681 + ], + "mapped", + [ + 1581, + 1580 + ] + ], + [ + [ + 64682, + 64682 + ], + "mapped", + [ + 1581, + 1605 + ] + ], + [ + [ + 64683, + 64683 + ], + "mapped", + [ + 1582, + 1580 + ] + ], + [ + [ + 64684, + 64684 + ], + "mapped", + [ + 1582, + 1605 + ] + ], + [ + [ + 64685, + 64685 + ], + "mapped", + [ + 1587, + 1580 + ] + ], + [ + [ + 64686, + 64686 + ], + "mapped", + [ + 1587, + 1581 + ] + ], + [ + [ + 64687, + 64687 + ], + "mapped", + [ + 1587, + 1582 + ] + ], + [ + [ + 64688, + 64688 + ], + "mapped", + [ + 1587, + 1605 + ] + ], + [ + [ + 64689, + 64689 + ], + "mapped", + [ + 1589, + 1581 + ] + ], + [ + [ + 64690, + 64690 + ], + "mapped", + [ + 1589, + 1582 + ] + ], + [ + [ + 64691, + 64691 + ], + "mapped", + [ + 1589, + 1605 + ] + ], + [ + [ + 64692, + 64692 + ], + "mapped", + [ + 1590, + 1580 + ] + ], + [ + [ + 64693, + 64693 + ], + "mapped", + [ + 1590, + 1581 + ] + ], + [ + [ + 64694, + 64694 + ], + "mapped", + [ + 1590, + 1582 + ] + ], + [ + [ + 64695, + 64695 + ], + "mapped", + [ + 1590, + 1605 + ] + ], + [ + [ + 64696, + 64696 + ], + "mapped", + [ + 1591, + 1581 + ] + ], + [ + [ + 64697, + 64697 + ], + "mapped", + [ + 1592, + 1605 + ] + ], + [ + [ + 64698, + 64698 + ], + "mapped", + [ + 1593, + 1580 + ] + ], + [ + [ + 64699, + 64699 + ], + "mapped", + [ + 1593, + 1605 + ] + ], + [ + [ + 64700, + 64700 + ], + "mapped", + [ + 1594, + 1580 + ] + ], + [ + [ + 64701, + 64701 + ], + "mapped", + [ + 1594, + 1605 + ] + ], + [ + [ + 64702, + 64702 + ], + "mapped", + [ + 1601, + 1580 + ] + ], + [ + [ + 64703, + 64703 + ], + "mapped", + [ + 1601, + 1581 + ] + ], + [ + [ + 64704, + 64704 + ], + "mapped", + [ + 1601, + 1582 + ] + ], + [ + [ + 64705, + 64705 + ], + "mapped", + [ + 1601, + 1605 + ] + ], + [ + [ + 64706, + 64706 + ], + "mapped", + [ + 1602, + 1581 + ] + ], + [ + [ + 64707, + 64707 + ], + "mapped", + [ + 1602, + 1605 + ] + ], + [ + [ + 64708, + 64708 + ], + "mapped", + [ + 1603, + 1580 + ] + ], + [ + [ + 64709, + 64709 + ], + "mapped", + [ + 1603, + 1581 + ] + ], + [ + [ + 64710, + 64710 + ], + "mapped", + [ + 1603, + 1582 + ] + ], + [ + [ + 64711, + 64711 + ], + "mapped", + [ + 1603, + 1604 + ] + ], + [ + [ + 64712, + 64712 + ], + "mapped", + [ + 1603, + 1605 + ] + ], + [ + [ + 64713, + 64713 + ], + "mapped", + [ + 1604, + 1580 + ] + ], + [ + [ + 64714, + 64714 + ], + "mapped", + [ + 1604, + 1581 + ] + ], + [ + [ + 64715, + 64715 + ], + "mapped", + [ + 1604, + 1582 + ] + ], + [ + [ + 64716, + 64716 + ], + "mapped", + [ + 1604, + 1605 + ] + ], + [ + [ + 64717, + 64717 + ], + "mapped", + [ + 1604, + 1607 + ] + ], + [ + [ + 64718, + 64718 + ], + "mapped", + [ + 1605, + 1580 + ] + ], + [ + [ + 64719, + 64719 + ], + "mapped", + [ + 1605, + 1581 + ] + ], + [ + [ + 64720, + 64720 + ], + "mapped", + [ + 1605, + 1582 + ] + ], + [ + [ + 64721, + 64721 + ], + "mapped", + [ + 1605, + 1605 + ] + ], + [ + [ + 64722, + 64722 + ], + "mapped", + [ + 1606, + 1580 + ] + ], + [ + [ + 64723, + 64723 + ], + "mapped", + [ + 1606, + 1581 + ] + ], + [ + [ + 64724, + 64724 + ], + "mapped", + [ + 1606, + 1582 + ] + ], + [ + [ + 64725, + 64725 + ], + "mapped", + [ + 1606, + 1605 + ] + ], + [ + [ + 64726, + 64726 + ], + "mapped", + [ + 1606, + 1607 + ] + ], + [ + [ + 64727, + 64727 + ], + "mapped", + [ + 1607, + 1580 + ] + ], + [ + [ + 64728, + 64728 + ], + "mapped", + [ + 1607, + 1605 + ] + ], + [ + [ + 64729, + 64729 + ], + "mapped", + [ + 1607, + 1648 + ] + ], + [ + [ + 64730, + 64730 + ], + "mapped", + [ + 1610, + 1580 + ] + ], + [ + [ + 64731, + 64731 + ], + "mapped", + [ + 1610, + 1581 + ] + ], + [ + [ + 64732, + 64732 + ], + "mapped", + [ + 1610, + 1582 + ] + ], + [ + [ + 64733, + 64733 + ], + "mapped", + [ + 1610, + 1605 + ] + ], + [ + [ + 64734, + 64734 + ], + "mapped", + [ + 1610, + 1607 + ] + ], + [ + [ + 64735, + 64735 + ], + "mapped", + [ + 1574, + 1605 + ] + ], + [ + [ + 64736, + 64736 + ], + "mapped", + [ + 1574, + 1607 + ] + ], + [ + [ + 64737, + 64737 + ], + "mapped", + [ + 1576, + 1605 + ] + ], + [ + [ + 64738, + 64738 + ], + "mapped", + [ + 1576, + 1607 + ] + ], + [ + [ + 64739, + 64739 + ], + "mapped", + [ + 1578, + 1605 + ] + ], + [ + [ + 64740, + 64740 + ], + "mapped", + [ + 1578, + 1607 + ] + ], + [ + [ + 64741, + 64741 + ], + "mapped", + [ + 1579, + 1605 + ] + ], + [ + [ + 64742, + 64742 + ], + "mapped", + [ + 1579, + 1607 + ] + ], + [ + [ + 64743, + 64743 + ], + "mapped", + [ + 1587, + 1605 + ] + ], + [ + [ + 64744, + 64744 + ], + "mapped", + [ + 1587, + 1607 + ] + ], + [ + [ + 64745, + 64745 + ], + "mapped", + [ + 1588, + 1605 + ] + ], + [ + [ + 64746, + 64746 + ], + "mapped", + [ + 1588, + 1607 + ] + ], + [ + [ + 64747, + 64747 + ], + "mapped", + [ + 1603, + 1604 + ] + ], + [ + [ + 64748, + 64748 + ], + "mapped", + [ + 1603, + 1605 + ] + ], + [ + [ + 64749, + 64749 + ], + "mapped", + [ + 1604, + 1605 + ] + ], + [ + [ + 64750, + 64750 + ], + "mapped", + [ + 1606, + 1605 + ] + ], + [ + [ + 64751, + 64751 + ], + "mapped", + [ + 1606, + 1607 + ] + ], + [ + [ + 64752, + 64752 + ], + "mapped", + [ + 1610, + 1605 + ] + ], + [ + [ + 64753, + 64753 + ], + "mapped", + [ + 1610, + 1607 + ] + ], + [ + [ + 64754, + 64754 + ], + "mapped", + [ + 1600, + 1614, + 1617 + ] + ], + [ + [ + 64755, + 64755 + ], + "mapped", + [ + 1600, + 1615, + 1617 + ] + ], + [ + [ + 64756, + 64756 + ], + "mapped", + [ + 1600, + 1616, + 1617 + ] + ], + [ + [ + 64757, + 64757 + ], + "mapped", + [ + 1591, + 1609 + ] + ], + [ + [ + 64758, + 64758 + ], + "mapped", + [ + 1591, + 1610 + ] + ], + [ + [ + 64759, + 64759 + ], + "mapped", + [ + 1593, + 1609 + ] + ], + [ + [ + 64760, + 64760 + ], + "mapped", + [ + 1593, + 1610 + ] + ], + [ + [ + 64761, + 64761 + ], + "mapped", + [ + 1594, + 1609 + ] + ], + [ + [ + 64762, + 64762 + ], + "mapped", + [ + 1594, + 1610 + ] + ], + [ + [ + 64763, + 64763 + ], + "mapped", + [ + 1587, + 1609 + ] + ], + [ + [ + 64764, + 64764 + ], + "mapped", + [ + 1587, + 1610 + ] + ], + [ + [ + 64765, + 64765 + ], + "mapped", + [ + 1588, + 1609 + ] + ], + [ + [ + 64766, + 64766 + ], + "mapped", + [ + 1588, + 1610 + ] + ], + [ + [ + 64767, + 64767 + ], + "mapped", + [ + 1581, + 1609 + ] + ], + [ + [ + 64768, + 64768 + ], + "mapped", + [ + 1581, + 1610 + ] + ], + [ + [ + 64769, + 64769 + ], + "mapped", + [ + 1580, + 1609 + ] + ], + [ + [ + 64770, + 64770 + ], + "mapped", + [ + 1580, + 1610 + ] + ], + [ + [ + 64771, + 64771 + ], + "mapped", + [ + 1582, + 1609 + ] + ], + [ + [ + 64772, + 64772 + ], + "mapped", + [ + 1582, + 1610 + ] + ], + [ + [ + 64773, + 64773 + ], + "mapped", + [ + 1589, + 1609 + ] + ], + [ + [ + 64774, + 64774 + ], + "mapped", + [ + 1589, + 1610 + ] + ], + [ + [ + 64775, + 64775 + ], + "mapped", + [ + 1590, + 1609 + ] + ], + [ + [ + 64776, + 64776 + ], + "mapped", + [ + 1590, + 1610 + ] + ], + [ + [ + 64777, + 64777 + ], + "mapped", + [ + 1588, + 1580 + ] + ], + [ + [ + 64778, + 64778 + ], + "mapped", + [ + 1588, + 1581 + ] + ], + [ + [ + 64779, + 64779 + ], + "mapped", + [ + 1588, + 1582 + ] + ], + [ + [ + 64780, + 64780 + ], + "mapped", + [ + 1588, + 1605 + ] + ], + [ + [ + 64781, + 64781 + ], + "mapped", + [ + 1588, + 1585 + ] + ], + [ + [ + 64782, + 64782 + ], + "mapped", + [ + 1587, + 1585 + ] + ], + [ + [ + 64783, + 64783 + ], + "mapped", + [ + 1589, + 1585 + ] + ], + [ + [ + 64784, + 64784 + ], + "mapped", + [ + 1590, + 1585 + ] + ], + [ + [ + 64785, + 64785 + ], + "mapped", + [ + 1591, + 1609 + ] + ], + [ + [ + 64786, + 64786 + ], + "mapped", + [ + 1591, + 1610 + ] + ], + [ + [ + 64787, + 64787 + ], + "mapped", + [ + 1593, + 1609 + ] + ], + [ + [ + 64788, + 64788 + ], + "mapped", + [ + 1593, + 1610 + ] + ], + [ + [ + 64789, + 64789 + ], + "mapped", + [ + 1594, + 1609 + ] + ], + [ + [ + 64790, + 64790 + ], + "mapped", + [ + 1594, + 1610 + ] + ], + [ + [ + 64791, + 64791 + ], + "mapped", + [ + 1587, + 1609 + ] + ], + [ + [ + 64792, + 64792 + ], + "mapped", + [ + 1587, + 1610 + ] + ], + [ + [ + 64793, + 64793 + ], + "mapped", + [ + 1588, + 1609 + ] + ], + [ + [ + 64794, + 64794 + ], + "mapped", + [ + 1588, + 1610 + ] + ], + [ + [ + 64795, + 64795 + ], + "mapped", + [ + 1581, + 1609 + ] + ], + [ + [ + 64796, + 64796 + ], + "mapped", + [ + 1581, + 1610 + ] + ], + [ + [ + 64797, + 64797 + ], + "mapped", + [ + 1580, + 1609 + ] + ], + [ + [ + 64798, + 64798 + ], + "mapped", + [ + 1580, + 1610 + ] + ], + [ + [ + 64799, + 64799 + ], + "mapped", + [ + 1582, + 1609 + ] + ], + [ + [ + 64800, + 64800 + ], + "mapped", + [ + 1582, + 1610 + ] + ], + [ + [ + 64801, + 64801 + ], + "mapped", + [ + 1589, + 1609 + ] + ], + [ + [ + 64802, + 64802 + ], + "mapped", + [ + 1589, + 1610 + ] + ], + [ + [ + 64803, + 64803 + ], + "mapped", + [ + 1590, + 1609 + ] + ], + [ + [ + 64804, + 64804 + ], + "mapped", + [ + 1590, + 1610 + ] + ], + [ + [ + 64805, + 64805 + ], + "mapped", + [ + 1588, + 1580 + ] + ], + [ + [ + 64806, + 64806 + ], + "mapped", + [ + 1588, + 1581 + ] + ], + [ + [ + 64807, + 64807 + ], + "mapped", + [ + 1588, + 1582 + ] + ], + [ + [ + 64808, + 64808 + ], + "mapped", + [ + 1588, + 1605 + ] + ], + [ + [ + 64809, + 64809 + ], + "mapped", + [ + 1588, + 1585 + ] + ], + [ + [ + 64810, + 64810 + ], + "mapped", + [ + 1587, + 1585 + ] + ], + [ + [ + 64811, + 64811 + ], + "mapped", + [ + 1589, + 1585 + ] + ], + [ + [ + 64812, + 64812 + ], + "mapped", + [ + 1590, + 1585 + ] + ], + [ + [ + 64813, + 64813 + ], + "mapped", + [ + 1588, + 1580 + ] + ], + [ + [ + 64814, + 64814 + ], + "mapped", + [ + 1588, + 1581 + ] + ], + [ + [ + 64815, + 64815 + ], + "mapped", + [ + 1588, + 1582 + ] + ], + [ + [ + 64816, + 64816 + ], + "mapped", + [ + 1588, + 1605 + ] + ], + [ + [ + 64817, + 64817 + ], + "mapped", + [ + 1587, + 1607 + ] + ], + [ + [ + 64818, + 64818 + ], + "mapped", + [ + 1588, + 1607 + ] + ], + [ + [ + 64819, + 64819 + ], + "mapped", + [ + 1591, + 1605 + ] + ], + [ + [ + 64820, + 64820 + ], + "mapped", + [ + 1587, + 1580 + ] + ], + [ + [ + 64821, + 64821 + ], + "mapped", + [ + 1587, + 1581 + ] + ], + [ + [ + 64822, + 64822 + ], + "mapped", + [ + 1587, + 1582 + ] + ], + [ + [ + 64823, + 64823 + ], + "mapped", + [ + 1588, + 1580 + ] + ], + [ + [ + 64824, + 64824 + ], + "mapped", + [ + 1588, + 1581 + ] + ], + [ + [ + 64825, + 64825 + ], + "mapped", + [ + 1588, + 1582 + ] + ], + [ + [ + 64826, + 64826 + ], + "mapped", + [ + 1591, + 1605 + ] + ], + [ + [ + 64827, + 64827 + ], + "mapped", + [ + 1592, + 1605 + ] + ], + [ + [ + 64828, + 64829 + ], + "mapped", + [ + 1575, + 1611 + ] + ], + [ + [ + 64830, + 64831 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 64832, + 64847 + ], + "disallowed" + ], + [ + [ + 64848, + 64848 + ], + "mapped", + [ + 1578, + 1580, + 1605 + ] + ], + [ + [ + 64849, + 64850 + ], + "mapped", + [ + 1578, + 1581, + 1580 + ] + ], + [ + [ + 64851, + 64851 + ], + "mapped", + [ + 1578, + 1581, + 1605 + ] + ], + [ + [ + 64852, + 64852 + ], + "mapped", + [ + 1578, + 1582, + 1605 + ] + ], + [ + [ + 64853, + 64853 + ], + "mapped", + [ + 1578, + 1605, + 1580 + ] + ], + [ + [ + 64854, + 64854 + ], + "mapped", + [ + 1578, + 1605, + 1581 + ] + ], + [ + [ + 64855, + 64855 + ], + "mapped", + [ + 1578, + 1605, + 1582 + ] + ], + [ + [ + 64856, + 64857 + ], + "mapped", + [ + 1580, + 1605, + 1581 + ] + ], + [ + [ + 64858, + 64858 + ], + "mapped", + [ + 1581, + 1605, + 1610 + ] + ], + [ + [ + 64859, + 64859 + ], + "mapped", + [ + 1581, + 1605, + 1609 + ] + ], + [ + [ + 64860, + 64860 + ], + "mapped", + [ + 1587, + 1581, + 1580 + ] + ], + [ + [ + 64861, + 64861 + ], + "mapped", + [ + 1587, + 1580, + 1581 + ] + ], + [ + [ + 64862, + 64862 + ], + "mapped", + [ + 1587, + 1580, + 1609 + ] + ], + [ + [ + 64863, + 64864 + ], + "mapped", + [ + 1587, + 1605, + 1581 + ] + ], + [ + [ + 64865, + 64865 + ], + "mapped", + [ + 1587, + 1605, + 1580 + ] + ], + [ + [ + 64866, + 64867 + ], + "mapped", + [ + 1587, + 1605, + 1605 + ] + ], + [ + [ + 64868, + 64869 + ], + "mapped", + [ + 1589, + 1581, + 1581 + ] + ], + [ + [ + 64870, + 64870 + ], + "mapped", + [ + 1589, + 1605, + 1605 + ] + ], + [ + [ + 64871, + 64872 + ], + "mapped", + [ + 1588, + 1581, + 1605 + ] + ], + [ + [ + 64873, + 64873 + ], + "mapped", + [ + 1588, + 1580, + 1610 + ] + ], + [ + [ + 64874, + 64875 + ], + "mapped", + [ + 1588, + 1605, + 1582 + ] + ], + [ + [ + 64876, + 64877 + ], + "mapped", + [ + 1588, + 1605, + 1605 + ] + ], + [ + [ + 64878, + 64878 + ], + "mapped", + [ + 1590, + 1581, + 1609 + ] + ], + [ + [ + 64879, + 64880 + ], + "mapped", + [ + 1590, + 1582, + 1605 + ] + ], + [ + [ + 64881, + 64882 + ], + "mapped", + [ + 1591, + 1605, + 1581 + ] + ], + [ + [ + 64883, + 64883 + ], + "mapped", + [ + 1591, + 1605, + 1605 + ] + ], + [ + [ + 64884, + 64884 + ], + "mapped", + [ + 1591, + 1605, + 1610 + ] + ], + [ + [ + 64885, + 64885 + ], + "mapped", + [ + 1593, + 1580, + 1605 + ] + ], + [ + [ + 64886, + 64887 + ], + "mapped", + [ + 1593, + 1605, + 1605 + ] + ], + [ + [ + 64888, + 64888 + ], + "mapped", + [ + 1593, + 1605, + 1609 + ] + ], + [ + [ + 64889, + 64889 + ], + "mapped", + [ + 1594, + 1605, + 1605 + ] + ], + [ + [ + 64890, + 64890 + ], + "mapped", + [ + 1594, + 1605, + 1610 + ] + ], + [ + [ + 64891, + 64891 + ], + "mapped", + [ + 1594, + 1605, + 1609 + ] + ], + [ + [ + 64892, + 64893 + ], + "mapped", + [ + 1601, + 1582, + 1605 + ] + ], + [ + [ + 64894, + 64894 + ], + "mapped", + [ + 1602, + 1605, + 1581 + ] + ], + [ + [ + 64895, + 64895 + ], + "mapped", + [ + 1602, + 1605, + 1605 + ] + ], + [ + [ + 64896, + 64896 + ], + "mapped", + [ + 1604, + 1581, + 1605 + ] + ], + [ + [ + 64897, + 64897 + ], + "mapped", + [ + 1604, + 1581, + 1610 + ] + ], + [ + [ + 64898, + 64898 + ], + "mapped", + [ + 1604, + 1581, + 1609 + ] + ], + [ + [ + 64899, + 64900 + ], + "mapped", + [ + 1604, + 1580, + 1580 + ] + ], + [ + [ + 64901, + 64902 + ], + "mapped", + [ + 1604, + 1582, + 1605 + ] + ], + [ + [ + 64903, + 64904 + ], + "mapped", + [ + 1604, + 1605, + 1581 + ] + ], + [ + [ + 64905, + 64905 + ], + "mapped", + [ + 1605, + 1581, + 1580 + ] + ], + [ + [ + 64906, + 64906 + ], + "mapped", + [ + 1605, + 1581, + 1605 + ] + ], + [ + [ + 64907, + 64907 + ], + "mapped", + [ + 1605, + 1581, + 1610 + ] + ], + [ + [ + 64908, + 64908 + ], + "mapped", + [ + 1605, + 1580, + 1581 + ] + ], + [ + [ + 64909, + 64909 + ], + "mapped", + [ + 1605, + 1580, + 1605 + ] + ], + [ + [ + 64910, + 64910 + ], + "mapped", + [ + 1605, + 1582, + 1580 + ] + ], + [ + [ + 64911, + 64911 + ], + "mapped", + [ + 1605, + 1582, + 1605 + ] + ], + [ + [ + 64912, + 64913 + ], + "disallowed" + ], + [ + [ + 64914, + 64914 + ], + "mapped", + [ + 1605, + 1580, + 1582 + ] + ], + [ + [ + 64915, + 64915 + ], + "mapped", + [ + 1607, + 1605, + 1580 + ] + ], + [ + [ + 64916, + 64916 + ], + "mapped", + [ + 1607, + 1605, + 1605 + ] + ], + [ + [ + 64917, + 64917 + ], + "mapped", + [ + 1606, + 1581, + 1605 + ] + ], + [ + [ + 64918, + 64918 + ], + "mapped", + [ + 1606, + 1581, + 1609 + ] + ], + [ + [ + 64919, + 64920 + ], + "mapped", + [ + 1606, + 1580, + 1605 + ] + ], + [ + [ + 64921, + 64921 + ], + "mapped", + [ + 1606, + 1580, + 1609 + ] + ], + [ + [ + 64922, + 64922 + ], + "mapped", + [ + 1606, + 1605, + 1610 + ] + ], + [ + [ + 64923, + 64923 + ], + "mapped", + [ + 1606, + 1605, + 1609 + ] + ], + [ + [ + 64924, + 64925 + ], + "mapped", + [ + 1610, + 1605, + 1605 + ] + ], + [ + [ + 64926, + 64926 + ], + "mapped", + [ + 1576, + 1582, + 1610 + ] + ], + [ + [ + 64927, + 64927 + ], + "mapped", + [ + 1578, + 1580, + 1610 + ] + ], + [ + [ + 64928, + 64928 + ], + "mapped", + [ + 1578, + 1580, + 1609 + ] + ], + [ + [ + 64929, + 64929 + ], + "mapped", + [ + 1578, + 1582, + 1610 + ] + ], + [ + [ + 64930, + 64930 + ], + "mapped", + [ + 1578, + 1582, + 1609 + ] + ], + [ + [ + 64931, + 64931 + ], + "mapped", + [ + 1578, + 1605, + 1610 + ] + ], + [ + [ + 64932, + 64932 + ], + "mapped", + [ + 1578, + 1605, + 1609 + ] + ], + [ + [ + 64933, + 64933 + ], + "mapped", + [ + 1580, + 1605, + 1610 + ] + ], + [ + [ + 64934, + 64934 + ], + "mapped", + [ + 1580, + 1581, + 1609 + ] + ], + [ + [ + 64935, + 64935 + ], + "mapped", + [ + 1580, + 1605, + 1609 + ] + ], + [ + [ + 64936, + 64936 + ], + "mapped", + [ + 1587, + 1582, + 1609 + ] + ], + [ + [ + 64937, + 64937 + ], + "mapped", + [ + 1589, + 1581, + 1610 + ] + ], + [ + [ + 64938, + 64938 + ], + "mapped", + [ + 1588, + 1581, + 1610 + ] + ], + [ + [ + 64939, + 64939 + ], + "mapped", + [ + 1590, + 1581, + 1610 + ] + ], + [ + [ + 64940, + 64940 + ], + "mapped", + [ + 1604, + 1580, + 1610 + ] + ], + [ + [ + 64941, + 64941 + ], + "mapped", + [ + 1604, + 1605, + 1610 + ] + ], + [ + [ + 64942, + 64942 + ], + "mapped", + [ + 1610, + 1581, + 1610 + ] + ], + [ + [ + 64943, + 64943 + ], + "mapped", + [ + 1610, + 1580, + 1610 + ] + ], + [ + [ + 64944, + 64944 + ], + "mapped", + [ + 1610, + 1605, + 1610 + ] + ], + [ + [ + 64945, + 64945 + ], + "mapped", + [ + 1605, + 1605, + 1610 + ] + ], + [ + [ + 64946, + 64946 + ], + "mapped", + [ + 1602, + 1605, + 1610 + ] + ], + [ + [ + 64947, + 64947 + ], + "mapped", + [ + 1606, + 1581, + 1610 + ] + ], + [ + [ + 64948, + 64948 + ], + "mapped", + [ + 1602, + 1605, + 1581 + ] + ], + [ + [ + 64949, + 64949 + ], + "mapped", + [ + 1604, + 1581, + 1605 + ] + ], + [ + [ + 64950, + 64950 + ], + "mapped", + [ + 1593, + 1605, + 1610 + ] + ], + [ + [ + 64951, + 64951 + ], + "mapped", + [ + 1603, + 1605, + 1610 + ] + ], + [ + [ + 64952, + 64952 + ], + "mapped", + [ + 1606, + 1580, + 1581 + ] + ], + [ + [ + 64953, + 64953 + ], + "mapped", + [ + 1605, + 1582, + 1610 + ] + ], + [ + [ + 64954, + 64954 + ], + "mapped", + [ + 1604, + 1580, + 1605 + ] + ], + [ + [ + 64955, + 64955 + ], + "mapped", + [ + 1603, + 1605, + 1605 + ] + ], + [ + [ + 64956, + 64956 + ], + "mapped", + [ + 1604, + 1580, + 1605 + ] + ], + [ + [ + 64957, + 64957 + ], + "mapped", + [ + 1606, + 1580, + 1581 + ] + ], + [ + [ + 64958, + 64958 + ], + "mapped", + [ + 1580, + 1581, + 1610 + ] + ], + [ + [ + 64959, + 64959 + ], + "mapped", + [ + 1581, + 1580, + 1610 + ] + ], + [ + [ + 64960, + 64960 + ], + "mapped", + [ + 1605, + 1580, + 1610 + ] + ], + [ + [ + 64961, + 64961 + ], + "mapped", + [ + 1601, + 1605, + 1610 + ] + ], + [ + [ + 64962, + 64962 + ], + "mapped", + [ + 1576, + 1581, + 1610 + ] + ], + [ + [ + 64963, + 64963 + ], + "mapped", + [ + 1603, + 1605, + 1605 + ] + ], + [ + [ + 64964, + 64964 + ], + "mapped", + [ + 1593, + 1580, + 1605 + ] + ], + [ + [ + 64965, + 64965 + ], + "mapped", + [ + 1589, + 1605, + 1605 + ] + ], + [ + [ + 64966, + 64966 + ], + "mapped", + [ + 1587, + 1582, + 1610 + ] + ], + [ + [ + 64967, + 64967 + ], + "mapped", + [ + 1606, + 1580, + 1610 + ] + ], + [ + [ + 64968, + 64975 + ], + "disallowed" + ], + [ + [ + 64976, + 65007 + ], + "disallowed" + ], + [ + [ + 65008, + 65008 + ], + "mapped", + [ + 1589, + 1604, + 1746 + ] + ], + [ + [ + 65009, + 65009 + ], + "mapped", + [ + 1602, + 1604, + 1746 + ] + ], + [ + [ + 65010, + 65010 + ], + "mapped", + [ + 1575, + 1604, + 1604, + 1607 + ] + ], + [ + [ + 65011, + 65011 + ], + "mapped", + [ + 1575, + 1603, + 1576, + 1585 + ] + ], + [ + [ + 65012, + 65012 + ], + "mapped", + [ + 1605, + 1581, + 1605, + 1583 + ] + ], + [ + [ + 65013, + 65013 + ], + "mapped", + [ + 1589, + 1604, + 1593, + 1605 + ] + ], + [ + [ + 65014, + 65014 + ], + "mapped", + [ + 1585, + 1587, + 1608, + 1604 + ] + ], + [ + [ + 65015, + 65015 + ], + "mapped", + [ + 1593, + 1604, + 1610, + 1607 + ] + ], + [ + [ + 65016, + 65016 + ], + "mapped", + [ + 1608, + 1587, + 1604, + 1605 + ] + ], + [ + [ + 65017, + 65017 + ], + "mapped", + [ + 1589, + 1604, + 1609 + ] + ], + [ + [ + 65018, + 65018 + ], + "disallowed_STD3_mapped", + [ + 1589, + 1604, + 1609, + 32, + 1575, + 1604, + 1604, + 1607, + 32, + 1593, + 1604, + 1610, + 1607, + 32, + 1608, + 1587, + 1604, + 1605 + ] + ], + [ + [ + 65019, + 65019 + ], + "disallowed_STD3_mapped", + [ + 1580, + 1604, + 32, + 1580, + 1604, + 1575, + 1604, + 1607 + ] + ], + [ + [ + 65020, + 65020 + ], + "mapped", + [ + 1585, + 1740, + 1575, + 1604 + ] + ], + [ + [ + 65021, + 65021 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 65022, + 65023 + ], + "disallowed" + ], + [ + [ + 65024, + 65039 + ], + "ignored" + ], + [ + [ + 65040, + 65040 + ], + "disallowed_STD3_mapped", + [ + 44 + ] + ], + [ + [ + 65041, + 65041 + ], + "mapped", + [ + 12289 + ] + ], + [ + [ + 65042, + 65042 + ], + "disallowed" + ], + [ + [ + 65043, + 65043 + ], + "disallowed_STD3_mapped", + [ + 58 + ] + ], + [ + [ + 65044, + 65044 + ], + "disallowed_STD3_mapped", + [ + 59 + ] + ], + [ + [ + 65045, + 65045 + ], + "disallowed_STD3_mapped", + [ + 33 + ] + ], + [ + [ + 65046, + 65046 + ], + "disallowed_STD3_mapped", + [ + 63 + ] + ], + [ + [ + 65047, + 65047 + ], + "mapped", + [ + 12310 + ] + ], + [ + [ + 65048, + 65048 + ], + "mapped", + [ + 12311 + ] + ], + [ + [ + 65049, + 65049 + ], + "disallowed" + ], + [ + [ + 65050, + 65055 + ], + "disallowed" + ], + [ + [ + 65056, + 65059 + ], + "valid" + ], + [ + [ + 65060, + 65062 + ], + "valid" + ], + [ + [ + 65063, + 65069 + ], + "valid" + ], + [ + [ + 65070, + 65071 + ], + "valid" + ], + [ + [ + 65072, + 65072 + ], + "disallowed" + ], + [ + [ + 65073, + 65073 + ], + "mapped", + [ + 8212 + ] + ], + [ + [ + 65074, + 65074 + ], + "mapped", + [ + 8211 + ] + ], + [ + [ + 65075, + 65076 + ], + "disallowed_STD3_mapped", + [ + 95 + ] + ], + [ + [ + 65077, + 65077 + ], + "disallowed_STD3_mapped", + [ + 40 + ] + ], + [ + [ + 65078, + 65078 + ], + "disallowed_STD3_mapped", + [ + 41 + ] + ], + [ + [ + 65079, + 65079 + ], + "disallowed_STD3_mapped", + [ + 123 + ] + ], + [ + [ + 65080, + 65080 + ], + "disallowed_STD3_mapped", + [ + 125 + ] + ], + [ + [ + 65081, + 65081 + ], + "mapped", + [ + 12308 + ] + ], + [ + [ + 65082, + 65082 + ], + "mapped", + [ + 12309 + ] + ], + [ + [ + 65083, + 65083 + ], + "mapped", + [ + 12304 + ] + ], + [ + [ + 65084, + 65084 + ], + "mapped", + [ + 12305 + ] + ], + [ + [ + 65085, + 65085 + ], + "mapped", + [ + 12298 + ] + ], + [ + [ + 65086, + 65086 + ], + "mapped", + [ + 12299 + ] + ], + [ + [ + 65087, + 65087 + ], + "mapped", + [ + 12296 + ] + ], + [ + [ + 65088, + 65088 + ], + "mapped", + [ + 12297 + ] + ], + [ + [ + 65089, + 65089 + ], + "mapped", + [ + 12300 + ] + ], + [ + [ + 65090, + 65090 + ], + "mapped", + [ + 12301 + ] + ], + [ + [ + 65091, + 65091 + ], + "mapped", + [ + 12302 + ] + ], + [ + [ + 65092, + 65092 + ], + "mapped", + [ + 12303 + ] + ], + [ + [ + 65093, + 65094 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 65095, + 65095 + ], + "disallowed_STD3_mapped", + [ + 91 + ] + ], + [ + [ + 65096, + 65096 + ], + "disallowed_STD3_mapped", + [ + 93 + ] + ], + [ + [ + 65097, + 65100 + ], + "disallowed_STD3_mapped", + [ + 32, + 773 + ] + ], + [ + [ + 65101, + 65103 + ], + "disallowed_STD3_mapped", + [ + 95 + ] + ], + [ + [ + 65104, + 65104 + ], + "disallowed_STD3_mapped", + [ + 44 + ] + ], + [ + [ + 65105, + 65105 + ], + "mapped", + [ + 12289 + ] + ], + [ + [ + 65106, + 65106 + ], + "disallowed" + ], + [ + [ + 65107, + 65107 + ], + "disallowed" + ], + [ + [ + 65108, + 65108 + ], + "disallowed_STD3_mapped", + [ + 59 + ] + ], + [ + [ + 65109, + 65109 + ], + "disallowed_STD3_mapped", + [ + 58 + ] + ], + [ + [ + 65110, + 65110 + ], + "disallowed_STD3_mapped", + [ + 63 + ] + ], + [ + [ + 65111, + 65111 + ], + "disallowed_STD3_mapped", + [ + 33 + ] + ], + [ + [ + 65112, + 65112 + ], + "mapped", + [ + 8212 + ] + ], + [ + [ + 65113, + 65113 + ], + "disallowed_STD3_mapped", + [ + 40 + ] + ], + [ + [ + 65114, + 65114 + ], + "disallowed_STD3_mapped", + [ + 41 + ] + ], + [ + [ + 65115, + 65115 + ], + "disallowed_STD3_mapped", + [ + 123 + ] + ], + [ + [ + 65116, + 65116 + ], + "disallowed_STD3_mapped", + [ + 125 + ] + ], + [ + [ + 65117, + 65117 + ], + "mapped", + [ + 12308 + ] + ], + [ + [ + 65118, + 65118 + ], + "mapped", + [ + 12309 + ] + ], + [ + [ + 65119, + 65119 + ], + "disallowed_STD3_mapped", + [ + 35 + ] + ], + [ + [ + 65120, + 65120 + ], + "disallowed_STD3_mapped", + [ + 38 + ] + ], + [ + [ + 65121, + 65121 + ], + "disallowed_STD3_mapped", + [ + 42 + ] + ], + [ + [ + 65122, + 65122 + ], + "disallowed_STD3_mapped", + [ + 43 + ] + ], + [ + [ + 65123, + 65123 + ], + "mapped", + [ + 45 + ] + ], + [ + [ + 65124, + 65124 + ], + "disallowed_STD3_mapped", + [ + 60 + ] + ], + [ + [ + 65125, + 65125 + ], + "disallowed_STD3_mapped", + [ + 62 + ] + ], + [ + [ + 65126, + 65126 + ], + "disallowed_STD3_mapped", + [ + 61 + ] + ], + [ + [ + 65127, + 65127 + ], + "disallowed" + ], + [ + [ + 65128, + 65128 + ], + "disallowed_STD3_mapped", + [ + 92 + ] + ], + [ + [ + 65129, + 65129 + ], + "disallowed_STD3_mapped", + [ + 36 + ] + ], + [ + [ + 65130, + 65130 + ], + "disallowed_STD3_mapped", + [ + 37 + ] + ], + [ + [ + 65131, + 65131 + ], + "disallowed_STD3_mapped", + [ + 64 + ] + ], + [ + [ + 65132, + 65135 + ], + "disallowed" + ], + [ + [ + 65136, + 65136 + ], + "disallowed_STD3_mapped", + [ + 32, + 1611 + ] + ], + [ + [ + 65137, + 65137 + ], + "mapped", + [ + 1600, + 1611 + ] + ], + [ + [ + 65138, + 65138 + ], + "disallowed_STD3_mapped", + [ + 32, + 1612 + ] + ], + [ + [ + 65139, + 65139 + ], + "valid" + ], + [ + [ + 65140, + 65140 + ], + "disallowed_STD3_mapped", + [ + 32, + 1613 + ] + ], + [ + [ + 65141, + 65141 + ], + "disallowed" + ], + [ + [ + 65142, + 65142 + ], + "disallowed_STD3_mapped", + [ + 32, + 1614 + ] + ], + [ + [ + 65143, + 65143 + ], + "mapped", + [ + 1600, + 1614 + ] + ], + [ + [ + 65144, + 65144 + ], + "disallowed_STD3_mapped", + [ + 32, + 1615 + ] + ], + [ + [ + 65145, + 65145 + ], + "mapped", + [ + 1600, + 1615 + ] + ], + [ + [ + 65146, + 65146 + ], + "disallowed_STD3_mapped", + [ + 32, + 1616 + ] + ], + [ + [ + 65147, + 65147 + ], + "mapped", + [ + 1600, + 1616 + ] + ], + [ + [ + 65148, + 65148 + ], + "disallowed_STD3_mapped", + [ + 32, + 1617 + ] + ], + [ + [ + 65149, + 65149 + ], + "mapped", + [ + 1600, + 1617 + ] + ], + [ + [ + 65150, + 65150 + ], + "disallowed_STD3_mapped", + [ + 32, + 1618 + ] + ], + [ + [ + 65151, + 65151 + ], + "mapped", + [ + 1600, + 1618 + ] + ], + [ + [ + 65152, + 65152 + ], + "mapped", + [ + 1569 + ] + ], + [ + [ + 65153, + 65154 + ], + "mapped", + [ + 1570 + ] + ], + [ + [ + 65155, + 65156 + ], + "mapped", + [ + 1571 + ] + ], + [ + [ + 65157, + 65158 + ], + "mapped", + [ + 1572 + ] + ], + [ + [ + 65159, + 65160 + ], + "mapped", + [ + 1573 + ] + ], + [ + [ + 65161, + 65164 + ], + "mapped", + [ + 1574 + ] + ], + [ + [ + 65165, + 65166 + ], + "mapped", + [ + 1575 + ] + ], + [ + [ + 65167, + 65170 + ], + "mapped", + [ + 1576 + ] + ], + [ + [ + 65171, + 65172 + ], + "mapped", + [ + 1577 + ] + ], + [ + [ + 65173, + 65176 + ], + "mapped", + [ + 1578 + ] + ], + [ + [ + 65177, + 65180 + ], + "mapped", + [ + 1579 + ] + ], + [ + [ + 65181, + 65184 + ], + "mapped", + [ + 1580 + ] + ], + [ + [ + 65185, + 65188 + ], + "mapped", + [ + 1581 + ] + ], + [ + [ + 65189, + 65192 + ], + "mapped", + [ + 1582 + ] + ], + [ + [ + 65193, + 65194 + ], + "mapped", + [ + 1583 + ] + ], + [ + [ + 65195, + 65196 + ], + "mapped", + [ + 1584 + ] + ], + [ + [ + 65197, + 65198 + ], + "mapped", + [ + 1585 + ] + ], + [ + [ + 65199, + 65200 + ], + "mapped", + [ + 1586 + ] + ], + [ + [ + 65201, + 65204 + ], + "mapped", + [ + 1587 + ] + ], + [ + [ + 65205, + 65208 + ], + "mapped", + [ + 1588 + ] + ], + [ + [ + 65209, + 65212 + ], + "mapped", + [ + 1589 + ] + ], + [ + [ + 65213, + 65216 + ], + "mapped", + [ + 1590 + ] + ], + [ + [ + 65217, + 65220 + ], + "mapped", + [ + 1591 + ] + ], + [ + [ + 65221, + 65224 + ], + "mapped", + [ + 1592 + ] + ], + [ + [ + 65225, + 65228 + ], + "mapped", + [ + 1593 + ] + ], + [ + [ + 65229, + 65232 + ], + "mapped", + [ + 1594 + ] + ], + [ + [ + 65233, + 65236 + ], + "mapped", + [ + 1601 + ] + ], + [ + [ + 65237, + 65240 + ], + "mapped", + [ + 1602 + ] + ], + [ + [ + 65241, + 65244 + ], + "mapped", + [ + 1603 + ] + ], + [ + [ + 65245, + 65248 + ], + "mapped", + [ + 1604 + ] + ], + [ + [ + 65249, + 65252 + ], + "mapped", + [ + 1605 + ] + ], + [ + [ + 65253, + 65256 + ], + "mapped", + [ + 1606 + ] + ], + [ + [ + 65257, + 65260 + ], + "mapped", + [ + 1607 + ] + ], + [ + [ + 65261, + 65262 + ], + "mapped", + [ + 1608 + ] + ], + [ + [ + 65263, + 65264 + ], + "mapped", + [ + 1609 + ] + ], + [ + [ + 65265, + 65268 + ], + "mapped", + [ + 1610 + ] + ], + [ + [ + 65269, + 65270 + ], + "mapped", + [ + 1604, + 1570 + ] + ], + [ + [ + 65271, + 65272 + ], + "mapped", + [ + 1604, + 1571 + ] + ], + [ + [ + 65273, + 65274 + ], + "mapped", + [ + 1604, + 1573 + ] + ], + [ + [ + 65275, + 65276 + ], + "mapped", + [ + 1604, + 1575 + ] + ], + [ + [ + 65277, + 65278 + ], + "disallowed" + ], + [ + [ + 65279, + 65279 + ], + "ignored" + ], + [ + [ + 65280, + 65280 + ], + "disallowed" + ], + [ + [ + 65281, + 65281 + ], + "disallowed_STD3_mapped", + [ + 33 + ] + ], + [ + [ + 65282, + 65282 + ], + "disallowed_STD3_mapped", + [ + 34 + ] + ], + [ + [ + 65283, + 65283 + ], + "disallowed_STD3_mapped", + [ + 35 + ] + ], + [ + [ + 65284, + 65284 + ], + "disallowed_STD3_mapped", + [ + 36 + ] + ], + [ + [ + 65285, + 65285 + ], + "disallowed_STD3_mapped", + [ + 37 + ] + ], + [ + [ + 65286, + 65286 + ], + "disallowed_STD3_mapped", + [ + 38 + ] + ], + [ + [ + 65287, + 65287 + ], + "disallowed_STD3_mapped", + [ + 39 + ] + ], + [ + [ + 65288, + 65288 + ], + "disallowed_STD3_mapped", + [ + 40 + ] + ], + [ + [ + 65289, + 65289 + ], + "disallowed_STD3_mapped", + [ + 41 + ] + ], + [ + [ + 65290, + 65290 + ], + "disallowed_STD3_mapped", + [ + 42 + ] + ], + [ + [ + 65291, + 65291 + ], + "disallowed_STD3_mapped", + [ + 43 + ] + ], + [ + [ + 65292, + 65292 + ], + "disallowed_STD3_mapped", + [ + 44 + ] + ], + [ + [ + 65293, + 65293 + ], + "mapped", + [ + 45 + ] + ], + [ + [ + 65294, + 65294 + ], + "mapped", + [ + 46 + ] + ], + [ + [ + 65295, + 65295 + ], + "disallowed_STD3_mapped", + [ + 47 + ] + ], + [ + [ + 65296, + 65296 + ], + "mapped", + [ + 48 + ] + ], + [ + [ + 65297, + 65297 + ], + "mapped", + [ + 49 + ] + ], + [ + [ + 65298, + 65298 + ], + "mapped", + [ + 50 + ] + ], + [ + [ + 65299, + 65299 + ], + "mapped", + [ + 51 + ] + ], + [ + [ + 65300, + 65300 + ], + "mapped", + [ + 52 + ] + ], + [ + [ + 65301, + 65301 + ], + "mapped", + [ + 53 + ] + ], + [ + [ + 65302, + 65302 + ], + "mapped", + [ + 54 + ] + ], + [ + [ + 65303, + 65303 + ], + "mapped", + [ + 55 + ] + ], + [ + [ + 65304, + 65304 + ], + "mapped", + [ + 56 + ] + ], + [ + [ + 65305, + 65305 + ], + "mapped", + [ + 57 + ] + ], + [ + [ + 65306, + 65306 + ], + "disallowed_STD3_mapped", + [ + 58 + ] + ], + [ + [ + 65307, + 65307 + ], + "disallowed_STD3_mapped", + [ + 59 + ] + ], + [ + [ + 65308, + 65308 + ], + "disallowed_STD3_mapped", + [ + 60 + ] + ], + [ + [ + 65309, + 65309 + ], + "disallowed_STD3_mapped", + [ + 61 + ] + ], + [ + [ + 65310, + 65310 + ], + "disallowed_STD3_mapped", + [ + 62 + ] + ], + [ + [ + 65311, + 65311 + ], + "disallowed_STD3_mapped", + [ + 63 + ] + ], + [ + [ + 65312, + 65312 + ], + "disallowed_STD3_mapped", + [ + 64 + ] + ], + [ + [ + 65313, + 65313 + ], + "mapped", + [ + 97 + ] + ], + [ + [ + 65314, + 65314 + ], + "mapped", + [ + 98 + ] + ], + [ + [ + 65315, + 65315 + ], + "mapped", + [ + 99 + ] + ], + [ + [ + 65316, + 65316 + ], + "mapped", + [ + 100 + ] + ], + [ + [ + 65317, + 65317 + ], + "mapped", + [ + 101 + ] + ], + [ + [ + 65318, + 65318 + ], + "mapped", + [ + 102 + ] + ], + [ + [ + 65319, + 65319 + ], + "mapped", + [ + 103 + ] + ], + [ + [ + 65320, + 65320 + ], + "mapped", + [ + 104 + ] + ], + [ + [ + 65321, + 65321 + ], + "mapped", + [ + 105 + ] + ], + [ + [ + 65322, + 65322 + ], + "mapped", + [ + 106 + ] + ], + [ + [ + 65323, + 65323 + ], + "mapped", + [ + 107 + ] + ], + [ + [ + 65324, + 65324 + ], + "mapped", + [ + 108 + ] + ], + [ + [ + 65325, + 65325 + ], + "mapped", + [ + 109 + ] + ], + [ + [ + 65326, + 65326 + ], + "mapped", + [ + 110 + ] + ], + [ + [ + 65327, + 65327 + ], + "mapped", + [ + 111 + ] + ], + [ + [ + 65328, + 65328 + ], + "mapped", + [ + 112 + ] + ], + [ + [ + 65329, + 65329 + ], + "mapped", + [ + 113 + ] + ], + [ + [ + 65330, + 65330 + ], + "mapped", + [ + 114 + ] + ], + [ + [ + 65331, + 65331 + ], + "mapped", + [ + 115 + ] + ], + [ + [ + 65332, + 65332 + ], + "mapped", + [ + 116 + ] + ], + [ + [ + 65333, + 65333 + ], + "mapped", + [ + 117 + ] + ], + [ + [ + 65334, + 65334 + ], + "mapped", + [ + 118 + ] + ], + [ + [ + 65335, + 65335 + ], + "mapped", + [ + 119 + ] + ], + [ + [ + 65336, + 65336 + ], + "mapped", + [ + 120 + ] + ], + [ + [ + 65337, + 65337 + ], + "mapped", + [ + 121 + ] + ], + [ + [ + 65338, + 65338 + ], + "mapped", + [ + 122 + ] + ], + [ + [ + 65339, + 65339 + ], + "disallowed_STD3_mapped", + [ + 91 + ] + ], + [ + [ + 65340, + 65340 + ], + "disallowed_STD3_mapped", + [ + 92 + ] + ], + [ + [ + 65341, + 65341 + ], + "disallowed_STD3_mapped", + [ + 93 + ] + ], + [ + [ + 65342, + 65342 + ], + "disallowed_STD3_mapped", + [ + 94 + ] + ], + [ + [ + 65343, + 65343 + ], + "disallowed_STD3_mapped", + [ + 95 + ] + ], + [ + [ + 65344, + 65344 + ], + "disallowed_STD3_mapped", + [ + 96 + ] + ], + [ + [ + 65345, + 65345 + ], + "mapped", + [ + 97 + ] + ], + [ + [ + 65346, + 65346 + ], + "mapped", + [ + 98 + ] + ], + [ + [ + 65347, + 65347 + ], + "mapped", + [ + 99 + ] + ], + [ + [ + 65348, + 65348 + ], + "mapped", + [ + 100 + ] + ], + [ + [ + 65349, + 65349 + ], + "mapped", + [ + 101 + ] + ], + [ + [ + 65350, + 65350 + ], + "mapped", + [ + 102 + ] + ], + [ + [ + 65351, + 65351 + ], + "mapped", + [ + 103 + ] + ], + [ + [ + 65352, + 65352 + ], + "mapped", + [ + 104 + ] + ], + [ + [ + 65353, + 65353 + ], + "mapped", + [ + 105 + ] + ], + [ + [ + 65354, + 65354 + ], + "mapped", + [ + 106 + ] + ], + [ + [ + 65355, + 65355 + ], + "mapped", + [ + 107 + ] + ], + [ + [ + 65356, + 65356 + ], + "mapped", + [ + 108 + ] + ], + [ + [ + 65357, + 65357 + ], + "mapped", + [ + 109 + ] + ], + [ + [ + 65358, + 65358 + ], + "mapped", + [ + 110 + ] + ], + [ + [ + 65359, + 65359 + ], + "mapped", + [ + 111 + ] + ], + [ + [ + 65360, + 65360 + ], + "mapped", + [ + 112 + ] + ], + [ + [ + 65361, + 65361 + ], + "mapped", + [ + 113 + ] + ], + [ + [ + 65362, + 65362 + ], + "mapped", + [ + 114 + ] + ], + [ + [ + 65363, + 65363 + ], + "mapped", + [ + 115 + ] + ], + [ + [ + 65364, + 65364 + ], + "mapped", + [ + 116 + ] + ], + [ + [ + 65365, + 65365 + ], + "mapped", + [ + 117 + ] + ], + [ + [ + 65366, + 65366 + ], + "mapped", + [ + 118 + ] + ], + [ + [ + 65367, + 65367 + ], + "mapped", + [ + 119 + ] + ], + [ + [ + 65368, + 65368 + ], + "mapped", + [ + 120 + ] + ], + [ + [ + 65369, + 65369 + ], + "mapped", + [ + 121 + ] + ], + [ + [ + 65370, + 65370 + ], + "mapped", + [ + 122 + ] + ], + [ + [ + 65371, + 65371 + ], + "disallowed_STD3_mapped", + [ + 123 + ] + ], + [ + [ + 65372, + 65372 + ], + "disallowed_STD3_mapped", + [ + 124 + ] + ], + [ + [ + 65373, + 65373 + ], + "disallowed_STD3_mapped", + [ + 125 + ] + ], + [ + [ + 65374, + 65374 + ], + "disallowed_STD3_mapped", + [ + 126 + ] + ], + [ + [ + 65375, + 65375 + ], + "mapped", + [ + 10629 + ] + ], + [ + [ + 65376, + 65376 + ], + "mapped", + [ + 10630 + ] + ], + [ + [ + 65377, + 65377 + ], + "mapped", + [ + 46 + ] + ], + [ + [ + 65378, + 65378 + ], + "mapped", + [ + 12300 + ] + ], + [ + [ + 65379, + 65379 + ], + "mapped", + [ + 12301 + ] + ], + [ + [ + 65380, + 65380 + ], + "mapped", + [ + 12289 + ] + ], + [ + [ + 65381, + 65381 + ], + "mapped", + [ + 12539 + ] + ], + [ + [ + 65382, + 65382 + ], + "mapped", + [ + 12530 + ] + ], + [ + [ + 65383, + 65383 + ], + "mapped", + [ + 12449 + ] + ], + [ + [ + 65384, + 65384 + ], + "mapped", + [ + 12451 + ] + ], + [ + [ + 65385, + 65385 + ], + "mapped", + [ + 12453 + ] + ], + [ + [ + 65386, + 65386 + ], + "mapped", + [ + 12455 + ] + ], + [ + [ + 65387, + 65387 + ], + "mapped", + [ + 12457 + ] + ], + [ + [ + 65388, + 65388 + ], + "mapped", + [ + 12515 + ] + ], + [ + [ + 65389, + 65389 + ], + "mapped", + [ + 12517 + ] + ], + [ + [ + 65390, + 65390 + ], + "mapped", + [ + 12519 + ] + ], + [ + [ + 65391, + 65391 + ], + "mapped", + [ + 12483 + ] + ], + [ + [ + 65392, + 65392 + ], + "mapped", + [ + 12540 + ] + ], + [ + [ + 65393, + 65393 + ], + "mapped", + [ + 12450 + ] + ], + [ + [ + 65394, + 65394 + ], + "mapped", + [ + 12452 + ] + ], + [ + [ + 65395, + 65395 + ], + "mapped", + [ + 12454 + ] + ], + [ + [ + 65396, + 65396 + ], + "mapped", + [ + 12456 + ] + ], + [ + [ + 65397, + 65397 + ], + "mapped", + [ + 12458 + ] + ], + [ + [ + 65398, + 65398 + ], + "mapped", + [ + 12459 + ] + ], + [ + [ + 65399, + 65399 + ], + "mapped", + [ + 12461 + ] + ], + [ + [ + 65400, + 65400 + ], + "mapped", + [ + 12463 + ] + ], + [ + [ + 65401, + 65401 + ], + "mapped", + [ + 12465 + ] + ], + [ + [ + 65402, + 65402 + ], + "mapped", + [ + 12467 + ] + ], + [ + [ + 65403, + 65403 + ], + "mapped", + [ + 12469 + ] + ], + [ + [ + 65404, + 65404 + ], + "mapped", + [ + 12471 + ] + ], + [ + [ + 65405, + 65405 + ], + "mapped", + [ + 12473 + ] + ], + [ + [ + 65406, + 65406 + ], + "mapped", + [ + 12475 + ] + ], + [ + [ + 65407, + 65407 + ], + "mapped", + [ + 12477 + ] + ], + [ + [ + 65408, + 65408 + ], + "mapped", + [ + 12479 + ] + ], + [ + [ + 65409, + 65409 + ], + "mapped", + [ + 12481 + ] + ], + [ + [ + 65410, + 65410 + ], + "mapped", + [ + 12484 + ] + ], + [ + [ + 65411, + 65411 + ], + "mapped", + [ + 12486 + ] + ], + [ + [ + 65412, + 65412 + ], + "mapped", + [ + 12488 + ] + ], + [ + [ + 65413, + 65413 + ], + "mapped", + [ + 12490 + ] + ], + [ + [ + 65414, + 65414 + ], + "mapped", + [ + 12491 + ] + ], + [ + [ + 65415, + 65415 + ], + "mapped", + [ + 12492 + ] + ], + [ + [ + 65416, + 65416 + ], + "mapped", + [ + 12493 + ] + ], + [ + [ + 65417, + 65417 + ], + "mapped", + [ + 12494 + ] + ], + [ + [ + 65418, + 65418 + ], + "mapped", + [ + 12495 + ] + ], + [ + [ + 65419, + 65419 + ], + "mapped", + [ + 12498 + ] + ], + [ + [ + 65420, + 65420 + ], + "mapped", + [ + 12501 + ] + ], + [ + [ + 65421, + 65421 + ], + "mapped", + [ + 12504 + ] + ], + [ + [ + 65422, + 65422 + ], + "mapped", + [ + 12507 + ] + ], + [ + [ + 65423, + 65423 + ], + "mapped", + [ + 12510 + ] + ], + [ + [ + 65424, + 65424 + ], + "mapped", + [ + 12511 + ] + ], + [ + [ + 65425, + 65425 + ], + "mapped", + [ + 12512 + ] + ], + [ + [ + 65426, + 65426 + ], + "mapped", + [ + 12513 + ] + ], + [ + [ + 65427, + 65427 + ], + "mapped", + [ + 12514 + ] + ], + [ + [ + 65428, + 65428 + ], + "mapped", + [ + 12516 + ] + ], + [ + [ + 65429, + 65429 + ], + "mapped", + [ + 12518 + ] + ], + [ + [ + 65430, + 65430 + ], + "mapped", + [ + 12520 + ] + ], + [ + [ + 65431, + 65431 + ], + "mapped", + [ + 12521 + ] + ], + [ + [ + 65432, + 65432 + ], + "mapped", + [ + 12522 + ] + ], + [ + [ + 65433, + 65433 + ], + "mapped", + [ + 12523 + ] + ], + [ + [ + 65434, + 65434 + ], + "mapped", + [ + 12524 + ] + ], + [ + [ + 65435, + 65435 + ], + "mapped", + [ + 12525 + ] + ], + [ + [ + 65436, + 65436 + ], + "mapped", + [ + 12527 + ] + ], + [ + [ + 65437, + 65437 + ], + "mapped", + [ + 12531 + ] + ], + [ + [ + 65438, + 65438 + ], + "mapped", + [ + 12441 + ] + ], + [ + [ + 65439, + 65439 + ], + "mapped", + [ + 12442 + ] + ], + [ + [ + 65440, + 65440 + ], + "disallowed" + ], + [ + [ + 65441, + 65441 + ], + "mapped", + [ + 4352 + ] + ], + [ + [ + 65442, + 65442 + ], + "mapped", + [ + 4353 + ] + ], + [ + [ + 65443, + 65443 + ], + "mapped", + [ + 4522 + ] + ], + [ + [ + 65444, + 65444 + ], + "mapped", + [ + 4354 + ] + ], + [ + [ + 65445, + 65445 + ], + "mapped", + [ + 4524 + ] + ], + [ + [ + 65446, + 65446 + ], + "mapped", + [ + 4525 + ] + ], + [ + [ + 65447, + 65447 + ], + "mapped", + [ + 4355 + ] + ], + [ + [ + 65448, + 65448 + ], + "mapped", + [ + 4356 + ] + ], + [ + [ + 65449, + 65449 + ], + "mapped", + [ + 4357 + ] + ], + [ + [ + 65450, + 65450 + ], + "mapped", + [ + 4528 + ] + ], + [ + [ + 65451, + 65451 + ], + "mapped", + [ + 4529 + ] + ], + [ + [ + 65452, + 65452 + ], + "mapped", + [ + 4530 + ] + ], + [ + [ + 65453, + 65453 + ], + "mapped", + [ + 4531 + ] + ], + [ + [ + 65454, + 65454 + ], + "mapped", + [ + 4532 + ] + ], + [ + [ + 65455, + 65455 + ], + "mapped", + [ + 4533 + ] + ], + [ + [ + 65456, + 65456 + ], + "mapped", + [ + 4378 + ] + ], + [ + [ + 65457, + 65457 + ], + "mapped", + [ + 4358 + ] + ], + [ + [ + 65458, + 65458 + ], + "mapped", + [ + 4359 + ] + ], + [ + [ + 65459, + 65459 + ], + "mapped", + [ + 4360 + ] + ], + [ + [ + 65460, + 65460 + ], + "mapped", + [ + 4385 + ] + ], + [ + [ + 65461, + 65461 + ], + "mapped", + [ + 4361 + ] + ], + [ + [ + 65462, + 65462 + ], + "mapped", + [ + 4362 + ] + ], + [ + [ + 65463, + 65463 + ], + "mapped", + [ + 4363 + ] + ], + [ + [ + 65464, + 65464 + ], + "mapped", + [ + 4364 + ] + ], + [ + [ + 65465, + 65465 + ], + "mapped", + [ + 4365 + ] + ], + [ + [ + 65466, + 65466 + ], + "mapped", + [ + 4366 + ] + ], + [ + [ + 65467, + 65467 + ], + "mapped", + [ + 4367 + ] + ], + [ + [ + 65468, + 65468 + ], + "mapped", + [ + 4368 + ] + ], + [ + [ + 65469, + 65469 + ], + "mapped", + [ + 4369 + ] + ], + [ + [ + 65470, + 65470 + ], + "mapped", + [ + 4370 + ] + ], + [ + [ + 65471, + 65473 + ], + "disallowed" + ], + [ + [ + 65474, + 65474 + ], + "mapped", + [ + 4449 + ] + ], + [ + [ + 65475, + 65475 + ], + "mapped", + [ + 4450 + ] + ], + [ + [ + 65476, + 65476 + ], + "mapped", + [ + 4451 + ] + ], + [ + [ + 65477, + 65477 + ], + "mapped", + [ + 4452 + ] + ], + [ + [ + 65478, + 65478 + ], + "mapped", + [ + 4453 + ] + ], + [ + [ + 65479, + 65479 + ], + "mapped", + [ + 4454 + ] + ], + [ + [ + 65480, + 65481 + ], + "disallowed" + ], + [ + [ + 65482, + 65482 + ], + "mapped", + [ + 4455 + ] + ], + [ + [ + 65483, + 65483 + ], + "mapped", + [ + 4456 + ] + ], + [ + [ + 65484, + 65484 + ], + "mapped", + [ + 4457 + ] + ], + [ + [ + 65485, + 65485 + ], + "mapped", + [ + 4458 + ] + ], + [ + [ + 65486, + 65486 + ], + "mapped", + [ + 4459 + ] + ], + [ + [ + 65487, + 65487 + ], + "mapped", + [ + 4460 + ] + ], + [ + [ + 65488, + 65489 + ], + "disallowed" + ], + [ + [ + 65490, + 65490 + ], + "mapped", + [ + 4461 + ] + ], + [ + [ + 65491, + 65491 + ], + "mapped", + [ + 4462 + ] + ], + [ + [ + 65492, + 65492 + ], + "mapped", + [ + 4463 + ] + ], + [ + [ + 65493, + 65493 + ], + "mapped", + [ + 4464 + ] + ], + [ + [ + 65494, + 65494 + ], + "mapped", + [ + 4465 + ] + ], + [ + [ + 65495, + 65495 + ], + "mapped", + [ + 4466 + ] + ], + [ + [ + 65496, + 65497 + ], + "disallowed" + ], + [ + [ + 65498, + 65498 + ], + "mapped", + [ + 4467 + ] + ], + [ + [ + 65499, + 65499 + ], + "mapped", + [ + 4468 + ] + ], + [ + [ + 65500, + 65500 + ], + "mapped", + [ + 4469 + ] + ], + [ + [ + 65501, + 65503 + ], + "disallowed" + ], + [ + [ + 65504, + 65504 + ], + "mapped", + [ + 162 + ] + ], + [ + [ + 65505, + 65505 + ], + "mapped", + [ + 163 + ] + ], + [ + [ + 65506, + 65506 + ], + "mapped", + [ + 172 + ] + ], + [ + [ + 65507, + 65507 + ], + "disallowed_STD3_mapped", + [ + 32, + 772 + ] + ], + [ + [ + 65508, + 65508 + ], + "mapped", + [ + 166 + ] + ], + [ + [ + 65509, + 65509 + ], + "mapped", + [ + 165 + ] + ], + [ + [ + 65510, + 65510 + ], + "mapped", + [ + 8361 + ] + ], + [ + [ + 65511, + 65511 + ], + "disallowed" + ], + [ + [ + 65512, + 65512 + ], + "mapped", + [ + 9474 + ] + ], + [ + [ + 65513, + 65513 + ], + "mapped", + [ + 8592 + ] + ], + [ + [ + 65514, + 65514 + ], + "mapped", + [ + 8593 + ] + ], + [ + [ + 65515, + 65515 + ], + "mapped", + [ + 8594 + ] + ], + [ + [ + 65516, + 65516 + ], + "mapped", + [ + 8595 + ] + ], + [ + [ + 65517, + 65517 + ], + "mapped", + [ + 9632 + ] + ], + [ + [ + 65518, + 65518 + ], + "mapped", + [ + 9675 + ] + ], + [ + [ + 65519, + 65528 + ], + "disallowed" + ], + [ + [ + 65529, + 65531 + ], + "disallowed" + ], + [ + [ + 65532, + 65532 + ], + "disallowed" + ], + [ + [ + 65533, + 65533 + ], + "disallowed" + ], + [ + [ + 65534, + 65535 + ], + "disallowed" + ], + [ + [ + 65536, + 65547 + ], + "valid" + ], + [ + [ + 65548, + 65548 + ], + "disallowed" + ], + [ + [ + 65549, + 65574 + ], + "valid" + ], + [ + [ + 65575, + 65575 + ], + "disallowed" + ], + [ + [ + 65576, + 65594 + ], + "valid" + ], + [ + [ + 65595, + 65595 + ], + "disallowed" + ], + [ + [ + 65596, + 65597 + ], + "valid" + ], + [ + [ + 65598, + 65598 + ], + "disallowed" + ], + [ + [ + 65599, + 65613 + ], + "valid" + ], + [ + [ + 65614, + 65615 + ], + "disallowed" + ], + [ + [ + 65616, + 65629 + ], + "valid" + ], + [ + [ + 65630, + 65663 + ], + "disallowed" + ], + [ + [ + 65664, + 65786 + ], + "valid" + ], + [ + [ + 65787, + 65791 + ], + "disallowed" + ], + [ + [ + 65792, + 65794 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 65795, + 65798 + ], + "disallowed" + ], + [ + [ + 65799, + 65843 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 65844, + 65846 + ], + "disallowed" + ], + [ + [ + 65847, + 65855 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 65856, + 65930 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 65931, + 65932 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 65933, + 65935 + ], + "disallowed" + ], + [ + [ + 65936, + 65947 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 65948, + 65951 + ], + "disallowed" + ], + [ + [ + 65952, + 65952 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 65953, + 65999 + ], + "disallowed" + ], + [ + [ + 66000, + 66044 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 66045, + 66045 + ], + "valid" + ], + [ + [ + 66046, + 66175 + ], + "disallowed" + ], + [ + [ + 66176, + 66204 + ], + "valid" + ], + [ + [ + 66205, + 66207 + ], + "disallowed" + ], + [ + [ + 66208, + 66256 + ], + "valid" + ], + [ + [ + 66257, + 66271 + ], + "disallowed" + ], + [ + [ + 66272, + 66272 + ], + "valid" + ], + [ + [ + 66273, + 66299 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 66300, + 66303 + ], + "disallowed" + ], + [ + [ + 66304, + 66334 + ], + "valid" + ], + [ + [ + 66335, + 66335 + ], + "valid" + ], + [ + [ + 66336, + 66339 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 66340, + 66351 + ], + "disallowed" + ], + [ + [ + 66352, + 66368 + ], + "valid" + ], + [ + [ + 66369, + 66369 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 66370, + 66377 + ], + "valid" + ], + [ + [ + 66378, + 66378 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 66379, + 66383 + ], + "disallowed" + ], + [ + [ + 66384, + 66426 + ], + "valid" + ], + [ + [ + 66427, + 66431 + ], + "disallowed" + ], + [ + [ + 66432, + 66461 + ], + "valid" + ], + [ + [ + 66462, + 66462 + ], + "disallowed" + ], + [ + [ + 66463, + 66463 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 66464, + 66499 + ], + "valid" + ], + [ + [ + 66500, + 66503 + ], + "disallowed" + ], + [ + [ + 66504, + 66511 + ], + "valid" + ], + [ + [ + 66512, + 66517 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 66518, + 66559 + ], + "disallowed" + ], + [ + [ + 66560, + 66560 + ], + "mapped", + [ + 66600 + ] + ], + [ + [ + 66561, + 66561 + ], + "mapped", + [ + 66601 + ] + ], + [ + [ + 66562, + 66562 + ], + "mapped", + [ + 66602 + ] + ], + [ + [ + 66563, + 66563 + ], + "mapped", + [ + 66603 + ] + ], + [ + [ + 66564, + 66564 + ], + "mapped", + [ + 66604 + ] + ], + [ + [ + 66565, + 66565 + ], + "mapped", + [ + 66605 + ] + ], + [ + [ + 66566, + 66566 + ], + "mapped", + [ + 66606 + ] + ], + [ + [ + 66567, + 66567 + ], + "mapped", + [ + 66607 + ] + ], + [ + [ + 66568, + 66568 + ], + "mapped", + [ + 66608 + ] + ], + [ + [ + 66569, + 66569 + ], + "mapped", + [ + 66609 + ] + ], + [ + [ + 66570, + 66570 + ], + "mapped", + [ + 66610 + ] + ], + [ + [ + 66571, + 66571 + ], + "mapped", + [ + 66611 + ] + ], + [ + [ + 66572, + 66572 + ], + "mapped", + [ + 66612 + ] + ], + [ + [ + 66573, + 66573 + ], + "mapped", + [ + 66613 + ] + ], + [ + [ + 66574, + 66574 + ], + "mapped", + [ + 66614 + ] + ], + [ + [ + 66575, + 66575 + ], + "mapped", + [ + 66615 + ] + ], + [ + [ + 66576, + 66576 + ], + "mapped", + [ + 66616 + ] + ], + [ + [ + 66577, + 66577 + ], + "mapped", + [ + 66617 + ] + ], + [ + [ + 66578, + 66578 + ], + "mapped", + [ + 66618 + ] + ], + [ + [ + 66579, + 66579 + ], + "mapped", + [ + 66619 + ] + ], + [ + [ + 66580, + 66580 + ], + "mapped", + [ + 66620 + ] + ], + [ + [ + 66581, + 66581 + ], + "mapped", + [ + 66621 + ] + ], + [ + [ + 66582, + 66582 + ], + "mapped", + [ + 66622 + ] + ], + [ + [ + 66583, + 66583 + ], + "mapped", + [ + 66623 + ] + ], + [ + [ + 66584, + 66584 + ], + "mapped", + [ + 66624 + ] + ], + [ + [ + 66585, + 66585 + ], + "mapped", + [ + 66625 + ] + ], + [ + [ + 66586, + 66586 + ], + "mapped", + [ + 66626 + ] + ], + [ + [ + 66587, + 66587 + ], + "mapped", + [ + 66627 + ] + ], + [ + [ + 66588, + 66588 + ], + "mapped", + [ + 66628 + ] + ], + [ + [ + 66589, + 66589 + ], + "mapped", + [ + 66629 + ] + ], + [ + [ + 66590, + 66590 + ], + "mapped", + [ + 66630 + ] + ], + [ + [ + 66591, + 66591 + ], + "mapped", + [ + 66631 + ] + ], + [ + [ + 66592, + 66592 + ], + "mapped", + [ + 66632 + ] + ], + [ + [ + 66593, + 66593 + ], + "mapped", + [ + 66633 + ] + ], + [ + [ + 66594, + 66594 + ], + "mapped", + [ + 66634 + ] + ], + [ + [ + 66595, + 66595 + ], + "mapped", + [ + 66635 + ] + ], + [ + [ + 66596, + 66596 + ], + "mapped", + [ + 66636 + ] + ], + [ + [ + 66597, + 66597 + ], + "mapped", + [ + 66637 + ] + ], + [ + [ + 66598, + 66598 + ], + "mapped", + [ + 66638 + ] + ], + [ + [ + 66599, + 66599 + ], + "mapped", + [ + 66639 + ] + ], + [ + [ + 66600, + 66637 + ], + "valid" + ], + [ + [ + 66638, + 66717 + ], + "valid" + ], + [ + [ + 66718, + 66719 + ], + "disallowed" + ], + [ + [ + 66720, + 66729 + ], + "valid" + ], + [ + [ + 66730, + 66815 + ], + "disallowed" + ], + [ + [ + 66816, + 66855 + ], + "valid" + ], + [ + [ + 66856, + 66863 + ], + "disallowed" + ], + [ + [ + 66864, + 66915 + ], + "valid" + ], + [ + [ + 66916, + 66926 + ], + "disallowed" + ], + [ + [ + 66927, + 66927 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 66928, + 67071 + ], + "disallowed" + ], + [ + [ + 67072, + 67382 + ], + "valid" + ], + [ + [ + 67383, + 67391 + ], + "disallowed" + ], + [ + [ + 67392, + 67413 + ], + "valid" + ], + [ + [ + 67414, + 67423 + ], + "disallowed" + ], + [ + [ + 67424, + 67431 + ], + "valid" + ], + [ + [ + 67432, + 67583 + ], + "disallowed" + ], + [ + [ + 67584, + 67589 + ], + "valid" + ], + [ + [ + 67590, + 67591 + ], + "disallowed" + ], + [ + [ + 67592, + 67592 + ], + "valid" + ], + [ + [ + 67593, + 67593 + ], + "disallowed" + ], + [ + [ + 67594, + 67637 + ], + "valid" + ], + [ + [ + 67638, + 67638 + ], + "disallowed" + ], + [ + [ + 67639, + 67640 + ], + "valid" + ], + [ + [ + 67641, + 67643 + ], + "disallowed" + ], + [ + [ + 67644, + 67644 + ], + "valid" + ], + [ + [ + 67645, + 67646 + ], + "disallowed" + ], + [ + [ + 67647, + 67647 + ], + "valid" + ], + [ + [ + 67648, + 67669 + ], + "valid" + ], + [ + [ + 67670, + 67670 + ], + "disallowed" + ], + [ + [ + 67671, + 67679 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 67680, + 67702 + ], + "valid" + ], + [ + [ + 67703, + 67711 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 67712, + 67742 + ], + "valid" + ], + [ + [ + 67743, + 67750 + ], + "disallowed" + ], + [ + [ + 67751, + 67759 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 67760, + 67807 + ], + "disallowed" + ], + [ + [ + 67808, + 67826 + ], + "valid" + ], + [ + [ + 67827, + 67827 + ], + "disallowed" + ], + [ + [ + 67828, + 67829 + ], + "valid" + ], + [ + [ + 67830, + 67834 + ], + "disallowed" + ], + [ + [ + 67835, + 67839 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 67840, + 67861 + ], + "valid" + ], + [ + [ + 67862, + 67865 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 67866, + 67867 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 67868, + 67870 + ], + "disallowed" + ], + [ + [ + 67871, + 67871 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 67872, + 67897 + ], + "valid" + ], + [ + [ + 67898, + 67902 + ], + "disallowed" + ], + [ + [ + 67903, + 67903 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 67904, + 67967 + ], + "disallowed" + ], + [ + [ + 67968, + 68023 + ], + "valid" + ], + [ + [ + 68024, + 68027 + ], + "disallowed" + ], + [ + [ + 68028, + 68029 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 68030, + 68031 + ], + "valid" + ], + [ + [ + 68032, + 68047 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 68048, + 68049 + ], + "disallowed" + ], + [ + [ + 68050, + 68095 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 68096, + 68099 + ], + "valid" + ], + [ + [ + 68100, + 68100 + ], + "disallowed" + ], + [ + [ + 68101, + 68102 + ], + "valid" + ], + [ + [ + 68103, + 68107 + ], + "disallowed" + ], + [ + [ + 68108, + 68115 + ], + "valid" + ], + [ + [ + 68116, + 68116 + ], + "disallowed" + ], + [ + [ + 68117, + 68119 + ], + "valid" + ], + [ + [ + 68120, + 68120 + ], + "disallowed" + ], + [ + [ + 68121, + 68147 + ], + "valid" + ], + [ + [ + 68148, + 68151 + ], + "disallowed" + ], + [ + [ + 68152, + 68154 + ], + "valid" + ], + [ + [ + 68155, + 68158 + ], + "disallowed" + ], + [ + [ + 68159, + 68159 + ], + "valid" + ], + [ + [ + 68160, + 68167 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 68168, + 68175 + ], + "disallowed" + ], + [ + [ + 68176, + 68184 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 68185, + 68191 + ], + "disallowed" + ], + [ + [ + 68192, + 68220 + ], + "valid" + ], + [ + [ + 68221, + 68223 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 68224, + 68252 + ], + "valid" + ], + [ + [ + 68253, + 68255 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 68256, + 68287 + ], + "disallowed" + ], + [ + [ + 68288, + 68295 + ], + "valid" + ], + [ + [ + 68296, + 68296 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 68297, + 68326 + ], + "valid" + ], + [ + [ + 68327, + 68330 + ], + "disallowed" + ], + [ + [ + 68331, + 68342 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 68343, + 68351 + ], + "disallowed" + ], + [ + [ + 68352, + 68405 + ], + "valid" + ], + [ + [ + 68406, + 68408 + ], + "disallowed" + ], + [ + [ + 68409, + 68415 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 68416, + 68437 + ], + "valid" + ], + [ + [ + 68438, + 68439 + ], + "disallowed" + ], + [ + [ + 68440, + 68447 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 68448, + 68466 + ], + "valid" + ], + [ + [ + 68467, + 68471 + ], + "disallowed" + ], + [ + [ + 68472, + 68479 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 68480, + 68497 + ], + "valid" + ], + [ + [ + 68498, + 68504 + ], + "disallowed" + ], + [ + [ + 68505, + 68508 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 68509, + 68520 + ], + "disallowed" + ], + [ + [ + 68521, + 68527 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 68528, + 68607 + ], + "disallowed" + ], + [ + [ + 68608, + 68680 + ], + "valid" + ], + [ + [ + 68681, + 68735 + ], + "disallowed" + ], + [ + [ + 68736, + 68736 + ], + "mapped", + [ + 68800 + ] + ], + [ + [ + 68737, + 68737 + ], + "mapped", + [ + 68801 + ] + ], + [ + [ + 68738, + 68738 + ], + "mapped", + [ + 68802 + ] + ], + [ + [ + 68739, + 68739 + ], + "mapped", + [ + 68803 + ] + ], + [ + [ + 68740, + 68740 + ], + "mapped", + [ + 68804 + ] + ], + [ + [ + 68741, + 68741 + ], + "mapped", + [ + 68805 + ] + ], + [ + [ + 68742, + 68742 + ], + "mapped", + [ + 68806 + ] + ], + [ + [ + 68743, + 68743 + ], + "mapped", + [ + 68807 + ] + ], + [ + [ + 68744, + 68744 + ], + "mapped", + [ + 68808 + ] + ], + [ + [ + 68745, + 68745 + ], + "mapped", + [ + 68809 + ] + ], + [ + [ + 68746, + 68746 + ], + "mapped", + [ + 68810 + ] + ], + [ + [ + 68747, + 68747 + ], + "mapped", + [ + 68811 + ] + ], + [ + [ + 68748, + 68748 + ], + "mapped", + [ + 68812 + ] + ], + [ + [ + 68749, + 68749 + ], + "mapped", + [ + 68813 + ] + ], + [ + [ + 68750, + 68750 + ], + "mapped", + [ + 68814 + ] + ], + [ + [ + 68751, + 68751 + ], + "mapped", + [ + 68815 + ] + ], + [ + [ + 68752, + 68752 + ], + "mapped", + [ + 68816 + ] + ], + [ + [ + 68753, + 68753 + ], + "mapped", + [ + 68817 + ] + ], + [ + [ + 68754, + 68754 + ], + "mapped", + [ + 68818 + ] + ], + [ + [ + 68755, + 68755 + ], + "mapped", + [ + 68819 + ] + ], + [ + [ + 68756, + 68756 + ], + "mapped", + [ + 68820 + ] + ], + [ + [ + 68757, + 68757 + ], + "mapped", + [ + 68821 + ] + ], + [ + [ + 68758, + 68758 + ], + "mapped", + [ + 68822 + ] + ], + [ + [ + 68759, + 68759 + ], + "mapped", + [ + 68823 + ] + ], + [ + [ + 68760, + 68760 + ], + "mapped", + [ + 68824 + ] + ], + [ + [ + 68761, + 68761 + ], + "mapped", + [ + 68825 + ] + ], + [ + [ + 68762, + 68762 + ], + "mapped", + [ + 68826 + ] + ], + [ + [ + 68763, + 68763 + ], + "mapped", + [ + 68827 + ] + ], + [ + [ + 68764, + 68764 + ], + "mapped", + [ + 68828 + ] + ], + [ + [ + 68765, + 68765 + ], + "mapped", + [ + 68829 + ] + ], + [ + [ + 68766, + 68766 + ], + "mapped", + [ + 68830 + ] + ], + [ + [ + 68767, + 68767 + ], + "mapped", + [ + 68831 + ] + ], + [ + [ + 68768, + 68768 + ], + "mapped", + [ + 68832 + ] + ], + [ + [ + 68769, + 68769 + ], + "mapped", + [ + 68833 + ] + ], + [ + [ + 68770, + 68770 + ], + "mapped", + [ + 68834 + ] + ], + [ + [ + 68771, + 68771 + ], + "mapped", + [ + 68835 + ] + ], + [ + [ + 68772, + 68772 + ], + "mapped", + [ + 68836 + ] + ], + [ + [ + 68773, + 68773 + ], + "mapped", + [ + 68837 + ] + ], + [ + [ + 68774, + 68774 + ], + "mapped", + [ + 68838 + ] + ], + [ + [ + 68775, + 68775 + ], + "mapped", + [ + 68839 + ] + ], + [ + [ + 68776, + 68776 + ], + "mapped", + [ + 68840 + ] + ], + [ + [ + 68777, + 68777 + ], + "mapped", + [ + 68841 + ] + ], + [ + [ + 68778, + 68778 + ], + "mapped", + [ + 68842 + ] + ], + [ + [ + 68779, + 68779 + ], + "mapped", + [ + 68843 + ] + ], + [ + [ + 68780, + 68780 + ], + "mapped", + [ + 68844 + ] + ], + [ + [ + 68781, + 68781 + ], + "mapped", + [ + 68845 + ] + ], + [ + [ + 68782, + 68782 + ], + "mapped", + [ + 68846 + ] + ], + [ + [ + 68783, + 68783 + ], + "mapped", + [ + 68847 + ] + ], + [ + [ + 68784, + 68784 + ], + "mapped", + [ + 68848 + ] + ], + [ + [ + 68785, + 68785 + ], + "mapped", + [ + 68849 + ] + ], + [ + [ + 68786, + 68786 + ], + "mapped", + [ + 68850 + ] + ], + [ + [ + 68787, + 68799 + ], + "disallowed" + ], + [ + [ + 68800, + 68850 + ], + "valid" + ], + [ + [ + 68851, + 68857 + ], + "disallowed" + ], + [ + [ + 68858, + 68863 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 68864, + 69215 + ], + "disallowed" + ], + [ + [ + 69216, + 69246 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 69247, + 69631 + ], + "disallowed" + ], + [ + [ + 69632, + 69702 + ], + "valid" + ], + [ + [ + 69703, + 69709 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 69710, + 69713 + ], + "disallowed" + ], + [ + [ + 69714, + 69733 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 69734, + 69743 + ], + "valid" + ], + [ + [ + 69744, + 69758 + ], + "disallowed" + ], + [ + [ + 69759, + 69759 + ], + "valid" + ], + [ + [ + 69760, + 69818 + ], + "valid" + ], + [ + [ + 69819, + 69820 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 69821, + 69821 + ], + "disallowed" + ], + [ + [ + 69822, + 69825 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 69826, + 69839 + ], + "disallowed" + ], + [ + [ + 69840, + 69864 + ], + "valid" + ], + [ + [ + 69865, + 69871 + ], + "disallowed" + ], + [ + [ + 69872, + 69881 + ], + "valid" + ], + [ + [ + 69882, + 69887 + ], + "disallowed" + ], + [ + [ + 69888, + 69940 + ], + "valid" + ], + [ + [ + 69941, + 69941 + ], + "disallowed" + ], + [ + [ + 69942, + 69951 + ], + "valid" + ], + [ + [ + 69952, + 69955 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 69956, + 69967 + ], + "disallowed" + ], + [ + [ + 69968, + 70003 + ], + "valid" + ], + [ + [ + 70004, + 70005 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 70006, + 70006 + ], + "valid" + ], + [ + [ + 70007, + 70015 + ], + "disallowed" + ], + [ + [ + 70016, + 70084 + ], + "valid" + ], + [ + [ + 70085, + 70088 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 70089, + 70089 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 70090, + 70092 + ], + "valid" + ], + [ + [ + 70093, + 70093 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 70094, + 70095 + ], + "disallowed" + ], + [ + [ + 70096, + 70105 + ], + "valid" + ], + [ + [ + 70106, + 70106 + ], + "valid" + ], + [ + [ + 70107, + 70107 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 70108, + 70108 + ], + "valid" + ], + [ + [ + 70109, + 70111 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 70112, + 70112 + ], + "disallowed" + ], + [ + [ + 70113, + 70132 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 70133, + 70143 + ], + "disallowed" + ], + [ + [ + 70144, + 70161 + ], + "valid" + ], + [ + [ + 70162, + 70162 + ], + "disallowed" + ], + [ + [ + 70163, + 70199 + ], + "valid" + ], + [ + [ + 70200, + 70205 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 70206, + 70271 + ], + "disallowed" + ], + [ + [ + 70272, + 70278 + ], + "valid" + ], + [ + [ + 70279, + 70279 + ], + "disallowed" + ], + [ + [ + 70280, + 70280 + ], + "valid" + ], + [ + [ + 70281, + 70281 + ], + "disallowed" + ], + [ + [ + 70282, + 70285 + ], + "valid" + ], + [ + [ + 70286, + 70286 + ], + "disallowed" + ], + [ + [ + 70287, + 70301 + ], + "valid" + ], + [ + [ + 70302, + 70302 + ], + "disallowed" + ], + [ + [ + 70303, + 70312 + ], + "valid" + ], + [ + [ + 70313, + 70313 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 70314, + 70319 + ], + "disallowed" + ], + [ + [ + 70320, + 70378 + ], + "valid" + ], + [ + [ + 70379, + 70383 + ], + "disallowed" + ], + [ + [ + 70384, + 70393 + ], + "valid" + ], + [ + [ + 70394, + 70399 + ], + "disallowed" + ], + [ + [ + 70400, + 70400 + ], + "valid" + ], + [ + [ + 70401, + 70403 + ], + "valid" + ], + [ + [ + 70404, + 70404 + ], + "disallowed" + ], + [ + [ + 70405, + 70412 + ], + "valid" + ], + [ + [ + 70413, + 70414 + ], + "disallowed" + ], + [ + [ + 70415, + 70416 + ], + "valid" + ], + [ + [ + 70417, + 70418 + ], + "disallowed" + ], + [ + [ + 70419, + 70440 + ], + "valid" + ], + [ + [ + 70441, + 70441 + ], + "disallowed" + ], + [ + [ + 70442, + 70448 + ], + "valid" + ], + [ + [ + 70449, + 70449 + ], + "disallowed" + ], + [ + [ + 70450, + 70451 + ], + "valid" + ], + [ + [ + 70452, + 70452 + ], + "disallowed" + ], + [ + [ + 70453, + 70457 + ], + "valid" + ], + [ + [ + 70458, + 70459 + ], + "disallowed" + ], + [ + [ + 70460, + 70468 + ], + "valid" + ], + [ + [ + 70469, + 70470 + ], + "disallowed" + ], + [ + [ + 70471, + 70472 + ], + "valid" + ], + [ + [ + 70473, + 70474 + ], + "disallowed" + ], + [ + [ + 70475, + 70477 + ], + "valid" + ], + [ + [ + 70478, + 70479 + ], + "disallowed" + ], + [ + [ + 70480, + 70480 + ], + "valid" + ], + [ + [ + 70481, + 70486 + ], + "disallowed" + ], + [ + [ + 70487, + 70487 + ], + "valid" + ], + [ + [ + 70488, + 70492 + ], + "disallowed" + ], + [ + [ + 70493, + 70499 + ], + "valid" + ], + [ + [ + 70500, + 70501 + ], + "disallowed" + ], + [ + [ + 70502, + 70508 + ], + "valid" + ], + [ + [ + 70509, + 70511 + ], + "disallowed" + ], + [ + [ + 70512, + 70516 + ], + "valid" + ], + [ + [ + 70517, + 70783 + ], + "disallowed" + ], + [ + [ + 70784, + 70853 + ], + "valid" + ], + [ + [ + 70854, + 70854 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 70855, + 70855 + ], + "valid" + ], + [ + [ + 70856, + 70863 + ], + "disallowed" + ], + [ + [ + 70864, + 70873 + ], + "valid" + ], + [ + [ + 70874, + 71039 + ], + "disallowed" + ], + [ + [ + 71040, + 71093 + ], + "valid" + ], + [ + [ + 71094, + 71095 + ], + "disallowed" + ], + [ + [ + 71096, + 71104 + ], + "valid" + ], + [ + [ + 71105, + 71113 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 71114, + 71127 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 71128, + 71133 + ], + "valid" + ], + [ + [ + 71134, + 71167 + ], + "disallowed" + ], + [ + [ + 71168, + 71232 + ], + "valid" + ], + [ + [ + 71233, + 71235 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 71236, + 71236 + ], + "valid" + ], + [ + [ + 71237, + 71247 + ], + "disallowed" + ], + [ + [ + 71248, + 71257 + ], + "valid" + ], + [ + [ + 71258, + 71295 + ], + "disallowed" + ], + [ + [ + 71296, + 71351 + ], + "valid" + ], + [ + [ + 71352, + 71359 + ], + "disallowed" + ], + [ + [ + 71360, + 71369 + ], + "valid" + ], + [ + [ + 71370, + 71423 + ], + "disallowed" + ], + [ + [ + 71424, + 71449 + ], + "valid" + ], + [ + [ + 71450, + 71452 + ], + "disallowed" + ], + [ + [ + 71453, + 71467 + ], + "valid" + ], + [ + [ + 71468, + 71471 + ], + "disallowed" + ], + [ + [ + 71472, + 71481 + ], + "valid" + ], + [ + [ + 71482, + 71487 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 71488, + 71839 + ], + "disallowed" + ], + [ + [ + 71840, + 71840 + ], + "mapped", + [ + 71872 + ] + ], + [ + [ + 71841, + 71841 + ], + "mapped", + [ + 71873 + ] + ], + [ + [ + 71842, + 71842 + ], + "mapped", + [ + 71874 + ] + ], + [ + [ + 71843, + 71843 + ], + "mapped", + [ + 71875 + ] + ], + [ + [ + 71844, + 71844 + ], + "mapped", + [ + 71876 + ] + ], + [ + [ + 71845, + 71845 + ], + "mapped", + [ + 71877 + ] + ], + [ + [ + 71846, + 71846 + ], + "mapped", + [ + 71878 + ] + ], + [ + [ + 71847, + 71847 + ], + "mapped", + [ + 71879 + ] + ], + [ + [ + 71848, + 71848 + ], + "mapped", + [ + 71880 + ] + ], + [ + [ + 71849, + 71849 + ], + "mapped", + [ + 71881 + ] + ], + [ + [ + 71850, + 71850 + ], + "mapped", + [ + 71882 + ] + ], + [ + [ + 71851, + 71851 + ], + "mapped", + [ + 71883 + ] + ], + [ + [ + 71852, + 71852 + ], + "mapped", + [ + 71884 + ] + ], + [ + [ + 71853, + 71853 + ], + "mapped", + [ + 71885 + ] + ], + [ + [ + 71854, + 71854 + ], + "mapped", + [ + 71886 + ] + ], + [ + [ + 71855, + 71855 + ], + "mapped", + [ + 71887 + ] + ], + [ + [ + 71856, + 71856 + ], + "mapped", + [ + 71888 + ] + ], + [ + [ + 71857, + 71857 + ], + "mapped", + [ + 71889 + ] + ], + [ + [ + 71858, + 71858 + ], + "mapped", + [ + 71890 + ] + ], + [ + [ + 71859, + 71859 + ], + "mapped", + [ + 71891 + ] + ], + [ + [ + 71860, + 71860 + ], + "mapped", + [ + 71892 + ] + ], + [ + [ + 71861, + 71861 + ], + "mapped", + [ + 71893 + ] + ], + [ + [ + 71862, + 71862 + ], + "mapped", + [ + 71894 + ] + ], + [ + [ + 71863, + 71863 + ], + "mapped", + [ + 71895 + ] + ], + [ + [ + 71864, + 71864 + ], + "mapped", + [ + 71896 + ] + ], + [ + [ + 71865, + 71865 + ], + "mapped", + [ + 71897 + ] + ], + [ + [ + 71866, + 71866 + ], + "mapped", + [ + 71898 + ] + ], + [ + [ + 71867, + 71867 + ], + "mapped", + [ + 71899 + ] + ], + [ + [ + 71868, + 71868 + ], + "mapped", + [ + 71900 + ] + ], + [ + [ + 71869, + 71869 + ], + "mapped", + [ + 71901 + ] + ], + [ + [ + 71870, + 71870 + ], + "mapped", + [ + 71902 + ] + ], + [ + [ + 71871, + 71871 + ], + "mapped", + [ + 71903 + ] + ], + [ + [ + 71872, + 71913 + ], + "valid" + ], + [ + [ + 71914, + 71922 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 71923, + 71934 + ], + "disallowed" + ], + [ + [ + 71935, + 71935 + ], + "valid" + ], + [ + [ + 71936, + 72383 + ], + "disallowed" + ], + [ + [ + 72384, + 72440 + ], + "valid" + ], + [ + [ + 72441, + 73727 + ], + "disallowed" + ], + [ + [ + 73728, + 74606 + ], + "valid" + ], + [ + [ + 74607, + 74648 + ], + "valid" + ], + [ + [ + 74649, + 74649 + ], + "valid" + ], + [ + [ + 74650, + 74751 + ], + "disallowed" + ], + [ + [ + 74752, + 74850 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 74851, + 74862 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 74863, + 74863 + ], + "disallowed" + ], + [ + [ + 74864, + 74867 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 74868, + 74868 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 74869, + 74879 + ], + "disallowed" + ], + [ + [ + 74880, + 75075 + ], + "valid" + ], + [ + [ + 75076, + 77823 + ], + "disallowed" + ], + [ + [ + 77824, + 78894 + ], + "valid" + ], + [ + [ + 78895, + 82943 + ], + "disallowed" + ], + [ + [ + 82944, + 83526 + ], + "valid" + ], + [ + [ + 83527, + 92159 + ], + "disallowed" + ], + [ + [ + 92160, + 92728 + ], + "valid" + ], + [ + [ + 92729, + 92735 + ], + "disallowed" + ], + [ + [ + 92736, + 92766 + ], + "valid" + ], + [ + [ + 92767, + 92767 + ], + "disallowed" + ], + [ + [ + 92768, + 92777 + ], + "valid" + ], + [ + [ + 92778, + 92781 + ], + "disallowed" + ], + [ + [ + 92782, + 92783 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 92784, + 92879 + ], + "disallowed" + ], + [ + [ + 92880, + 92909 + ], + "valid" + ], + [ + [ + 92910, + 92911 + ], + "disallowed" + ], + [ + [ + 92912, + 92916 + ], + "valid" + ], + [ + [ + 92917, + 92917 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 92918, + 92927 + ], + "disallowed" + ], + [ + [ + 92928, + 92982 + ], + "valid" + ], + [ + [ + 92983, + 92991 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 92992, + 92995 + ], + "valid" + ], + [ + [ + 92996, + 92997 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 92998, + 93007 + ], + "disallowed" + ], + [ + [ + 93008, + 93017 + ], + "valid" + ], + [ + [ + 93018, + 93018 + ], + "disallowed" + ], + [ + [ + 93019, + 93025 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 93026, + 93026 + ], + "disallowed" + ], + [ + [ + 93027, + 93047 + ], + "valid" + ], + [ + [ + 93048, + 93052 + ], + "disallowed" + ], + [ + [ + 93053, + 93071 + ], + "valid" + ], + [ + [ + 93072, + 93951 + ], + "disallowed" + ], + [ + [ + 93952, + 94020 + ], + "valid" + ], + [ + [ + 94021, + 94031 + ], + "disallowed" + ], + [ + [ + 94032, + 94078 + ], + "valid" + ], + [ + [ + 94079, + 94094 + ], + "disallowed" + ], + [ + [ + 94095, + 94111 + ], + "valid" + ], + [ + [ + 94112, + 110591 + ], + "disallowed" + ], + [ + [ + 110592, + 110593 + ], + "valid" + ], + [ + [ + 110594, + 113663 + ], + "disallowed" + ], + [ + [ + 113664, + 113770 + ], + "valid" + ], + [ + [ + 113771, + 113775 + ], + "disallowed" + ], + [ + [ + 113776, + 113788 + ], + "valid" + ], + [ + [ + 113789, + 113791 + ], + "disallowed" + ], + [ + [ + 113792, + 113800 + ], + "valid" + ], + [ + [ + 113801, + 113807 + ], + "disallowed" + ], + [ + [ + 113808, + 113817 + ], + "valid" + ], + [ + [ + 113818, + 113819 + ], + "disallowed" + ], + [ + [ + 113820, + 113820 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 113821, + 113822 + ], + "valid" + ], + [ + [ + 113823, + 113823 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 113824, + 113827 + ], + "ignored" + ], + [ + [ + 113828, + 118783 + ], + "disallowed" + ], + [ + [ + 118784, + 119029 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 119030, + 119039 + ], + "disallowed" + ], + [ + [ + 119040, + 119078 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 119079, + 119080 + ], + "disallowed" + ], + [ + [ + 119081, + 119081 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 119082, + 119133 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 119134, + 119134 + ], + "mapped", + [ + 119127, + 119141 + ] + ], + [ + [ + 119135, + 119135 + ], + "mapped", + [ + 119128, + 119141 + ] + ], + [ + [ + 119136, + 119136 + ], + "mapped", + [ + 119128, + 119141, + 119150 + ] + ], + [ + [ + 119137, + 119137 + ], + "mapped", + [ + 119128, + 119141, + 119151 + ] + ], + [ + [ + 119138, + 119138 + ], + "mapped", + [ + 119128, + 119141, + 119152 + ] + ], + [ + [ + 119139, + 119139 + ], + "mapped", + [ + 119128, + 119141, + 119153 + ] + ], + [ + [ + 119140, + 119140 + ], + "mapped", + [ + 119128, + 119141, + 119154 + ] + ], + [ + [ + 119141, + 119154 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 119155, + 119162 + ], + "disallowed" + ], + [ + [ + 119163, + 119226 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 119227, + 119227 + ], + "mapped", + [ + 119225, + 119141 + ] + ], + [ + [ + 119228, + 119228 + ], + "mapped", + [ + 119226, + 119141 + ] + ], + [ + [ + 119229, + 119229 + ], + "mapped", + [ + 119225, + 119141, + 119150 + ] + ], + [ + [ + 119230, + 119230 + ], + "mapped", + [ + 119226, + 119141, + 119150 + ] + ], + [ + [ + 119231, + 119231 + ], + "mapped", + [ + 119225, + 119141, + 119151 + ] + ], + [ + [ + 119232, + 119232 + ], + "mapped", + [ + 119226, + 119141, + 119151 + ] + ], + [ + [ + 119233, + 119261 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 119262, + 119272 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 119273, + 119295 + ], + "disallowed" + ], + [ + [ + 119296, + 119365 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 119366, + 119551 + ], + "disallowed" + ], + [ + [ + 119552, + 119638 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 119639, + 119647 + ], + "disallowed" + ], + [ + [ + 119648, + 119665 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 119666, + 119807 + ], + "disallowed" + ], + [ + [ + 119808, + 119808 + ], + "mapped", + [ + 97 + ] + ], + [ + [ + 119809, + 119809 + ], + "mapped", + [ + 98 + ] + ], + [ + [ + 119810, + 119810 + ], + "mapped", + [ + 99 + ] + ], + [ + [ + 119811, + 119811 + ], + "mapped", + [ + 100 + ] + ], + [ + [ + 119812, + 119812 + ], + "mapped", + [ + 101 + ] + ], + [ + [ + 119813, + 119813 + ], + "mapped", + [ + 102 + ] + ], + [ + [ + 119814, + 119814 + ], + "mapped", + [ + 103 + ] + ], + [ + [ + 119815, + 119815 + ], + "mapped", + [ + 104 + ] + ], + [ + [ + 119816, + 119816 + ], + "mapped", + [ + 105 + ] + ], + [ + [ + 119817, + 119817 + ], + "mapped", + [ + 106 + ] + ], + [ + [ + 119818, + 119818 + ], + "mapped", + [ + 107 + ] + ], + [ + [ + 119819, + 119819 + ], + "mapped", + [ + 108 + ] + ], + [ + [ + 119820, + 119820 + ], + "mapped", + [ + 109 + ] + ], + [ + [ + 119821, + 119821 + ], + "mapped", + [ + 110 + ] + ], + [ + [ + 119822, + 119822 + ], + "mapped", + [ + 111 + ] + ], + [ + [ + 119823, + 119823 + ], + "mapped", + [ + 112 + ] + ], + [ + [ + 119824, + 119824 + ], + "mapped", + [ + 113 + ] + ], + [ + [ + 119825, + 119825 + ], + "mapped", + [ + 114 + ] + ], + [ + [ + 119826, + 119826 + ], + "mapped", + [ + 115 + ] + ], + [ + [ + 119827, + 119827 + ], + "mapped", + [ + 116 + ] + ], + [ + [ + 119828, + 119828 + ], + "mapped", + [ + 117 + ] + ], + [ + [ + 119829, + 119829 + ], + "mapped", + [ + 118 + ] + ], + [ + [ + 119830, + 119830 + ], + "mapped", + [ + 119 + ] + ], + [ + [ + 119831, + 119831 + ], + "mapped", + [ + 120 + ] + ], + [ + [ + 119832, + 119832 + ], + "mapped", + [ + 121 + ] + ], + [ + [ + 119833, + 119833 + ], + "mapped", + [ + 122 + ] + ], + [ + [ + 119834, + 119834 + ], + "mapped", + [ + 97 + ] + ], + [ + [ + 119835, + 119835 + ], + "mapped", + [ + 98 + ] + ], + [ + [ + 119836, + 119836 + ], + "mapped", + [ + 99 + ] + ], + [ + [ + 119837, + 119837 + ], + "mapped", + [ + 100 + ] + ], + [ + [ + 119838, + 119838 + ], + "mapped", + [ + 101 + ] + ], + [ + [ + 119839, + 119839 + ], + "mapped", + [ + 102 + ] + ], + [ + [ + 119840, + 119840 + ], + "mapped", + [ + 103 + ] + ], + [ + [ + 119841, + 119841 + ], + "mapped", + [ + 104 + ] + ], + [ + [ + 119842, + 119842 + ], + "mapped", + [ + 105 + ] + ], + [ + [ + 119843, + 119843 + ], + "mapped", + [ + 106 + ] + ], + [ + [ + 119844, + 119844 + ], + "mapped", + [ + 107 + ] + ], + [ + [ + 119845, + 119845 + ], + "mapped", + [ + 108 + ] + ], + [ + [ + 119846, + 119846 + ], + "mapped", + [ + 109 + ] + ], + [ + [ + 119847, + 119847 + ], + "mapped", + [ + 110 + ] + ], + [ + [ + 119848, + 119848 + ], + "mapped", + [ + 111 + ] + ], + [ + [ + 119849, + 119849 + ], + "mapped", + [ + 112 + ] + ], + [ + [ + 119850, + 119850 + ], + "mapped", + [ + 113 + ] + ], + [ + [ + 119851, + 119851 + ], + "mapped", + [ + 114 + ] + ], + [ + [ + 119852, + 119852 + ], + "mapped", + [ + 115 + ] + ], + [ + [ + 119853, + 119853 + ], + "mapped", + [ + 116 + ] + ], + [ + [ + 119854, + 119854 + ], + "mapped", + [ + 117 + ] + ], + [ + [ + 119855, + 119855 + ], + "mapped", + [ + 118 + ] + ], + [ + [ + 119856, + 119856 + ], + "mapped", + [ + 119 + ] + ], + [ + [ + 119857, + 119857 + ], + "mapped", + [ + 120 + ] + ], + [ + [ + 119858, + 119858 + ], + "mapped", + [ + 121 + ] + ], + [ + [ + 119859, + 119859 + ], + "mapped", + [ + 122 + ] + ], + [ + [ + 119860, + 119860 + ], + "mapped", + [ + 97 + ] + ], + [ + [ + 119861, + 119861 + ], + "mapped", + [ + 98 + ] + ], + [ + [ + 119862, + 119862 + ], + "mapped", + [ + 99 + ] + ], + [ + [ + 119863, + 119863 + ], + "mapped", + [ + 100 + ] + ], + [ + [ + 119864, + 119864 + ], + "mapped", + [ + 101 + ] + ], + [ + [ + 119865, + 119865 + ], + "mapped", + [ + 102 + ] + ], + [ + [ + 119866, + 119866 + ], + "mapped", + [ + 103 + ] + ], + [ + [ + 119867, + 119867 + ], + "mapped", + [ + 104 + ] + ], + [ + [ + 119868, + 119868 + ], + "mapped", + [ + 105 + ] + ], + [ + [ + 119869, + 119869 + ], + "mapped", + [ + 106 + ] + ], + [ + [ + 119870, + 119870 + ], + "mapped", + [ + 107 + ] + ], + [ + [ + 119871, + 119871 + ], + "mapped", + [ + 108 + ] + ], + [ + [ + 119872, + 119872 + ], + "mapped", + [ + 109 + ] + ], + [ + [ + 119873, + 119873 + ], + "mapped", + [ + 110 + ] + ], + [ + [ + 119874, + 119874 + ], + "mapped", + [ + 111 + ] + ], + [ + [ + 119875, + 119875 + ], + "mapped", + [ + 112 + ] + ], + [ + [ + 119876, + 119876 + ], + "mapped", + [ + 113 + ] + ], + [ + [ + 119877, + 119877 + ], + "mapped", + [ + 114 + ] + ], + [ + [ + 119878, + 119878 + ], + "mapped", + [ + 115 + ] + ], + [ + [ + 119879, + 119879 + ], + "mapped", + [ + 116 + ] + ], + [ + [ + 119880, + 119880 + ], + "mapped", + [ + 117 + ] + ], + [ + [ + 119881, + 119881 + ], + "mapped", + [ + 118 + ] + ], + [ + [ + 119882, + 119882 + ], + "mapped", + [ + 119 + ] + ], + [ + [ + 119883, + 119883 + ], + "mapped", + [ + 120 + ] + ], + [ + [ + 119884, + 119884 + ], + "mapped", + [ + 121 + ] + ], + [ + [ + 119885, + 119885 + ], + "mapped", + [ + 122 + ] + ], + [ + [ + 119886, + 119886 + ], + "mapped", + [ + 97 + ] + ], + [ + [ + 119887, + 119887 + ], + "mapped", + [ + 98 + ] + ], + [ + [ + 119888, + 119888 + ], + "mapped", + [ + 99 + ] + ], + [ + [ + 119889, + 119889 + ], + "mapped", + [ + 100 + ] + ], + [ + [ + 119890, + 119890 + ], + "mapped", + [ + 101 + ] + ], + [ + [ + 119891, + 119891 + ], + "mapped", + [ + 102 + ] + ], + [ + [ + 119892, + 119892 + ], + "mapped", + [ + 103 + ] + ], + [ + [ + 119893, + 119893 + ], + "disallowed" + ], + [ + [ + 119894, + 119894 + ], + "mapped", + [ + 105 + ] + ], + [ + [ + 119895, + 119895 + ], + "mapped", + [ + 106 + ] + ], + [ + [ + 119896, + 119896 + ], + "mapped", + [ + 107 + ] + ], + [ + [ + 119897, + 119897 + ], + "mapped", + [ + 108 + ] + ], + [ + [ + 119898, + 119898 + ], + "mapped", + [ + 109 + ] + ], + [ + [ + 119899, + 119899 + ], + "mapped", + [ + 110 + ] + ], + [ + [ + 119900, + 119900 + ], + "mapped", + [ + 111 + ] + ], + [ + [ + 119901, + 119901 + ], + "mapped", + [ + 112 + ] + ], + [ + [ + 119902, + 119902 + ], + "mapped", + [ + 113 + ] + ], + [ + [ + 119903, + 119903 + ], + "mapped", + [ + 114 + ] + ], + [ + [ + 119904, + 119904 + ], + "mapped", + [ + 115 + ] + ], + [ + [ + 119905, + 119905 + ], + "mapped", + [ + 116 + ] + ], + [ + [ + 119906, + 119906 + ], + "mapped", + [ + 117 + ] + ], + [ + [ + 119907, + 119907 + ], + "mapped", + [ + 118 + ] + ], + [ + [ + 119908, + 119908 + ], + "mapped", + [ + 119 + ] + ], + [ + [ + 119909, + 119909 + ], + "mapped", + [ + 120 + ] + ], + [ + [ + 119910, + 119910 + ], + "mapped", + [ + 121 + ] + ], + [ + [ + 119911, + 119911 + ], + "mapped", + [ + 122 + ] + ], + [ + [ + 119912, + 119912 + ], + "mapped", + [ + 97 + ] + ], + [ + [ + 119913, + 119913 + ], + "mapped", + [ + 98 + ] + ], + [ + [ + 119914, + 119914 + ], + "mapped", + [ + 99 + ] + ], + [ + [ + 119915, + 119915 + ], + "mapped", + [ + 100 + ] + ], + [ + [ + 119916, + 119916 + ], + "mapped", + [ + 101 + ] + ], + [ + [ + 119917, + 119917 + ], + "mapped", + [ + 102 + ] + ], + [ + [ + 119918, + 119918 + ], + "mapped", + [ + 103 + ] + ], + [ + [ + 119919, + 119919 + ], + "mapped", + [ + 104 + ] + ], + [ + [ + 119920, + 119920 + ], + "mapped", + [ + 105 + ] + ], + [ + [ + 119921, + 119921 + ], + "mapped", + [ + 106 + ] + ], + [ + [ + 119922, + 119922 + ], + "mapped", + [ + 107 + ] + ], + [ + [ + 119923, + 119923 + ], + "mapped", + [ + 108 + ] + ], + [ + [ + 119924, + 119924 + ], + "mapped", + [ + 109 + ] + ], + [ + [ + 119925, + 119925 + ], + "mapped", + [ + 110 + ] + ], + [ + [ + 119926, + 119926 + ], + "mapped", + [ + 111 + ] + ], + [ + [ + 119927, + 119927 + ], + "mapped", + [ + 112 + ] + ], + [ + [ + 119928, + 119928 + ], + "mapped", + [ + 113 + ] + ], + [ + [ + 119929, + 119929 + ], + "mapped", + [ + 114 + ] + ], + [ + [ + 119930, + 119930 + ], + "mapped", + [ + 115 + ] + ], + [ + [ + 119931, + 119931 + ], + "mapped", + [ + 116 + ] + ], + [ + [ + 119932, + 119932 + ], + "mapped", + [ + 117 + ] + ], + [ + [ + 119933, + 119933 + ], + "mapped", + [ + 118 + ] + ], + [ + [ + 119934, + 119934 + ], + "mapped", + [ + 119 + ] + ], + [ + [ + 119935, + 119935 + ], + "mapped", + [ + 120 + ] + ], + [ + [ + 119936, + 119936 + ], + "mapped", + [ + 121 + ] + ], + [ + [ + 119937, + 119937 + ], + "mapped", + [ + 122 + ] + ], + [ + [ + 119938, + 119938 + ], + "mapped", + [ + 97 + ] + ], + [ + [ + 119939, + 119939 + ], + "mapped", + [ + 98 + ] + ], + [ + [ + 119940, + 119940 + ], + "mapped", + [ + 99 + ] + ], + [ + [ + 119941, + 119941 + ], + "mapped", + [ + 100 + ] + ], + [ + [ + 119942, + 119942 + ], + "mapped", + [ + 101 + ] + ], + [ + [ + 119943, + 119943 + ], + "mapped", + [ + 102 + ] + ], + [ + [ + 119944, + 119944 + ], + "mapped", + [ + 103 + ] + ], + [ + [ + 119945, + 119945 + ], + "mapped", + [ + 104 + ] + ], + [ + [ + 119946, + 119946 + ], + "mapped", + [ + 105 + ] + ], + [ + [ + 119947, + 119947 + ], + "mapped", + [ + 106 + ] + ], + [ + [ + 119948, + 119948 + ], + "mapped", + [ + 107 + ] + ], + [ + [ + 119949, + 119949 + ], + "mapped", + [ + 108 + ] + ], + [ + [ + 119950, + 119950 + ], + "mapped", + [ + 109 + ] + ], + [ + [ + 119951, + 119951 + ], + "mapped", + [ + 110 + ] + ], + [ + [ + 119952, + 119952 + ], + "mapped", + [ + 111 + ] + ], + [ + [ + 119953, + 119953 + ], + "mapped", + [ + 112 + ] + ], + [ + [ + 119954, + 119954 + ], + "mapped", + [ + 113 + ] + ], + [ + [ + 119955, + 119955 + ], + "mapped", + [ + 114 + ] + ], + [ + [ + 119956, + 119956 + ], + "mapped", + [ + 115 + ] + ], + [ + [ + 119957, + 119957 + ], + "mapped", + [ + 116 + ] + ], + [ + [ + 119958, + 119958 + ], + "mapped", + [ + 117 + ] + ], + [ + [ + 119959, + 119959 + ], + "mapped", + [ + 118 + ] + ], + [ + [ + 119960, + 119960 + ], + "mapped", + [ + 119 + ] + ], + [ + [ + 119961, + 119961 + ], + "mapped", + [ + 120 + ] + ], + [ + [ + 119962, + 119962 + ], + "mapped", + [ + 121 + ] + ], + [ + [ + 119963, + 119963 + ], + "mapped", + [ + 122 + ] + ], + [ + [ + 119964, + 119964 + ], + "mapped", + [ + 97 + ] + ], + [ + [ + 119965, + 119965 + ], + "disallowed" + ], + [ + [ + 119966, + 119966 + ], + "mapped", + [ + 99 + ] + ], + [ + [ + 119967, + 119967 + ], + "mapped", + [ + 100 + ] + ], + [ + [ + 119968, + 119969 + ], + "disallowed" + ], + [ + [ + 119970, + 119970 + ], + "mapped", + [ + 103 + ] + ], + [ + [ + 119971, + 119972 + ], + "disallowed" + ], + [ + [ + 119973, + 119973 + ], + "mapped", + [ + 106 + ] + ], + [ + [ + 119974, + 119974 + ], + "mapped", + [ + 107 + ] + ], + [ + [ + 119975, + 119976 + ], + "disallowed" + ], + [ + [ + 119977, + 119977 + ], + "mapped", + [ + 110 + ] + ], + [ + [ + 119978, + 119978 + ], + "mapped", + [ + 111 + ] + ], + [ + [ + 119979, + 119979 + ], + "mapped", + [ + 112 + ] + ], + [ + [ + 119980, + 119980 + ], + "mapped", + [ + 113 + ] + ], + [ + [ + 119981, + 119981 + ], + "disallowed" + ], + [ + [ + 119982, + 119982 + ], + "mapped", + [ + 115 + ] + ], + [ + [ + 119983, + 119983 + ], + "mapped", + [ + 116 + ] + ], + [ + [ + 119984, + 119984 + ], + "mapped", + [ + 117 + ] + ], + [ + [ + 119985, + 119985 + ], + "mapped", + [ + 118 + ] + ], + [ + [ + 119986, + 119986 + ], + "mapped", + [ + 119 + ] + ], + [ + [ + 119987, + 119987 + ], + "mapped", + [ + 120 + ] + ], + [ + [ + 119988, + 119988 + ], + "mapped", + [ + 121 + ] + ], + [ + [ + 119989, + 119989 + ], + "mapped", + [ + 122 + ] + ], + [ + [ + 119990, + 119990 + ], + "mapped", + [ + 97 + ] + ], + [ + [ + 119991, + 119991 + ], + "mapped", + [ + 98 + ] + ], + [ + [ + 119992, + 119992 + ], + "mapped", + [ + 99 + ] + ], + [ + [ + 119993, + 119993 + ], + "mapped", + [ + 100 + ] + ], + [ + [ + 119994, + 119994 + ], + "disallowed" + ], + [ + [ + 119995, + 119995 + ], + "mapped", + [ + 102 + ] + ], + [ + [ + 119996, + 119996 + ], + "disallowed" + ], + [ + [ + 119997, + 119997 + ], + "mapped", + [ + 104 + ] + ], + [ + [ + 119998, + 119998 + ], + "mapped", + [ + 105 + ] + ], + [ + [ + 119999, + 119999 + ], + "mapped", + [ + 106 + ] + ], + [ + [ + 120000, + 120000 + ], + "mapped", + [ + 107 + ] + ], + [ + [ + 120001, + 120001 + ], + "mapped", + [ + 108 + ] + ], + [ + [ + 120002, + 120002 + ], + "mapped", + [ + 109 + ] + ], + [ + [ + 120003, + 120003 + ], + "mapped", + [ + 110 + ] + ], + [ + [ + 120004, + 120004 + ], + "disallowed" + ], + [ + [ + 120005, + 120005 + ], + "mapped", + [ + 112 + ] + ], + [ + [ + 120006, + 120006 + ], + "mapped", + [ + 113 + ] + ], + [ + [ + 120007, + 120007 + ], + "mapped", + [ + 114 + ] + ], + [ + [ + 120008, + 120008 + ], + "mapped", + [ + 115 + ] + ], + [ + [ + 120009, + 120009 + ], + "mapped", + [ + 116 + ] + ], + [ + [ + 120010, + 120010 + ], + "mapped", + [ + 117 + ] + ], + [ + [ + 120011, + 120011 + ], + "mapped", + [ + 118 + ] + ], + [ + [ + 120012, + 120012 + ], + "mapped", + [ + 119 + ] + ], + [ + [ + 120013, + 120013 + ], + "mapped", + [ + 120 + ] + ], + [ + [ + 120014, + 120014 + ], + "mapped", + [ + 121 + ] + ], + [ + [ + 120015, + 120015 + ], + "mapped", + [ + 122 + ] + ], + [ + [ + 120016, + 120016 + ], + "mapped", + [ + 97 + ] + ], + [ + [ + 120017, + 120017 + ], + "mapped", + [ + 98 + ] + ], + [ + [ + 120018, + 120018 + ], + "mapped", + [ + 99 + ] + ], + [ + [ + 120019, + 120019 + ], + "mapped", + [ + 100 + ] + ], + [ + [ + 120020, + 120020 + ], + "mapped", + [ + 101 + ] + ], + [ + [ + 120021, + 120021 + ], + "mapped", + [ + 102 + ] + ], + [ + [ + 120022, + 120022 + ], + "mapped", + [ + 103 + ] + ], + [ + [ + 120023, + 120023 + ], + "mapped", + [ + 104 + ] + ], + [ + [ + 120024, + 120024 + ], + "mapped", + [ + 105 + ] + ], + [ + [ + 120025, + 120025 + ], + "mapped", + [ + 106 + ] + ], + [ + [ + 120026, + 120026 + ], + "mapped", + [ + 107 + ] + ], + [ + [ + 120027, + 120027 + ], + "mapped", + [ + 108 + ] + ], + [ + [ + 120028, + 120028 + ], + "mapped", + [ + 109 + ] + ], + [ + [ + 120029, + 120029 + ], + "mapped", + [ + 110 + ] + ], + [ + [ + 120030, + 120030 + ], + "mapped", + [ + 111 + ] + ], + [ + [ + 120031, + 120031 + ], + "mapped", + [ + 112 + ] + ], + [ + [ + 120032, + 120032 + ], + "mapped", + [ + 113 + ] + ], + [ + [ + 120033, + 120033 + ], + "mapped", + [ + 114 + ] + ], + [ + [ + 120034, + 120034 + ], + "mapped", + [ + 115 + ] + ], + [ + [ + 120035, + 120035 + ], + "mapped", + [ + 116 + ] + ], + [ + [ + 120036, + 120036 + ], + "mapped", + [ + 117 + ] + ], + [ + [ + 120037, + 120037 + ], + "mapped", + [ + 118 + ] + ], + [ + [ + 120038, + 120038 + ], + "mapped", + [ + 119 + ] + ], + [ + [ + 120039, + 120039 + ], + "mapped", + [ + 120 + ] + ], + [ + [ + 120040, + 120040 + ], + "mapped", + [ + 121 + ] + ], + [ + [ + 120041, + 120041 + ], + "mapped", + [ + 122 + ] + ], + [ + [ + 120042, + 120042 + ], + "mapped", + [ + 97 + ] + ], + [ + [ + 120043, + 120043 + ], + "mapped", + [ + 98 + ] + ], + [ + [ + 120044, + 120044 + ], + "mapped", + [ + 99 + ] + ], + [ + [ + 120045, + 120045 + ], + "mapped", + [ + 100 + ] + ], + [ + [ + 120046, + 120046 + ], + "mapped", + [ + 101 + ] + ], + [ + [ + 120047, + 120047 + ], + "mapped", + [ + 102 + ] + ], + [ + [ + 120048, + 120048 + ], + "mapped", + [ + 103 + ] + ], + [ + [ + 120049, + 120049 + ], + "mapped", + [ + 104 + ] + ], + [ + [ + 120050, + 120050 + ], + "mapped", + [ + 105 + ] + ], + [ + [ + 120051, + 120051 + ], + "mapped", + [ + 106 + ] + ], + [ + [ + 120052, + 120052 + ], + "mapped", + [ + 107 + ] + ], + [ + [ + 120053, + 120053 + ], + "mapped", + [ + 108 + ] + ], + [ + [ + 120054, + 120054 + ], + "mapped", + [ + 109 + ] + ], + [ + [ + 120055, + 120055 + ], + "mapped", + [ + 110 + ] + ], + [ + [ + 120056, + 120056 + ], + "mapped", + [ + 111 + ] + ], + [ + [ + 120057, + 120057 + ], + "mapped", + [ + 112 + ] + ], + [ + [ + 120058, + 120058 + ], + "mapped", + [ + 113 + ] + ], + [ + [ + 120059, + 120059 + ], + "mapped", + [ + 114 + ] + ], + [ + [ + 120060, + 120060 + ], + "mapped", + [ + 115 + ] + ], + [ + [ + 120061, + 120061 + ], + "mapped", + [ + 116 + ] + ], + [ + [ + 120062, + 120062 + ], + "mapped", + [ + 117 + ] + ], + [ + [ + 120063, + 120063 + ], + "mapped", + [ + 118 + ] + ], + [ + [ + 120064, + 120064 + ], + "mapped", + [ + 119 + ] + ], + [ + [ + 120065, + 120065 + ], + "mapped", + [ + 120 + ] + ], + [ + [ + 120066, + 120066 + ], + "mapped", + [ + 121 + ] + ], + [ + [ + 120067, + 120067 + ], + "mapped", + [ + 122 + ] + ], + [ + [ + 120068, + 120068 + ], + "mapped", + [ + 97 + ] + ], + [ + [ + 120069, + 120069 + ], + "mapped", + [ + 98 + ] + ], + [ + [ + 120070, + 120070 + ], + "disallowed" + ], + [ + [ + 120071, + 120071 + ], + "mapped", + [ + 100 + ] + ], + [ + [ + 120072, + 120072 + ], + "mapped", + [ + 101 + ] + ], + [ + [ + 120073, + 120073 + ], + "mapped", + [ + 102 + ] + ], + [ + [ + 120074, + 120074 + ], + "mapped", + [ + 103 + ] + ], + [ + [ + 120075, + 120076 + ], + "disallowed" + ], + [ + [ + 120077, + 120077 + ], + "mapped", + [ + 106 + ] + ], + [ + [ + 120078, + 120078 + ], + "mapped", + [ + 107 + ] + ], + [ + [ + 120079, + 120079 + ], + "mapped", + [ + 108 + ] + ], + [ + [ + 120080, + 120080 + ], + "mapped", + [ + 109 + ] + ], + [ + [ + 120081, + 120081 + ], + "mapped", + [ + 110 + ] + ], + [ + [ + 120082, + 120082 + ], + "mapped", + [ + 111 + ] + ], + [ + [ + 120083, + 120083 + ], + "mapped", + [ + 112 + ] + ], + [ + [ + 120084, + 120084 + ], + "mapped", + [ + 113 + ] + ], + [ + [ + 120085, + 120085 + ], + "disallowed" + ], + [ + [ + 120086, + 120086 + ], + "mapped", + [ + 115 + ] + ], + [ + [ + 120087, + 120087 + ], + "mapped", + [ + 116 + ] + ], + [ + [ + 120088, + 120088 + ], + "mapped", + [ + 117 + ] + ], + [ + [ + 120089, + 120089 + ], + "mapped", + [ + 118 + ] + ], + [ + [ + 120090, + 120090 + ], + "mapped", + [ + 119 + ] + ], + [ + [ + 120091, + 120091 + ], + "mapped", + [ + 120 + ] + ], + [ + [ + 120092, + 120092 + ], + "mapped", + [ + 121 + ] + ], + [ + [ + 120093, + 120093 + ], + "disallowed" + ], + [ + [ + 120094, + 120094 + ], + "mapped", + [ + 97 + ] + ], + [ + [ + 120095, + 120095 + ], + "mapped", + [ + 98 + ] + ], + [ + [ + 120096, + 120096 + ], + "mapped", + [ + 99 + ] + ], + [ + [ + 120097, + 120097 + ], + "mapped", + [ + 100 + ] + ], + [ + [ + 120098, + 120098 + ], + "mapped", + [ + 101 + ] + ], + [ + [ + 120099, + 120099 + ], + "mapped", + [ + 102 + ] + ], + [ + [ + 120100, + 120100 + ], + "mapped", + [ + 103 + ] + ], + [ + [ + 120101, + 120101 + ], + "mapped", + [ + 104 + ] + ], + [ + [ + 120102, + 120102 + ], + "mapped", + [ + 105 + ] + ], + [ + [ + 120103, + 120103 + ], + "mapped", + [ + 106 + ] + ], + [ + [ + 120104, + 120104 + ], + "mapped", + [ + 107 + ] + ], + [ + [ + 120105, + 120105 + ], + "mapped", + [ + 108 + ] + ], + [ + [ + 120106, + 120106 + ], + "mapped", + [ + 109 + ] + ], + [ + [ + 120107, + 120107 + ], + "mapped", + [ + 110 + ] + ], + [ + [ + 120108, + 120108 + ], + "mapped", + [ + 111 + ] + ], + [ + [ + 120109, + 120109 + ], + "mapped", + [ + 112 + ] + ], + [ + [ + 120110, + 120110 + ], + "mapped", + [ + 113 + ] + ], + [ + [ + 120111, + 120111 + ], + "mapped", + [ + 114 + ] + ], + [ + [ + 120112, + 120112 + ], + "mapped", + [ + 115 + ] + ], + [ + [ + 120113, + 120113 + ], + "mapped", + [ + 116 + ] + ], + [ + [ + 120114, + 120114 + ], + "mapped", + [ + 117 + ] + ], + [ + [ + 120115, + 120115 + ], + "mapped", + [ + 118 + ] + ], + [ + [ + 120116, + 120116 + ], + "mapped", + [ + 119 + ] + ], + [ + [ + 120117, + 120117 + ], + "mapped", + [ + 120 + ] + ], + [ + [ + 120118, + 120118 + ], + "mapped", + [ + 121 + ] + ], + [ + [ + 120119, + 120119 + ], + "mapped", + [ + 122 + ] + ], + [ + [ + 120120, + 120120 + ], + "mapped", + [ + 97 + ] + ], + [ + [ + 120121, + 120121 + ], + "mapped", + [ + 98 + ] + ], + [ + [ + 120122, + 120122 + ], + "disallowed" + ], + [ + [ + 120123, + 120123 + ], + "mapped", + [ + 100 + ] + ], + [ + [ + 120124, + 120124 + ], + "mapped", + [ + 101 + ] + ], + [ + [ + 120125, + 120125 + ], + "mapped", + [ + 102 + ] + ], + [ + [ + 120126, + 120126 + ], + "mapped", + [ + 103 + ] + ], + [ + [ + 120127, + 120127 + ], + "disallowed" + ], + [ + [ + 120128, + 120128 + ], + "mapped", + [ + 105 + ] + ], + [ + [ + 120129, + 120129 + ], + "mapped", + [ + 106 + ] + ], + [ + [ + 120130, + 120130 + ], + "mapped", + [ + 107 + ] + ], + [ + [ + 120131, + 120131 + ], + "mapped", + [ + 108 + ] + ], + [ + [ + 120132, + 120132 + ], + "mapped", + [ + 109 + ] + ], + [ + [ + 120133, + 120133 + ], + "disallowed" + ], + [ + [ + 120134, + 120134 + ], + "mapped", + [ + 111 + ] + ], + [ + [ + 120135, + 120137 + ], + "disallowed" + ], + [ + [ + 120138, + 120138 + ], + "mapped", + [ + 115 + ] + ], + [ + [ + 120139, + 120139 + ], + "mapped", + [ + 116 + ] + ], + [ + [ + 120140, + 120140 + ], + "mapped", + [ + 117 + ] + ], + [ + [ + 120141, + 120141 + ], + "mapped", + [ + 118 + ] + ], + [ + [ + 120142, + 120142 + ], + "mapped", + [ + 119 + ] + ], + [ + [ + 120143, + 120143 + ], + "mapped", + [ + 120 + ] + ], + [ + [ + 120144, + 120144 + ], + "mapped", + [ + 121 + ] + ], + [ + [ + 120145, + 120145 + ], + "disallowed" + ], + [ + [ + 120146, + 120146 + ], + "mapped", + [ + 97 + ] + ], + [ + [ + 120147, + 120147 + ], + "mapped", + [ + 98 + ] + ], + [ + [ + 120148, + 120148 + ], + "mapped", + [ + 99 + ] + ], + [ + [ + 120149, + 120149 + ], + "mapped", + [ + 100 + ] + ], + [ + [ + 120150, + 120150 + ], + "mapped", + [ + 101 + ] + ], + [ + [ + 120151, + 120151 + ], + "mapped", + [ + 102 + ] + ], + [ + [ + 120152, + 120152 + ], + "mapped", + [ + 103 + ] + ], + [ + [ + 120153, + 120153 + ], + "mapped", + [ + 104 + ] + ], + [ + [ + 120154, + 120154 + ], + "mapped", + [ + 105 + ] + ], + [ + [ + 120155, + 120155 + ], + "mapped", + [ + 106 + ] + ], + [ + [ + 120156, + 120156 + ], + "mapped", + [ + 107 + ] + ], + [ + [ + 120157, + 120157 + ], + "mapped", + [ + 108 + ] + ], + [ + [ + 120158, + 120158 + ], + "mapped", + [ + 109 + ] + ], + [ + [ + 120159, + 120159 + ], + "mapped", + [ + 110 + ] + ], + [ + [ + 120160, + 120160 + ], + "mapped", + [ + 111 + ] + ], + [ + [ + 120161, + 120161 + ], + "mapped", + [ + 112 + ] + ], + [ + [ + 120162, + 120162 + ], + "mapped", + [ + 113 + ] + ], + [ + [ + 120163, + 120163 + ], + "mapped", + [ + 114 + ] + ], + [ + [ + 120164, + 120164 + ], + "mapped", + [ + 115 + ] + ], + [ + [ + 120165, + 120165 + ], + "mapped", + [ + 116 + ] + ], + [ + [ + 120166, + 120166 + ], + "mapped", + [ + 117 + ] + ], + [ + [ + 120167, + 120167 + ], + "mapped", + [ + 118 + ] + ], + [ + [ + 120168, + 120168 + ], + "mapped", + [ + 119 + ] + ], + [ + [ + 120169, + 120169 + ], + "mapped", + [ + 120 + ] + ], + [ + [ + 120170, + 120170 + ], + "mapped", + [ + 121 + ] + ], + [ + [ + 120171, + 120171 + ], + "mapped", + [ + 122 + ] + ], + [ + [ + 120172, + 120172 + ], + "mapped", + [ + 97 + ] + ], + [ + [ + 120173, + 120173 + ], + "mapped", + [ + 98 + ] + ], + [ + [ + 120174, + 120174 + ], + "mapped", + [ + 99 + ] + ], + [ + [ + 120175, + 120175 + ], + "mapped", + [ + 100 + ] + ], + [ + [ + 120176, + 120176 + ], + "mapped", + [ + 101 + ] + ], + [ + [ + 120177, + 120177 + ], + "mapped", + [ + 102 + ] + ], + [ + [ + 120178, + 120178 + ], + "mapped", + [ + 103 + ] + ], + [ + [ + 120179, + 120179 + ], + "mapped", + [ + 104 + ] + ], + [ + [ + 120180, + 120180 + ], + "mapped", + [ + 105 + ] + ], + [ + [ + 120181, + 120181 + ], + "mapped", + [ + 106 + ] + ], + [ + [ + 120182, + 120182 + ], + "mapped", + [ + 107 + ] + ], + [ + [ + 120183, + 120183 + ], + "mapped", + [ + 108 + ] + ], + [ + [ + 120184, + 120184 + ], + "mapped", + [ + 109 + ] + ], + [ + [ + 120185, + 120185 + ], + "mapped", + [ + 110 + ] + ], + [ + [ + 120186, + 120186 + ], + "mapped", + [ + 111 + ] + ], + [ + [ + 120187, + 120187 + ], + "mapped", + [ + 112 + ] + ], + [ + [ + 120188, + 120188 + ], + "mapped", + [ + 113 + ] + ], + [ + [ + 120189, + 120189 + ], + "mapped", + [ + 114 + ] + ], + [ + [ + 120190, + 120190 + ], + "mapped", + [ + 115 + ] + ], + [ + [ + 120191, + 120191 + ], + "mapped", + [ + 116 + ] + ], + [ + [ + 120192, + 120192 + ], + "mapped", + [ + 117 + ] + ], + [ + [ + 120193, + 120193 + ], + "mapped", + [ + 118 + ] + ], + [ + [ + 120194, + 120194 + ], + "mapped", + [ + 119 + ] + ], + [ + [ + 120195, + 120195 + ], + "mapped", + [ + 120 + ] + ], + [ + [ + 120196, + 120196 + ], + "mapped", + [ + 121 + ] + ], + [ + [ + 120197, + 120197 + ], + "mapped", + [ + 122 + ] + ], + [ + [ + 120198, + 120198 + ], + "mapped", + [ + 97 + ] + ], + [ + [ + 120199, + 120199 + ], + "mapped", + [ + 98 + ] + ], + [ + [ + 120200, + 120200 + ], + "mapped", + [ + 99 + ] + ], + [ + [ + 120201, + 120201 + ], + "mapped", + [ + 100 + ] + ], + [ + [ + 120202, + 120202 + ], + "mapped", + [ + 101 + ] + ], + [ + [ + 120203, + 120203 + ], + "mapped", + [ + 102 + ] + ], + [ + [ + 120204, + 120204 + ], + "mapped", + [ + 103 + ] + ], + [ + [ + 120205, + 120205 + ], + "mapped", + [ + 104 + ] + ], + [ + [ + 120206, + 120206 + ], + "mapped", + [ + 105 + ] + ], + [ + [ + 120207, + 120207 + ], + "mapped", + [ + 106 + ] + ], + [ + [ + 120208, + 120208 + ], + "mapped", + [ + 107 + ] + ], + [ + [ + 120209, + 120209 + ], + "mapped", + [ + 108 + ] + ], + [ + [ + 120210, + 120210 + ], + "mapped", + [ + 109 + ] + ], + [ + [ + 120211, + 120211 + ], + "mapped", + [ + 110 + ] + ], + [ + [ + 120212, + 120212 + ], + "mapped", + [ + 111 + ] + ], + [ + [ + 120213, + 120213 + ], + "mapped", + [ + 112 + ] + ], + [ + [ + 120214, + 120214 + ], + "mapped", + [ + 113 + ] + ], + [ + [ + 120215, + 120215 + ], + "mapped", + [ + 114 + ] + ], + [ + [ + 120216, + 120216 + ], + "mapped", + [ + 115 + ] + ], + [ + [ + 120217, + 120217 + ], + "mapped", + [ + 116 + ] + ], + [ + [ + 120218, + 120218 + ], + "mapped", + [ + 117 + ] + ], + [ + [ + 120219, + 120219 + ], + "mapped", + [ + 118 + ] + ], + [ + [ + 120220, + 120220 + ], + "mapped", + [ + 119 + ] + ], + [ + [ + 120221, + 120221 + ], + "mapped", + [ + 120 + ] + ], + [ + [ + 120222, + 120222 + ], + "mapped", + [ + 121 + ] + ], + [ + [ + 120223, + 120223 + ], + "mapped", + [ + 122 + ] + ], + [ + [ + 120224, + 120224 + ], + "mapped", + [ + 97 + ] + ], + [ + [ + 120225, + 120225 + ], + "mapped", + [ + 98 + ] + ], + [ + [ + 120226, + 120226 + ], + "mapped", + [ + 99 + ] + ], + [ + [ + 120227, + 120227 + ], + "mapped", + [ + 100 + ] + ], + [ + [ + 120228, + 120228 + ], + "mapped", + [ + 101 + ] + ], + [ + [ + 120229, + 120229 + ], + "mapped", + [ + 102 + ] + ], + [ + [ + 120230, + 120230 + ], + "mapped", + [ + 103 + ] + ], + [ + [ + 120231, + 120231 + ], + "mapped", + [ + 104 + ] + ], + [ + [ + 120232, + 120232 + ], + "mapped", + [ + 105 + ] + ], + [ + [ + 120233, + 120233 + ], + "mapped", + [ + 106 + ] + ], + [ + [ + 120234, + 120234 + ], + "mapped", + [ + 107 + ] + ], + [ + [ + 120235, + 120235 + ], + "mapped", + [ + 108 + ] + ], + [ + [ + 120236, + 120236 + ], + "mapped", + [ + 109 + ] + ], + [ + [ + 120237, + 120237 + ], + "mapped", + [ + 110 + ] + ], + [ + [ + 120238, + 120238 + ], + "mapped", + [ + 111 + ] + ], + [ + [ + 120239, + 120239 + ], + "mapped", + [ + 112 + ] + ], + [ + [ + 120240, + 120240 + ], + "mapped", + [ + 113 + ] + ], + [ + [ + 120241, + 120241 + ], + "mapped", + [ + 114 + ] + ], + [ + [ + 120242, + 120242 + ], + "mapped", + [ + 115 + ] + ], + [ + [ + 120243, + 120243 + ], + "mapped", + [ + 116 + ] + ], + [ + [ + 120244, + 120244 + ], + "mapped", + [ + 117 + ] + ], + [ + [ + 120245, + 120245 + ], + "mapped", + [ + 118 + ] + ], + [ + [ + 120246, + 120246 + ], + "mapped", + [ + 119 + ] + ], + [ + [ + 120247, + 120247 + ], + "mapped", + [ + 120 + ] + ], + [ + [ + 120248, + 120248 + ], + "mapped", + [ + 121 + ] + ], + [ + [ + 120249, + 120249 + ], + "mapped", + [ + 122 + ] + ], + [ + [ + 120250, + 120250 + ], + "mapped", + [ + 97 + ] + ], + [ + [ + 120251, + 120251 + ], + "mapped", + [ + 98 + ] + ], + [ + [ + 120252, + 120252 + ], + "mapped", + [ + 99 + ] + ], + [ + [ + 120253, + 120253 + ], + "mapped", + [ + 100 + ] + ], + [ + [ + 120254, + 120254 + ], + "mapped", + [ + 101 + ] + ], + [ + [ + 120255, + 120255 + ], + "mapped", + [ + 102 + ] + ], + [ + [ + 120256, + 120256 + ], + "mapped", + [ + 103 + ] + ], + [ + [ + 120257, + 120257 + ], + "mapped", + [ + 104 + ] + ], + [ + [ + 120258, + 120258 + ], + "mapped", + [ + 105 + ] + ], + [ + [ + 120259, + 120259 + ], + "mapped", + [ + 106 + ] + ], + [ + [ + 120260, + 120260 + ], + "mapped", + [ + 107 + ] + ], + [ + [ + 120261, + 120261 + ], + "mapped", + [ + 108 + ] + ], + [ + [ + 120262, + 120262 + ], + "mapped", + [ + 109 + ] + ], + [ + [ + 120263, + 120263 + ], + "mapped", + [ + 110 + ] + ], + [ + [ + 120264, + 120264 + ], + "mapped", + [ + 111 + ] + ], + [ + [ + 120265, + 120265 + ], + "mapped", + [ + 112 + ] + ], + [ + [ + 120266, + 120266 + ], + "mapped", + [ + 113 + ] + ], + [ + [ + 120267, + 120267 + ], + "mapped", + [ + 114 + ] + ], + [ + [ + 120268, + 120268 + ], + "mapped", + [ + 115 + ] + ], + [ + [ + 120269, + 120269 + ], + "mapped", + [ + 116 + ] + ], + [ + [ + 120270, + 120270 + ], + "mapped", + [ + 117 + ] + ], + [ + [ + 120271, + 120271 + ], + "mapped", + [ + 118 + ] + ], + [ + [ + 120272, + 120272 + ], + "mapped", + [ + 119 + ] + ], + [ + [ + 120273, + 120273 + ], + "mapped", + [ + 120 + ] + ], + [ + [ + 120274, + 120274 + ], + "mapped", + [ + 121 + ] + ], + [ + [ + 120275, + 120275 + ], + "mapped", + [ + 122 + ] + ], + [ + [ + 120276, + 120276 + ], + "mapped", + [ + 97 + ] + ], + [ + [ + 120277, + 120277 + ], + "mapped", + [ + 98 + ] + ], + [ + [ + 120278, + 120278 + ], + "mapped", + [ + 99 + ] + ], + [ + [ + 120279, + 120279 + ], + "mapped", + [ + 100 + ] + ], + [ + [ + 120280, + 120280 + ], + "mapped", + [ + 101 + ] + ], + [ + [ + 120281, + 120281 + ], + "mapped", + [ + 102 + ] + ], + [ + [ + 120282, + 120282 + ], + "mapped", + [ + 103 + ] + ], + [ + [ + 120283, + 120283 + ], + "mapped", + [ + 104 + ] + ], + [ + [ + 120284, + 120284 + ], + "mapped", + [ + 105 + ] + ], + [ + [ + 120285, + 120285 + ], + "mapped", + [ + 106 + ] + ], + [ + [ + 120286, + 120286 + ], + "mapped", + [ + 107 + ] + ], + [ + [ + 120287, + 120287 + ], + "mapped", + [ + 108 + ] + ], + [ + [ + 120288, + 120288 + ], + "mapped", + [ + 109 + ] + ], + [ + [ + 120289, + 120289 + ], + "mapped", + [ + 110 + ] + ], + [ + [ + 120290, + 120290 + ], + "mapped", + [ + 111 + ] + ], + [ + [ + 120291, + 120291 + ], + "mapped", + [ + 112 + ] + ], + [ + [ + 120292, + 120292 + ], + "mapped", + [ + 113 + ] + ], + [ + [ + 120293, + 120293 + ], + "mapped", + [ + 114 + ] + ], + [ + [ + 120294, + 120294 + ], + "mapped", + [ + 115 + ] + ], + [ + [ + 120295, + 120295 + ], + "mapped", + [ + 116 + ] + ], + [ + [ + 120296, + 120296 + ], + "mapped", + [ + 117 + ] + ], + [ + [ + 120297, + 120297 + ], + "mapped", + [ + 118 + ] + ], + [ + [ + 120298, + 120298 + ], + "mapped", + [ + 119 + ] + ], + [ + [ + 120299, + 120299 + ], + "mapped", + [ + 120 + ] + ], + [ + [ + 120300, + 120300 + ], + "mapped", + [ + 121 + ] + ], + [ + [ + 120301, + 120301 + ], + "mapped", + [ + 122 + ] + ], + [ + [ + 120302, + 120302 + ], + "mapped", + [ + 97 + ] + ], + [ + [ + 120303, + 120303 + ], + "mapped", + [ + 98 + ] + ], + [ + [ + 120304, + 120304 + ], + "mapped", + [ + 99 + ] + ], + [ + [ + 120305, + 120305 + ], + "mapped", + [ + 100 + ] + ], + [ + [ + 120306, + 120306 + ], + "mapped", + [ + 101 + ] + ], + [ + [ + 120307, + 120307 + ], + "mapped", + [ + 102 + ] + ], + [ + [ + 120308, + 120308 + ], + "mapped", + [ + 103 + ] + ], + [ + [ + 120309, + 120309 + ], + "mapped", + [ + 104 + ] + ], + [ + [ + 120310, + 120310 + ], + "mapped", + [ + 105 + ] + ], + [ + [ + 120311, + 120311 + ], + "mapped", + [ + 106 + ] + ], + [ + [ + 120312, + 120312 + ], + "mapped", + [ + 107 + ] + ], + [ + [ + 120313, + 120313 + ], + "mapped", + [ + 108 + ] + ], + [ + [ + 120314, + 120314 + ], + "mapped", + [ + 109 + ] + ], + [ + [ + 120315, + 120315 + ], + "mapped", + [ + 110 + ] + ], + [ + [ + 120316, + 120316 + ], + "mapped", + [ + 111 + ] + ], + [ + [ + 120317, + 120317 + ], + "mapped", + [ + 112 + ] + ], + [ + [ + 120318, + 120318 + ], + "mapped", + [ + 113 + ] + ], + [ + [ + 120319, + 120319 + ], + "mapped", + [ + 114 + ] + ], + [ + [ + 120320, + 120320 + ], + "mapped", + [ + 115 + ] + ], + [ + [ + 120321, + 120321 + ], + "mapped", + [ + 116 + ] + ], + [ + [ + 120322, + 120322 + ], + "mapped", + [ + 117 + ] + ], + [ + [ + 120323, + 120323 + ], + "mapped", + [ + 118 + ] + ], + [ + [ + 120324, + 120324 + ], + "mapped", + [ + 119 + ] + ], + [ + [ + 120325, + 120325 + ], + "mapped", + [ + 120 + ] + ], + [ + [ + 120326, + 120326 + ], + "mapped", + [ + 121 + ] + ], + [ + [ + 120327, + 120327 + ], + "mapped", + [ + 122 + ] + ], + [ + [ + 120328, + 120328 + ], + "mapped", + [ + 97 + ] + ], + [ + [ + 120329, + 120329 + ], + "mapped", + [ + 98 + ] + ], + [ + [ + 120330, + 120330 + ], + "mapped", + [ + 99 + ] + ], + [ + [ + 120331, + 120331 + ], + "mapped", + [ + 100 + ] + ], + [ + [ + 120332, + 120332 + ], + "mapped", + [ + 101 + ] + ], + [ + [ + 120333, + 120333 + ], + "mapped", + [ + 102 + ] + ], + [ + [ + 120334, + 120334 + ], + "mapped", + [ + 103 + ] + ], + [ + [ + 120335, + 120335 + ], + "mapped", + [ + 104 + ] + ], + [ + [ + 120336, + 120336 + ], + "mapped", + [ + 105 + ] + ], + [ + [ + 120337, + 120337 + ], + "mapped", + [ + 106 + ] + ], + [ + [ + 120338, + 120338 + ], + "mapped", + [ + 107 + ] + ], + [ + [ + 120339, + 120339 + ], + "mapped", + [ + 108 + ] + ], + [ + [ + 120340, + 120340 + ], + "mapped", + [ + 109 + ] + ], + [ + [ + 120341, + 120341 + ], + "mapped", + [ + 110 + ] + ], + [ + [ + 120342, + 120342 + ], + "mapped", + [ + 111 + ] + ], + [ + [ + 120343, + 120343 + ], + "mapped", + [ + 112 + ] + ], + [ + [ + 120344, + 120344 + ], + "mapped", + [ + 113 + ] + ], + [ + [ + 120345, + 120345 + ], + "mapped", + [ + 114 + ] + ], + [ + [ + 120346, + 120346 + ], + "mapped", + [ + 115 + ] + ], + [ + [ + 120347, + 120347 + ], + "mapped", + [ + 116 + ] + ], + [ + [ + 120348, + 120348 + ], + "mapped", + [ + 117 + ] + ], + [ + [ + 120349, + 120349 + ], + "mapped", + [ + 118 + ] + ], + [ + [ + 120350, + 120350 + ], + "mapped", + [ + 119 + ] + ], + [ + [ + 120351, + 120351 + ], + "mapped", + [ + 120 + ] + ], + [ + [ + 120352, + 120352 + ], + "mapped", + [ + 121 + ] + ], + [ + [ + 120353, + 120353 + ], + "mapped", + [ + 122 + ] + ], + [ + [ + 120354, + 120354 + ], + "mapped", + [ + 97 + ] + ], + [ + [ + 120355, + 120355 + ], + "mapped", + [ + 98 + ] + ], + [ + [ + 120356, + 120356 + ], + "mapped", + [ + 99 + ] + ], + [ + [ + 120357, + 120357 + ], + "mapped", + [ + 100 + ] + ], + [ + [ + 120358, + 120358 + ], + "mapped", + [ + 101 + ] + ], + [ + [ + 120359, + 120359 + ], + "mapped", + [ + 102 + ] + ], + [ + [ + 120360, + 120360 + ], + "mapped", + [ + 103 + ] + ], + [ + [ + 120361, + 120361 + ], + "mapped", + [ + 104 + ] + ], + [ + [ + 120362, + 120362 + ], + "mapped", + [ + 105 + ] + ], + [ + [ + 120363, + 120363 + ], + "mapped", + [ + 106 + ] + ], + [ + [ + 120364, + 120364 + ], + "mapped", + [ + 107 + ] + ], + [ + [ + 120365, + 120365 + ], + "mapped", + [ + 108 + ] + ], + [ + [ + 120366, + 120366 + ], + "mapped", + [ + 109 + ] + ], + [ + [ + 120367, + 120367 + ], + "mapped", + [ + 110 + ] + ], + [ + [ + 120368, + 120368 + ], + "mapped", + [ + 111 + ] + ], + [ + [ + 120369, + 120369 + ], + "mapped", + [ + 112 + ] + ], + [ + [ + 120370, + 120370 + ], + "mapped", + [ + 113 + ] + ], + [ + [ + 120371, + 120371 + ], + "mapped", + [ + 114 + ] + ], + [ + [ + 120372, + 120372 + ], + "mapped", + [ + 115 + ] + ], + [ + [ + 120373, + 120373 + ], + "mapped", + [ + 116 + ] + ], + [ + [ + 120374, + 120374 + ], + "mapped", + [ + 117 + ] + ], + [ + [ + 120375, + 120375 + ], + "mapped", + [ + 118 + ] + ], + [ + [ + 120376, + 120376 + ], + "mapped", + [ + 119 + ] + ], + [ + [ + 120377, + 120377 + ], + "mapped", + [ + 120 + ] + ], + [ + [ + 120378, + 120378 + ], + "mapped", + [ + 121 + ] + ], + [ + [ + 120379, + 120379 + ], + "mapped", + [ + 122 + ] + ], + [ + [ + 120380, + 120380 + ], + "mapped", + [ + 97 + ] + ], + [ + [ + 120381, + 120381 + ], + "mapped", + [ + 98 + ] + ], + [ + [ + 120382, + 120382 + ], + "mapped", + [ + 99 + ] + ], + [ + [ + 120383, + 120383 + ], + "mapped", + [ + 100 + ] + ], + [ + [ + 120384, + 120384 + ], + "mapped", + [ + 101 + ] + ], + [ + [ + 120385, + 120385 + ], + "mapped", + [ + 102 + ] + ], + [ + [ + 120386, + 120386 + ], + "mapped", + [ + 103 + ] + ], + [ + [ + 120387, + 120387 + ], + "mapped", + [ + 104 + ] + ], + [ + [ + 120388, + 120388 + ], + "mapped", + [ + 105 + ] + ], + [ + [ + 120389, + 120389 + ], + "mapped", + [ + 106 + ] + ], + [ + [ + 120390, + 120390 + ], + "mapped", + [ + 107 + ] + ], + [ + [ + 120391, + 120391 + ], + "mapped", + [ + 108 + ] + ], + [ + [ + 120392, + 120392 + ], + "mapped", + [ + 109 + ] + ], + [ + [ + 120393, + 120393 + ], + "mapped", + [ + 110 + ] + ], + [ + [ + 120394, + 120394 + ], + "mapped", + [ + 111 + ] + ], + [ + [ + 120395, + 120395 + ], + "mapped", + [ + 112 + ] + ], + [ + [ + 120396, + 120396 + ], + "mapped", + [ + 113 + ] + ], + [ + [ + 120397, + 120397 + ], + "mapped", + [ + 114 + ] + ], + [ + [ + 120398, + 120398 + ], + "mapped", + [ + 115 + ] + ], + [ + [ + 120399, + 120399 + ], + "mapped", + [ + 116 + ] + ], + [ + [ + 120400, + 120400 + ], + "mapped", + [ + 117 + ] + ], + [ + [ + 120401, + 120401 + ], + "mapped", + [ + 118 + ] + ], + [ + [ + 120402, + 120402 + ], + "mapped", + [ + 119 + ] + ], + [ + [ + 120403, + 120403 + ], + "mapped", + [ + 120 + ] + ], + [ + [ + 120404, + 120404 + ], + "mapped", + [ + 121 + ] + ], + [ + [ + 120405, + 120405 + ], + "mapped", + [ + 122 + ] + ], + [ + [ + 120406, + 120406 + ], + "mapped", + [ + 97 + ] + ], + [ + [ + 120407, + 120407 + ], + "mapped", + [ + 98 + ] + ], + [ + [ + 120408, + 120408 + ], + "mapped", + [ + 99 + ] + ], + [ + [ + 120409, + 120409 + ], + "mapped", + [ + 100 + ] + ], + [ + [ + 120410, + 120410 + ], + "mapped", + [ + 101 + ] + ], + [ + [ + 120411, + 120411 + ], + "mapped", + [ + 102 + ] + ], + [ + [ + 120412, + 120412 + ], + "mapped", + [ + 103 + ] + ], + [ + [ + 120413, + 120413 + ], + "mapped", + [ + 104 + ] + ], + [ + [ + 120414, + 120414 + ], + "mapped", + [ + 105 + ] + ], + [ + [ + 120415, + 120415 + ], + "mapped", + [ + 106 + ] + ], + [ + [ + 120416, + 120416 + ], + "mapped", + [ + 107 + ] + ], + [ + [ + 120417, + 120417 + ], + "mapped", + [ + 108 + ] + ], + [ + [ + 120418, + 120418 + ], + "mapped", + [ + 109 + ] + ], + [ + [ + 120419, + 120419 + ], + "mapped", + [ + 110 + ] + ], + [ + [ + 120420, + 120420 + ], + "mapped", + [ + 111 + ] + ], + [ + [ + 120421, + 120421 + ], + "mapped", + [ + 112 + ] + ], + [ + [ + 120422, + 120422 + ], + "mapped", + [ + 113 + ] + ], + [ + [ + 120423, + 120423 + ], + "mapped", + [ + 114 + ] + ], + [ + [ + 120424, + 120424 + ], + "mapped", + [ + 115 + ] + ], + [ + [ + 120425, + 120425 + ], + "mapped", + [ + 116 + ] + ], + [ + [ + 120426, + 120426 + ], + "mapped", + [ + 117 + ] + ], + [ + [ + 120427, + 120427 + ], + "mapped", + [ + 118 + ] + ], + [ + [ + 120428, + 120428 + ], + "mapped", + [ + 119 + ] + ], + [ + [ + 120429, + 120429 + ], + "mapped", + [ + 120 + ] + ], + [ + [ + 120430, + 120430 + ], + "mapped", + [ + 121 + ] + ], + [ + [ + 120431, + 120431 + ], + "mapped", + [ + 122 + ] + ], + [ + [ + 120432, + 120432 + ], + "mapped", + [ + 97 + ] + ], + [ + [ + 120433, + 120433 + ], + "mapped", + [ + 98 + ] + ], + [ + [ + 120434, + 120434 + ], + "mapped", + [ + 99 + ] + ], + [ + [ + 120435, + 120435 + ], + "mapped", + [ + 100 + ] + ], + [ + [ + 120436, + 120436 + ], + "mapped", + [ + 101 + ] + ], + [ + [ + 120437, + 120437 + ], + "mapped", + [ + 102 + ] + ], + [ + [ + 120438, + 120438 + ], + "mapped", + [ + 103 + ] + ], + [ + [ + 120439, + 120439 + ], + "mapped", + [ + 104 + ] + ], + [ + [ + 120440, + 120440 + ], + "mapped", + [ + 105 + ] + ], + [ + [ + 120441, + 120441 + ], + "mapped", + [ + 106 + ] + ], + [ + [ + 120442, + 120442 + ], + "mapped", + [ + 107 + ] + ], + [ + [ + 120443, + 120443 + ], + "mapped", + [ + 108 + ] + ], + [ + [ + 120444, + 120444 + ], + "mapped", + [ + 109 + ] + ], + [ + [ + 120445, + 120445 + ], + "mapped", + [ + 110 + ] + ], + [ + [ + 120446, + 120446 + ], + "mapped", + [ + 111 + ] + ], + [ + [ + 120447, + 120447 + ], + "mapped", + [ + 112 + ] + ], + [ + [ + 120448, + 120448 + ], + "mapped", + [ + 113 + ] + ], + [ + [ + 120449, + 120449 + ], + "mapped", + [ + 114 + ] + ], + [ + [ + 120450, + 120450 + ], + "mapped", + [ + 115 + ] + ], + [ + [ + 120451, + 120451 + ], + "mapped", + [ + 116 + ] + ], + [ + [ + 120452, + 120452 + ], + "mapped", + [ + 117 + ] + ], + [ + [ + 120453, + 120453 + ], + "mapped", + [ + 118 + ] + ], + [ + [ + 120454, + 120454 + ], + "mapped", + [ + 119 + ] + ], + [ + [ + 120455, + 120455 + ], + "mapped", + [ + 120 + ] + ], + [ + [ + 120456, + 120456 + ], + "mapped", + [ + 121 + ] + ], + [ + [ + 120457, + 120457 + ], + "mapped", + [ + 122 + ] + ], + [ + [ + 120458, + 120458 + ], + "mapped", + [ + 97 + ] + ], + [ + [ + 120459, + 120459 + ], + "mapped", + [ + 98 + ] + ], + [ + [ + 120460, + 120460 + ], + "mapped", + [ + 99 + ] + ], + [ + [ + 120461, + 120461 + ], + "mapped", + [ + 100 + ] + ], + [ + [ + 120462, + 120462 + ], + "mapped", + [ + 101 + ] + ], + [ + [ + 120463, + 120463 + ], + "mapped", + [ + 102 + ] + ], + [ + [ + 120464, + 120464 + ], + "mapped", + [ + 103 + ] + ], + [ + [ + 120465, + 120465 + ], + "mapped", + [ + 104 + ] + ], + [ + [ + 120466, + 120466 + ], + "mapped", + [ + 105 + ] + ], + [ + [ + 120467, + 120467 + ], + "mapped", + [ + 106 + ] + ], + [ + [ + 120468, + 120468 + ], + "mapped", + [ + 107 + ] + ], + [ + [ + 120469, + 120469 + ], + "mapped", + [ + 108 + ] + ], + [ + [ + 120470, + 120470 + ], + "mapped", + [ + 109 + ] + ], + [ + [ + 120471, + 120471 + ], + "mapped", + [ + 110 + ] + ], + [ + [ + 120472, + 120472 + ], + "mapped", + [ + 111 + ] + ], + [ + [ + 120473, + 120473 + ], + "mapped", + [ + 112 + ] + ], + [ + [ + 120474, + 120474 + ], + "mapped", + [ + 113 + ] + ], + [ + [ + 120475, + 120475 + ], + "mapped", + [ + 114 + ] + ], + [ + [ + 120476, + 120476 + ], + "mapped", + [ + 115 + ] + ], + [ + [ + 120477, + 120477 + ], + "mapped", + [ + 116 + ] + ], + [ + [ + 120478, + 120478 + ], + "mapped", + [ + 117 + ] + ], + [ + [ + 120479, + 120479 + ], + "mapped", + [ + 118 + ] + ], + [ + [ + 120480, + 120480 + ], + "mapped", + [ + 119 + ] + ], + [ + [ + 120481, + 120481 + ], + "mapped", + [ + 120 + ] + ], + [ + [ + 120482, + 120482 + ], + "mapped", + [ + 121 + ] + ], + [ + [ + 120483, + 120483 + ], + "mapped", + [ + 122 + ] + ], + [ + [ + 120484, + 120484 + ], + "mapped", + [ + 305 + ] + ], + [ + [ + 120485, + 120485 + ], + "mapped", + [ + 567 + ] + ], + [ + [ + 120486, + 120487 + ], + "disallowed" + ], + [ + [ + 120488, + 120488 + ], + "mapped", + [ + 945 + ] + ], + [ + [ + 120489, + 120489 + ], + "mapped", + [ + 946 + ] + ], + [ + [ + 120490, + 120490 + ], + "mapped", + [ + 947 + ] + ], + [ + [ + 120491, + 120491 + ], + "mapped", + [ + 948 + ] + ], + [ + [ + 120492, + 120492 + ], + "mapped", + [ + 949 + ] + ], + [ + [ + 120493, + 120493 + ], + "mapped", + [ + 950 + ] + ], + [ + [ + 120494, + 120494 + ], + "mapped", + [ + 951 + ] + ], + [ + [ + 120495, + 120495 + ], + "mapped", + [ + 952 + ] + ], + [ + [ + 120496, + 120496 + ], + "mapped", + [ + 953 + ] + ], + [ + [ + 120497, + 120497 + ], + "mapped", + [ + 954 + ] + ], + [ + [ + 120498, + 120498 + ], + "mapped", + [ + 955 + ] + ], + [ + [ + 120499, + 120499 + ], + "mapped", + [ + 956 + ] + ], + [ + [ + 120500, + 120500 + ], + "mapped", + [ + 957 + ] + ], + [ + [ + 120501, + 120501 + ], + "mapped", + [ + 958 + ] + ], + [ + [ + 120502, + 120502 + ], + "mapped", + [ + 959 + ] + ], + [ + [ + 120503, + 120503 + ], + "mapped", + [ + 960 + ] + ], + [ + [ + 120504, + 120504 + ], + "mapped", + [ + 961 + ] + ], + [ + [ + 120505, + 120505 + ], + "mapped", + [ + 952 + ] + ], + [ + [ + 120506, + 120506 + ], + "mapped", + [ + 963 + ] + ], + [ + [ + 120507, + 120507 + ], + "mapped", + [ + 964 + ] + ], + [ + [ + 120508, + 120508 + ], + "mapped", + [ + 965 + ] + ], + [ + [ + 120509, + 120509 + ], + "mapped", + [ + 966 + ] + ], + [ + [ + 120510, + 120510 + ], + "mapped", + [ + 967 + ] + ], + [ + [ + 120511, + 120511 + ], + "mapped", + [ + 968 + ] + ], + [ + [ + 120512, + 120512 + ], + "mapped", + [ + 969 + ] + ], + [ + [ + 120513, + 120513 + ], + "mapped", + [ + 8711 + ] + ], + [ + [ + 120514, + 120514 + ], + "mapped", + [ + 945 + ] + ], + [ + [ + 120515, + 120515 + ], + "mapped", + [ + 946 + ] + ], + [ + [ + 120516, + 120516 + ], + "mapped", + [ + 947 + ] + ], + [ + [ + 120517, + 120517 + ], + "mapped", + [ + 948 + ] + ], + [ + [ + 120518, + 120518 + ], + "mapped", + [ + 949 + ] + ], + [ + [ + 120519, + 120519 + ], + "mapped", + [ + 950 + ] + ], + [ + [ + 120520, + 120520 + ], + "mapped", + [ + 951 + ] + ], + [ + [ + 120521, + 120521 + ], + "mapped", + [ + 952 + ] + ], + [ + [ + 120522, + 120522 + ], + "mapped", + [ + 953 + ] + ], + [ + [ + 120523, + 120523 + ], + "mapped", + [ + 954 + ] + ], + [ + [ + 120524, + 120524 + ], + "mapped", + [ + 955 + ] + ], + [ + [ + 120525, + 120525 + ], + "mapped", + [ + 956 + ] + ], + [ + [ + 120526, + 120526 + ], + "mapped", + [ + 957 + ] + ], + [ + [ + 120527, + 120527 + ], + "mapped", + [ + 958 + ] + ], + [ + [ + 120528, + 120528 + ], + "mapped", + [ + 959 + ] + ], + [ + [ + 120529, + 120529 + ], + "mapped", + [ + 960 + ] + ], + [ + [ + 120530, + 120530 + ], + "mapped", + [ + 961 + ] + ], + [ + [ + 120531, + 120532 + ], + "mapped", + [ + 963 + ] + ], + [ + [ + 120533, + 120533 + ], + "mapped", + [ + 964 + ] + ], + [ + [ + 120534, + 120534 + ], + "mapped", + [ + 965 + ] + ], + [ + [ + 120535, + 120535 + ], + "mapped", + [ + 966 + ] + ], + [ + [ + 120536, + 120536 + ], + "mapped", + [ + 967 + ] + ], + [ + [ + 120537, + 120537 + ], + "mapped", + [ + 968 + ] + ], + [ + [ + 120538, + 120538 + ], + "mapped", + [ + 969 + ] + ], + [ + [ + 120539, + 120539 + ], + "mapped", + [ + 8706 + ] + ], + [ + [ + 120540, + 120540 + ], + "mapped", + [ + 949 + ] + ], + [ + [ + 120541, + 120541 + ], + "mapped", + [ + 952 + ] + ], + [ + [ + 120542, + 120542 + ], + "mapped", + [ + 954 + ] + ], + [ + [ + 120543, + 120543 + ], + "mapped", + [ + 966 + ] + ], + [ + [ + 120544, + 120544 + ], + "mapped", + [ + 961 + ] + ], + [ + [ + 120545, + 120545 + ], + "mapped", + [ + 960 + ] + ], + [ + [ + 120546, + 120546 + ], + "mapped", + [ + 945 + ] + ], + [ + [ + 120547, + 120547 + ], + "mapped", + [ + 946 + ] + ], + [ + [ + 120548, + 120548 + ], + "mapped", + [ + 947 + ] + ], + [ + [ + 120549, + 120549 + ], + "mapped", + [ + 948 + ] + ], + [ + [ + 120550, + 120550 + ], + "mapped", + [ + 949 + ] + ], + [ + [ + 120551, + 120551 + ], + "mapped", + [ + 950 + ] + ], + [ + [ + 120552, + 120552 + ], + "mapped", + [ + 951 + ] + ], + [ + [ + 120553, + 120553 + ], + "mapped", + [ + 952 + ] + ], + [ + [ + 120554, + 120554 + ], + "mapped", + [ + 953 + ] + ], + [ + [ + 120555, + 120555 + ], + "mapped", + [ + 954 + ] + ], + [ + [ + 120556, + 120556 + ], + "mapped", + [ + 955 + ] + ], + [ + [ + 120557, + 120557 + ], + "mapped", + [ + 956 + ] + ], + [ + [ + 120558, + 120558 + ], + "mapped", + [ + 957 + ] + ], + [ + [ + 120559, + 120559 + ], + "mapped", + [ + 958 + ] + ], + [ + [ + 120560, + 120560 + ], + "mapped", + [ + 959 + ] + ], + [ + [ + 120561, + 120561 + ], + "mapped", + [ + 960 + ] + ], + [ + [ + 120562, + 120562 + ], + "mapped", + [ + 961 + ] + ], + [ + [ + 120563, + 120563 + ], + "mapped", + [ + 952 + ] + ], + [ + [ + 120564, + 120564 + ], + "mapped", + [ + 963 + ] + ], + [ + [ + 120565, + 120565 + ], + "mapped", + [ + 964 + ] + ], + [ + [ + 120566, + 120566 + ], + "mapped", + [ + 965 + ] + ], + [ + [ + 120567, + 120567 + ], + "mapped", + [ + 966 + ] + ], + [ + [ + 120568, + 120568 + ], + "mapped", + [ + 967 + ] + ], + [ + [ + 120569, + 120569 + ], + "mapped", + [ + 968 + ] + ], + [ + [ + 120570, + 120570 + ], + "mapped", + [ + 969 + ] + ], + [ + [ + 120571, + 120571 + ], + "mapped", + [ + 8711 + ] + ], + [ + [ + 120572, + 120572 + ], + "mapped", + [ + 945 + ] + ], + [ + [ + 120573, + 120573 + ], + "mapped", + [ + 946 + ] + ], + [ + [ + 120574, + 120574 + ], + "mapped", + [ + 947 + ] + ], + [ + [ + 120575, + 120575 + ], + "mapped", + [ + 948 + ] + ], + [ + [ + 120576, + 120576 + ], + "mapped", + [ + 949 + ] + ], + [ + [ + 120577, + 120577 + ], + "mapped", + [ + 950 + ] + ], + [ + [ + 120578, + 120578 + ], + "mapped", + [ + 951 + ] + ], + [ + [ + 120579, + 120579 + ], + "mapped", + [ + 952 + ] + ], + [ + [ + 120580, + 120580 + ], + "mapped", + [ + 953 + ] + ], + [ + [ + 120581, + 120581 + ], + "mapped", + [ + 954 + ] + ], + [ + [ + 120582, + 120582 + ], + "mapped", + [ + 955 + ] + ], + [ + [ + 120583, + 120583 + ], + "mapped", + [ + 956 + ] + ], + [ + [ + 120584, + 120584 + ], + "mapped", + [ + 957 + ] + ], + [ + [ + 120585, + 120585 + ], + "mapped", + [ + 958 + ] + ], + [ + [ + 120586, + 120586 + ], + "mapped", + [ + 959 + ] + ], + [ + [ + 120587, + 120587 + ], + "mapped", + [ + 960 + ] + ], + [ + [ + 120588, + 120588 + ], + "mapped", + [ + 961 + ] + ], + [ + [ + 120589, + 120590 + ], + "mapped", + [ + 963 + ] + ], + [ + [ + 120591, + 120591 + ], + "mapped", + [ + 964 + ] + ], + [ + [ + 120592, + 120592 + ], + "mapped", + [ + 965 + ] + ], + [ + [ + 120593, + 120593 + ], + "mapped", + [ + 966 + ] + ], + [ + [ + 120594, + 120594 + ], + "mapped", + [ + 967 + ] + ], + [ + [ + 120595, + 120595 + ], + "mapped", + [ + 968 + ] + ], + [ + [ + 120596, + 120596 + ], + "mapped", + [ + 969 + ] + ], + [ + [ + 120597, + 120597 + ], + "mapped", + [ + 8706 + ] + ], + [ + [ + 120598, + 120598 + ], + "mapped", + [ + 949 + ] + ], + [ + [ + 120599, + 120599 + ], + "mapped", + [ + 952 + ] + ], + [ + [ + 120600, + 120600 + ], + "mapped", + [ + 954 + ] + ], + [ + [ + 120601, + 120601 + ], + "mapped", + [ + 966 + ] + ], + [ + [ + 120602, + 120602 + ], + "mapped", + [ + 961 + ] + ], + [ + [ + 120603, + 120603 + ], + "mapped", + [ + 960 + ] + ], + [ + [ + 120604, + 120604 + ], + "mapped", + [ + 945 + ] + ], + [ + [ + 120605, + 120605 + ], + "mapped", + [ + 946 + ] + ], + [ + [ + 120606, + 120606 + ], + "mapped", + [ + 947 + ] + ], + [ + [ + 120607, + 120607 + ], + "mapped", + [ + 948 + ] + ], + [ + [ + 120608, + 120608 + ], + "mapped", + [ + 949 + ] + ], + [ + [ + 120609, + 120609 + ], + "mapped", + [ + 950 + ] + ], + [ + [ + 120610, + 120610 + ], + "mapped", + [ + 951 + ] + ], + [ + [ + 120611, + 120611 + ], + "mapped", + [ + 952 + ] + ], + [ + [ + 120612, + 120612 + ], + "mapped", + [ + 953 + ] + ], + [ + [ + 120613, + 120613 + ], + "mapped", + [ + 954 + ] + ], + [ + [ + 120614, + 120614 + ], + "mapped", + [ + 955 + ] + ], + [ + [ + 120615, + 120615 + ], + "mapped", + [ + 956 + ] + ], + [ + [ + 120616, + 120616 + ], + "mapped", + [ + 957 + ] + ], + [ + [ + 120617, + 120617 + ], + "mapped", + [ + 958 + ] + ], + [ + [ + 120618, + 120618 + ], + "mapped", + [ + 959 + ] + ], + [ + [ + 120619, + 120619 + ], + "mapped", + [ + 960 + ] + ], + [ + [ + 120620, + 120620 + ], + "mapped", + [ + 961 + ] + ], + [ + [ + 120621, + 120621 + ], + "mapped", + [ + 952 + ] + ], + [ + [ + 120622, + 120622 + ], + "mapped", + [ + 963 + ] + ], + [ + [ + 120623, + 120623 + ], + "mapped", + [ + 964 + ] + ], + [ + [ + 120624, + 120624 + ], + "mapped", + [ + 965 + ] + ], + [ + [ + 120625, + 120625 + ], + "mapped", + [ + 966 + ] + ], + [ + [ + 120626, + 120626 + ], + "mapped", + [ + 967 + ] + ], + [ + [ + 120627, + 120627 + ], + "mapped", + [ + 968 + ] + ], + [ + [ + 120628, + 120628 + ], + "mapped", + [ + 969 + ] + ], + [ + [ + 120629, + 120629 + ], + "mapped", + [ + 8711 + ] + ], + [ + [ + 120630, + 120630 + ], + "mapped", + [ + 945 + ] + ], + [ + [ + 120631, + 120631 + ], + "mapped", + [ + 946 + ] + ], + [ + [ + 120632, + 120632 + ], + "mapped", + [ + 947 + ] + ], + [ + [ + 120633, + 120633 + ], + "mapped", + [ + 948 + ] + ], + [ + [ + 120634, + 120634 + ], + "mapped", + [ + 949 + ] + ], + [ + [ + 120635, + 120635 + ], + "mapped", + [ + 950 + ] + ], + [ + [ + 120636, + 120636 + ], + "mapped", + [ + 951 + ] + ], + [ + [ + 120637, + 120637 + ], + "mapped", + [ + 952 + ] + ], + [ + [ + 120638, + 120638 + ], + "mapped", + [ + 953 + ] + ], + [ + [ + 120639, + 120639 + ], + "mapped", + [ + 954 + ] + ], + [ + [ + 120640, + 120640 + ], + "mapped", + [ + 955 + ] + ], + [ + [ + 120641, + 120641 + ], + "mapped", + [ + 956 + ] + ], + [ + [ + 120642, + 120642 + ], + "mapped", + [ + 957 + ] + ], + [ + [ + 120643, + 120643 + ], + "mapped", + [ + 958 + ] + ], + [ + [ + 120644, + 120644 + ], + "mapped", + [ + 959 + ] + ], + [ + [ + 120645, + 120645 + ], + "mapped", + [ + 960 + ] + ], + [ + [ + 120646, + 120646 + ], + "mapped", + [ + 961 + ] + ], + [ + [ + 120647, + 120648 + ], + "mapped", + [ + 963 + ] + ], + [ + [ + 120649, + 120649 + ], + "mapped", + [ + 964 + ] + ], + [ + [ + 120650, + 120650 + ], + "mapped", + [ + 965 + ] + ], + [ + [ + 120651, + 120651 + ], + "mapped", + [ + 966 + ] + ], + [ + [ + 120652, + 120652 + ], + "mapped", + [ + 967 + ] + ], + [ + [ + 120653, + 120653 + ], + "mapped", + [ + 968 + ] + ], + [ + [ + 120654, + 120654 + ], + "mapped", + [ + 969 + ] + ], + [ + [ + 120655, + 120655 + ], + "mapped", + [ + 8706 + ] + ], + [ + [ + 120656, + 120656 + ], + "mapped", + [ + 949 + ] + ], + [ + [ + 120657, + 120657 + ], + "mapped", + [ + 952 + ] + ], + [ + [ + 120658, + 120658 + ], + "mapped", + [ + 954 + ] + ], + [ + [ + 120659, + 120659 + ], + "mapped", + [ + 966 + ] + ], + [ + [ + 120660, + 120660 + ], + "mapped", + [ + 961 + ] + ], + [ + [ + 120661, + 120661 + ], + "mapped", + [ + 960 + ] + ], + [ + [ + 120662, + 120662 + ], + "mapped", + [ + 945 + ] + ], + [ + [ + 120663, + 120663 + ], + "mapped", + [ + 946 + ] + ], + [ + [ + 120664, + 120664 + ], + "mapped", + [ + 947 + ] + ], + [ + [ + 120665, + 120665 + ], + "mapped", + [ + 948 + ] + ], + [ + [ + 120666, + 120666 + ], + "mapped", + [ + 949 + ] + ], + [ + [ + 120667, + 120667 + ], + "mapped", + [ + 950 + ] + ], + [ + [ + 120668, + 120668 + ], + "mapped", + [ + 951 + ] + ], + [ + [ + 120669, + 120669 + ], + "mapped", + [ + 952 + ] + ], + [ + [ + 120670, + 120670 + ], + "mapped", + [ + 953 + ] + ], + [ + [ + 120671, + 120671 + ], + "mapped", + [ + 954 + ] + ], + [ + [ + 120672, + 120672 + ], + "mapped", + [ + 955 + ] + ], + [ + [ + 120673, + 120673 + ], + "mapped", + [ + 956 + ] + ], + [ + [ + 120674, + 120674 + ], + "mapped", + [ + 957 + ] + ], + [ + [ + 120675, + 120675 + ], + "mapped", + [ + 958 + ] + ], + [ + [ + 120676, + 120676 + ], + "mapped", + [ + 959 + ] + ], + [ + [ + 120677, + 120677 + ], + "mapped", + [ + 960 + ] + ], + [ + [ + 120678, + 120678 + ], + "mapped", + [ + 961 + ] + ], + [ + [ + 120679, + 120679 + ], + "mapped", + [ + 952 + ] + ], + [ + [ + 120680, + 120680 + ], + "mapped", + [ + 963 + ] + ], + [ + [ + 120681, + 120681 + ], + "mapped", + [ + 964 + ] + ], + [ + [ + 120682, + 120682 + ], + "mapped", + [ + 965 + ] + ], + [ + [ + 120683, + 120683 + ], + "mapped", + [ + 966 + ] + ], + [ + [ + 120684, + 120684 + ], + "mapped", + [ + 967 + ] + ], + [ + [ + 120685, + 120685 + ], + "mapped", + [ + 968 + ] + ], + [ + [ + 120686, + 120686 + ], + "mapped", + [ + 969 + ] + ], + [ + [ + 120687, + 120687 + ], + "mapped", + [ + 8711 + ] + ], + [ + [ + 120688, + 120688 + ], + "mapped", + [ + 945 + ] + ], + [ + [ + 120689, + 120689 + ], + "mapped", + [ + 946 + ] + ], + [ + [ + 120690, + 120690 + ], + "mapped", + [ + 947 + ] + ], + [ + [ + 120691, + 120691 + ], + "mapped", + [ + 948 + ] + ], + [ + [ + 120692, + 120692 + ], + "mapped", + [ + 949 + ] + ], + [ + [ + 120693, + 120693 + ], + "mapped", + [ + 950 + ] + ], + [ + [ + 120694, + 120694 + ], + "mapped", + [ + 951 + ] + ], + [ + [ + 120695, + 120695 + ], + "mapped", + [ + 952 + ] + ], + [ + [ + 120696, + 120696 + ], + "mapped", + [ + 953 + ] + ], + [ + [ + 120697, + 120697 + ], + "mapped", + [ + 954 + ] + ], + [ + [ + 120698, + 120698 + ], + "mapped", + [ + 955 + ] + ], + [ + [ + 120699, + 120699 + ], + "mapped", + [ + 956 + ] + ], + [ + [ + 120700, + 120700 + ], + "mapped", + [ + 957 + ] + ], + [ + [ + 120701, + 120701 + ], + "mapped", + [ + 958 + ] + ], + [ + [ + 120702, + 120702 + ], + "mapped", + [ + 959 + ] + ], + [ + [ + 120703, + 120703 + ], + "mapped", + [ + 960 + ] + ], + [ + [ + 120704, + 120704 + ], + "mapped", + [ + 961 + ] + ], + [ + [ + 120705, + 120706 + ], + "mapped", + [ + 963 + ] + ], + [ + [ + 120707, + 120707 + ], + "mapped", + [ + 964 + ] + ], + [ + [ + 120708, + 120708 + ], + "mapped", + [ + 965 + ] + ], + [ + [ + 120709, + 120709 + ], + "mapped", + [ + 966 + ] + ], + [ + [ + 120710, + 120710 + ], + "mapped", + [ + 967 + ] + ], + [ + [ + 120711, + 120711 + ], + "mapped", + [ + 968 + ] + ], + [ + [ + 120712, + 120712 + ], + "mapped", + [ + 969 + ] + ], + [ + [ + 120713, + 120713 + ], + "mapped", + [ + 8706 + ] + ], + [ + [ + 120714, + 120714 + ], + "mapped", + [ + 949 + ] + ], + [ + [ + 120715, + 120715 + ], + "mapped", + [ + 952 + ] + ], + [ + [ + 120716, + 120716 + ], + "mapped", + [ + 954 + ] + ], + [ + [ + 120717, + 120717 + ], + "mapped", + [ + 966 + ] + ], + [ + [ + 120718, + 120718 + ], + "mapped", + [ + 961 + ] + ], + [ + [ + 120719, + 120719 + ], + "mapped", + [ + 960 + ] + ], + [ + [ + 120720, + 120720 + ], + "mapped", + [ + 945 + ] + ], + [ + [ + 120721, + 120721 + ], + "mapped", + [ + 946 + ] + ], + [ + [ + 120722, + 120722 + ], + "mapped", + [ + 947 + ] + ], + [ + [ + 120723, + 120723 + ], + "mapped", + [ + 948 + ] + ], + [ + [ + 120724, + 120724 + ], + "mapped", + [ + 949 + ] + ], + [ + [ + 120725, + 120725 + ], + "mapped", + [ + 950 + ] + ], + [ + [ + 120726, + 120726 + ], + "mapped", + [ + 951 + ] + ], + [ + [ + 120727, + 120727 + ], + "mapped", + [ + 952 + ] + ], + [ + [ + 120728, + 120728 + ], + "mapped", + [ + 953 + ] + ], + [ + [ + 120729, + 120729 + ], + "mapped", + [ + 954 + ] + ], + [ + [ + 120730, + 120730 + ], + "mapped", + [ + 955 + ] + ], + [ + [ + 120731, + 120731 + ], + "mapped", + [ + 956 + ] + ], + [ + [ + 120732, + 120732 + ], + "mapped", + [ + 957 + ] + ], + [ + [ + 120733, + 120733 + ], + "mapped", + [ + 958 + ] + ], + [ + [ + 120734, + 120734 + ], + "mapped", + [ + 959 + ] + ], + [ + [ + 120735, + 120735 + ], + "mapped", + [ + 960 + ] + ], + [ + [ + 120736, + 120736 + ], + "mapped", + [ + 961 + ] + ], + [ + [ + 120737, + 120737 + ], + "mapped", + [ + 952 + ] + ], + [ + [ + 120738, + 120738 + ], + "mapped", + [ + 963 + ] + ], + [ + [ + 120739, + 120739 + ], + "mapped", + [ + 964 + ] + ], + [ + [ + 120740, + 120740 + ], + "mapped", + [ + 965 + ] + ], + [ + [ + 120741, + 120741 + ], + "mapped", + [ + 966 + ] + ], + [ + [ + 120742, + 120742 + ], + "mapped", + [ + 967 + ] + ], + [ + [ + 120743, + 120743 + ], + "mapped", + [ + 968 + ] + ], + [ + [ + 120744, + 120744 + ], + "mapped", + [ + 969 + ] + ], + [ + [ + 120745, + 120745 + ], + "mapped", + [ + 8711 + ] + ], + [ + [ + 120746, + 120746 + ], + "mapped", + [ + 945 + ] + ], + [ + [ + 120747, + 120747 + ], + "mapped", + [ + 946 + ] + ], + [ + [ + 120748, + 120748 + ], + "mapped", + [ + 947 + ] + ], + [ + [ + 120749, + 120749 + ], + "mapped", + [ + 948 + ] + ], + [ + [ + 120750, + 120750 + ], + "mapped", + [ + 949 + ] + ], + [ + [ + 120751, + 120751 + ], + "mapped", + [ + 950 + ] + ], + [ + [ + 120752, + 120752 + ], + "mapped", + [ + 951 + ] + ], + [ + [ + 120753, + 120753 + ], + "mapped", + [ + 952 + ] + ], + [ + [ + 120754, + 120754 + ], + "mapped", + [ + 953 + ] + ], + [ + [ + 120755, + 120755 + ], + "mapped", + [ + 954 + ] + ], + [ + [ + 120756, + 120756 + ], + "mapped", + [ + 955 + ] + ], + [ + [ + 120757, + 120757 + ], + "mapped", + [ + 956 + ] + ], + [ + [ + 120758, + 120758 + ], + "mapped", + [ + 957 + ] + ], + [ + [ + 120759, + 120759 + ], + "mapped", + [ + 958 + ] + ], + [ + [ + 120760, + 120760 + ], + "mapped", + [ + 959 + ] + ], + [ + [ + 120761, + 120761 + ], + "mapped", + [ + 960 + ] + ], + [ + [ + 120762, + 120762 + ], + "mapped", + [ + 961 + ] + ], + [ + [ + 120763, + 120764 + ], + "mapped", + [ + 963 + ] + ], + [ + [ + 120765, + 120765 + ], + "mapped", + [ + 964 + ] + ], + [ + [ + 120766, + 120766 + ], + "mapped", + [ + 965 + ] + ], + [ + [ + 120767, + 120767 + ], + "mapped", + [ + 966 + ] + ], + [ + [ + 120768, + 120768 + ], + "mapped", + [ + 967 + ] + ], + [ + [ + 120769, + 120769 + ], + "mapped", + [ + 968 + ] + ], + [ + [ + 120770, + 120770 + ], + "mapped", + [ + 969 + ] + ], + [ + [ + 120771, + 120771 + ], + "mapped", + [ + 8706 + ] + ], + [ + [ + 120772, + 120772 + ], + "mapped", + [ + 949 + ] + ], + [ + [ + 120773, + 120773 + ], + "mapped", + [ + 952 + ] + ], + [ + [ + 120774, + 120774 + ], + "mapped", + [ + 954 + ] + ], + [ + [ + 120775, + 120775 + ], + "mapped", + [ + 966 + ] + ], + [ + [ + 120776, + 120776 + ], + "mapped", + [ + 961 + ] + ], + [ + [ + 120777, + 120777 + ], + "mapped", + [ + 960 + ] + ], + [ + [ + 120778, + 120779 + ], + "mapped", + [ + 989 + ] + ], + [ + [ + 120780, + 120781 + ], + "disallowed" + ], + [ + [ + 120782, + 120782 + ], + "mapped", + [ + 48 + ] + ], + [ + [ + 120783, + 120783 + ], + "mapped", + [ + 49 + ] + ], + [ + [ + 120784, + 120784 + ], + "mapped", + [ + 50 + ] + ], + [ + [ + 120785, + 120785 + ], + "mapped", + [ + 51 + ] + ], + [ + [ + 120786, + 120786 + ], + "mapped", + [ + 52 + ] + ], + [ + [ + 120787, + 120787 + ], + "mapped", + [ + 53 + ] + ], + [ + [ + 120788, + 120788 + ], + "mapped", + [ + 54 + ] + ], + [ + [ + 120789, + 120789 + ], + "mapped", + [ + 55 + ] + ], + [ + [ + 120790, + 120790 + ], + "mapped", + [ + 56 + ] + ], + [ + [ + 120791, + 120791 + ], + "mapped", + [ + 57 + ] + ], + [ + [ + 120792, + 120792 + ], + "mapped", + [ + 48 + ] + ], + [ + [ + 120793, + 120793 + ], + "mapped", + [ + 49 + ] + ], + [ + [ + 120794, + 120794 + ], + "mapped", + [ + 50 + ] + ], + [ + [ + 120795, + 120795 + ], + "mapped", + [ + 51 + ] + ], + [ + [ + 120796, + 120796 + ], + "mapped", + [ + 52 + ] + ], + [ + [ + 120797, + 120797 + ], + "mapped", + [ + 53 + ] + ], + [ + [ + 120798, + 120798 + ], + "mapped", + [ + 54 + ] + ], + [ + [ + 120799, + 120799 + ], + "mapped", + [ + 55 + ] + ], + [ + [ + 120800, + 120800 + ], + "mapped", + [ + 56 + ] + ], + [ + [ + 120801, + 120801 + ], + "mapped", + [ + 57 + ] + ], + [ + [ + 120802, + 120802 + ], + "mapped", + [ + 48 + ] + ], + [ + [ + 120803, + 120803 + ], + "mapped", + [ + 49 + ] + ], + [ + [ + 120804, + 120804 + ], + "mapped", + [ + 50 + ] + ], + [ + [ + 120805, + 120805 + ], + "mapped", + [ + 51 + ] + ], + [ + [ + 120806, + 120806 + ], + "mapped", + [ + 52 + ] + ], + [ + [ + 120807, + 120807 + ], + "mapped", + [ + 53 + ] + ], + [ + [ + 120808, + 120808 + ], + "mapped", + [ + 54 + ] + ], + [ + [ + 120809, + 120809 + ], + "mapped", + [ + 55 + ] + ], + [ + [ + 120810, + 120810 + ], + "mapped", + [ + 56 + ] + ], + [ + [ + 120811, + 120811 + ], + "mapped", + [ + 57 + ] + ], + [ + [ + 120812, + 120812 + ], + "mapped", + [ + 48 + ] + ], + [ + [ + 120813, + 120813 + ], + "mapped", + [ + 49 + ] + ], + [ + [ + 120814, + 120814 + ], + "mapped", + [ + 50 + ] + ], + [ + [ + 120815, + 120815 + ], + "mapped", + [ + 51 + ] + ], + [ + [ + 120816, + 120816 + ], + "mapped", + [ + 52 + ] + ], + [ + [ + 120817, + 120817 + ], + "mapped", + [ + 53 + ] + ], + [ + [ + 120818, + 120818 + ], + "mapped", + [ + 54 + ] + ], + [ + [ + 120819, + 120819 + ], + "mapped", + [ + 55 + ] + ], + [ + [ + 120820, + 120820 + ], + "mapped", + [ + 56 + ] + ], + [ + [ + 120821, + 120821 + ], + "mapped", + [ + 57 + ] + ], + [ + [ + 120822, + 120822 + ], + "mapped", + [ + 48 + ] + ], + [ + [ + 120823, + 120823 + ], + "mapped", + [ + 49 + ] + ], + [ + [ + 120824, + 120824 + ], + "mapped", + [ + 50 + ] + ], + [ + [ + 120825, + 120825 + ], + "mapped", + [ + 51 + ] + ], + [ + [ + 120826, + 120826 + ], + "mapped", + [ + 52 + ] + ], + [ + [ + 120827, + 120827 + ], + "mapped", + [ + 53 + ] + ], + [ + [ + 120828, + 120828 + ], + "mapped", + [ + 54 + ] + ], + [ + [ + 120829, + 120829 + ], + "mapped", + [ + 55 + ] + ], + [ + [ + 120830, + 120830 + ], + "mapped", + [ + 56 + ] + ], + [ + [ + 120831, + 120831 + ], + "mapped", + [ + 57 + ] + ], + [ + [ + 120832, + 121343 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 121344, + 121398 + ], + "valid" + ], + [ + [ + 121399, + 121402 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 121403, + 121452 + ], + "valid" + ], + [ + [ + 121453, + 121460 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 121461, + 121461 + ], + "valid" + ], + [ + [ + 121462, + 121475 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 121476, + 121476 + ], + "valid" + ], + [ + [ + 121477, + 121483 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 121484, + 121498 + ], + "disallowed" + ], + [ + [ + 121499, + 121503 + ], + "valid" + ], + [ + [ + 121504, + 121504 + ], + "disallowed" + ], + [ + [ + 121505, + 121519 + ], + "valid" + ], + [ + [ + 121520, + 124927 + ], + "disallowed" + ], + [ + [ + 124928, + 125124 + ], + "valid" + ], + [ + [ + 125125, + 125126 + ], + "disallowed" + ], + [ + [ + 125127, + 125135 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 125136, + 125142 + ], + "valid" + ], + [ + [ + 125143, + 126463 + ], + "disallowed" + ], + [ + [ + 126464, + 126464 + ], + "mapped", + [ + 1575 + ] + ], + [ + [ + 126465, + 126465 + ], + "mapped", + [ + 1576 + ] + ], + [ + [ + 126466, + 126466 + ], + "mapped", + [ + 1580 + ] + ], + [ + [ + 126467, + 126467 + ], + "mapped", + [ + 1583 + ] + ], + [ + [ + 126468, + 126468 + ], + "disallowed" + ], + [ + [ + 126469, + 126469 + ], + "mapped", + [ + 1608 + ] + ], + [ + [ + 126470, + 126470 + ], + "mapped", + [ + 1586 + ] + ], + [ + [ + 126471, + 126471 + ], + "mapped", + [ + 1581 + ] + ], + [ + [ + 126472, + 126472 + ], + "mapped", + [ + 1591 + ] + ], + [ + [ + 126473, + 126473 + ], + "mapped", + [ + 1610 + ] + ], + [ + [ + 126474, + 126474 + ], + "mapped", + [ + 1603 + ] + ], + [ + [ + 126475, + 126475 + ], + "mapped", + [ + 1604 + ] + ], + [ + [ + 126476, + 126476 + ], + "mapped", + [ + 1605 + ] + ], + [ + [ + 126477, + 126477 + ], + "mapped", + [ + 1606 + ] + ], + [ + [ + 126478, + 126478 + ], + "mapped", + [ + 1587 + ] + ], + [ + [ + 126479, + 126479 + ], + "mapped", + [ + 1593 + ] + ], + [ + [ + 126480, + 126480 + ], + "mapped", + [ + 1601 + ] + ], + [ + [ + 126481, + 126481 + ], + "mapped", + [ + 1589 + ] + ], + [ + [ + 126482, + 126482 + ], + "mapped", + [ + 1602 + ] + ], + [ + [ + 126483, + 126483 + ], + "mapped", + [ + 1585 + ] + ], + [ + [ + 126484, + 126484 + ], + "mapped", + [ + 1588 + ] + ], + [ + [ + 126485, + 126485 + ], + "mapped", + [ + 1578 + ] + ], + [ + [ + 126486, + 126486 + ], + "mapped", + [ + 1579 + ] + ], + [ + [ + 126487, + 126487 + ], + "mapped", + [ + 1582 + ] + ], + [ + [ + 126488, + 126488 + ], + "mapped", + [ + 1584 + ] + ], + [ + [ + 126489, + 126489 + ], + "mapped", + [ + 1590 + ] + ], + [ + [ + 126490, + 126490 + ], + "mapped", + [ + 1592 + ] + ], + [ + [ + 126491, + 126491 + ], + "mapped", + [ + 1594 + ] + ], + [ + [ + 126492, + 126492 + ], + "mapped", + [ + 1646 + ] + ], + [ + [ + 126493, + 126493 + ], + "mapped", + [ + 1722 + ] + ], + [ + [ + 126494, + 126494 + ], + "mapped", + [ + 1697 + ] + ], + [ + [ + 126495, + 126495 + ], + "mapped", + [ + 1647 + ] + ], + [ + [ + 126496, + 126496 + ], + "disallowed" + ], + [ + [ + 126497, + 126497 + ], + "mapped", + [ + 1576 + ] + ], + [ + [ + 126498, + 126498 + ], + "mapped", + [ + 1580 + ] + ], + [ + [ + 126499, + 126499 + ], + "disallowed" + ], + [ + [ + 126500, + 126500 + ], + "mapped", + [ + 1607 + ] + ], + [ + [ + 126501, + 126502 + ], + "disallowed" + ], + [ + [ + 126503, + 126503 + ], + "mapped", + [ + 1581 + ] + ], + [ + [ + 126504, + 126504 + ], + "disallowed" + ], + [ + [ + 126505, + 126505 + ], + "mapped", + [ + 1610 + ] + ], + [ + [ + 126506, + 126506 + ], + "mapped", + [ + 1603 + ] + ], + [ + [ + 126507, + 126507 + ], + "mapped", + [ + 1604 + ] + ], + [ + [ + 126508, + 126508 + ], + "mapped", + [ + 1605 + ] + ], + [ + [ + 126509, + 126509 + ], + "mapped", + [ + 1606 + ] + ], + [ + [ + 126510, + 126510 + ], + "mapped", + [ + 1587 + ] + ], + [ + [ + 126511, + 126511 + ], + "mapped", + [ + 1593 + ] + ], + [ + [ + 126512, + 126512 + ], + "mapped", + [ + 1601 + ] + ], + [ + [ + 126513, + 126513 + ], + "mapped", + [ + 1589 + ] + ], + [ + [ + 126514, + 126514 + ], + "mapped", + [ + 1602 + ] + ], + [ + [ + 126515, + 126515 + ], + "disallowed" + ], + [ + [ + 126516, + 126516 + ], + "mapped", + [ + 1588 + ] + ], + [ + [ + 126517, + 126517 + ], + "mapped", + [ + 1578 + ] + ], + [ + [ + 126518, + 126518 + ], + "mapped", + [ + 1579 + ] + ], + [ + [ + 126519, + 126519 + ], + "mapped", + [ + 1582 + ] + ], + [ + [ + 126520, + 126520 + ], + "disallowed" + ], + [ + [ + 126521, + 126521 + ], + "mapped", + [ + 1590 + ] + ], + [ + [ + 126522, + 126522 + ], + "disallowed" + ], + [ + [ + 126523, + 126523 + ], + "mapped", + [ + 1594 + ] + ], + [ + [ + 126524, + 126529 + ], + "disallowed" + ], + [ + [ + 126530, + 126530 + ], + "mapped", + [ + 1580 + ] + ], + [ + [ + 126531, + 126534 + ], + "disallowed" + ], + [ + [ + 126535, + 126535 + ], + "mapped", + [ + 1581 + ] + ], + [ + [ + 126536, + 126536 + ], + "disallowed" + ], + [ + [ + 126537, + 126537 + ], + "mapped", + [ + 1610 + ] + ], + [ + [ + 126538, + 126538 + ], + "disallowed" + ], + [ + [ + 126539, + 126539 + ], + "mapped", + [ + 1604 + ] + ], + [ + [ + 126540, + 126540 + ], + "disallowed" + ], + [ + [ + 126541, + 126541 + ], + "mapped", + [ + 1606 + ] + ], + [ + [ + 126542, + 126542 + ], + "mapped", + [ + 1587 + ] + ], + [ + [ + 126543, + 126543 + ], + "mapped", + [ + 1593 + ] + ], + [ + [ + 126544, + 126544 + ], + "disallowed" + ], + [ + [ + 126545, + 126545 + ], + "mapped", + [ + 1589 + ] + ], + [ + [ + 126546, + 126546 + ], + "mapped", + [ + 1602 + ] + ], + [ + [ + 126547, + 126547 + ], + "disallowed" + ], + [ + [ + 126548, + 126548 + ], + "mapped", + [ + 1588 + ] + ], + [ + [ + 126549, + 126550 + ], + "disallowed" + ], + [ + [ + 126551, + 126551 + ], + "mapped", + [ + 1582 + ] + ], + [ + [ + 126552, + 126552 + ], + "disallowed" + ], + [ + [ + 126553, + 126553 + ], + "mapped", + [ + 1590 + ] + ], + [ + [ + 126554, + 126554 + ], + "disallowed" + ], + [ + [ + 126555, + 126555 + ], + "mapped", + [ + 1594 + ] + ], + [ + [ + 126556, + 126556 + ], + "disallowed" + ], + [ + [ + 126557, + 126557 + ], + "mapped", + [ + 1722 + ] + ], + [ + [ + 126558, + 126558 + ], + "disallowed" + ], + [ + [ + 126559, + 126559 + ], + "mapped", + [ + 1647 + ] + ], + [ + [ + 126560, + 126560 + ], + "disallowed" + ], + [ + [ + 126561, + 126561 + ], + "mapped", + [ + 1576 + ] + ], + [ + [ + 126562, + 126562 + ], + "mapped", + [ + 1580 + ] + ], + [ + [ + 126563, + 126563 + ], + "disallowed" + ], + [ + [ + 126564, + 126564 + ], + "mapped", + [ + 1607 + ] + ], + [ + [ + 126565, + 126566 + ], + "disallowed" + ], + [ + [ + 126567, + 126567 + ], + "mapped", + [ + 1581 + ] + ], + [ + [ + 126568, + 126568 + ], + "mapped", + [ + 1591 + ] + ], + [ + [ + 126569, + 126569 + ], + "mapped", + [ + 1610 + ] + ], + [ + [ + 126570, + 126570 + ], + "mapped", + [ + 1603 + ] + ], + [ + [ + 126571, + 126571 + ], + "disallowed" + ], + [ + [ + 126572, + 126572 + ], + "mapped", + [ + 1605 + ] + ], + [ + [ + 126573, + 126573 + ], + "mapped", + [ + 1606 + ] + ], + [ + [ + 126574, + 126574 + ], + "mapped", + [ + 1587 + ] + ], + [ + [ + 126575, + 126575 + ], + "mapped", + [ + 1593 + ] + ], + [ + [ + 126576, + 126576 + ], + "mapped", + [ + 1601 + ] + ], + [ + [ + 126577, + 126577 + ], + "mapped", + [ + 1589 + ] + ], + [ + [ + 126578, + 126578 + ], + "mapped", + [ + 1602 + ] + ], + [ + [ + 126579, + 126579 + ], + "disallowed" + ], + [ + [ + 126580, + 126580 + ], + "mapped", + [ + 1588 + ] + ], + [ + [ + 126581, + 126581 + ], + "mapped", + [ + 1578 + ] + ], + [ + [ + 126582, + 126582 + ], + "mapped", + [ + 1579 + ] + ], + [ + [ + 126583, + 126583 + ], + "mapped", + [ + 1582 + ] + ], + [ + [ + 126584, + 126584 + ], + "disallowed" + ], + [ + [ + 126585, + 126585 + ], + "mapped", + [ + 1590 + ] + ], + [ + [ + 126586, + 126586 + ], + "mapped", + [ + 1592 + ] + ], + [ + [ + 126587, + 126587 + ], + "mapped", + [ + 1594 + ] + ], + [ + [ + 126588, + 126588 + ], + "mapped", + [ + 1646 + ] + ], + [ + [ + 126589, + 126589 + ], + "disallowed" + ], + [ + [ + 126590, + 126590 + ], + "mapped", + [ + 1697 + ] + ], + [ + [ + 126591, + 126591 + ], + "disallowed" + ], + [ + [ + 126592, + 126592 + ], + "mapped", + [ + 1575 + ] + ], + [ + [ + 126593, + 126593 + ], + "mapped", + [ + 1576 + ] + ], + [ + [ + 126594, + 126594 + ], + "mapped", + [ + 1580 + ] + ], + [ + [ + 126595, + 126595 + ], + "mapped", + [ + 1583 + ] + ], + [ + [ + 126596, + 126596 + ], + "mapped", + [ + 1607 + ] + ], + [ + [ + 126597, + 126597 + ], + "mapped", + [ + 1608 + ] + ], + [ + [ + 126598, + 126598 + ], + "mapped", + [ + 1586 + ] + ], + [ + [ + 126599, + 126599 + ], + "mapped", + [ + 1581 + ] + ], + [ + [ + 126600, + 126600 + ], + "mapped", + [ + 1591 + ] + ], + [ + [ + 126601, + 126601 + ], + "mapped", + [ + 1610 + ] + ], + [ + [ + 126602, + 126602 + ], + "disallowed" + ], + [ + [ + 126603, + 126603 + ], + "mapped", + [ + 1604 + ] + ], + [ + [ + 126604, + 126604 + ], + "mapped", + [ + 1605 + ] + ], + [ + [ + 126605, + 126605 + ], + "mapped", + [ + 1606 + ] + ], + [ + [ + 126606, + 126606 + ], + "mapped", + [ + 1587 + ] + ], + [ + [ + 126607, + 126607 + ], + "mapped", + [ + 1593 + ] + ], + [ + [ + 126608, + 126608 + ], + "mapped", + [ + 1601 + ] + ], + [ + [ + 126609, + 126609 + ], + "mapped", + [ + 1589 + ] + ], + [ + [ + 126610, + 126610 + ], + "mapped", + [ + 1602 + ] + ], + [ + [ + 126611, + 126611 + ], + "mapped", + [ + 1585 + ] + ], + [ + [ + 126612, + 126612 + ], + "mapped", + [ + 1588 + ] + ], + [ + [ + 126613, + 126613 + ], + "mapped", + [ + 1578 + ] + ], + [ + [ + 126614, + 126614 + ], + "mapped", + [ + 1579 + ] + ], + [ + [ + 126615, + 126615 + ], + "mapped", + [ + 1582 + ] + ], + [ + [ + 126616, + 126616 + ], + "mapped", + [ + 1584 + ] + ], + [ + [ + 126617, + 126617 + ], + "mapped", + [ + 1590 + ] + ], + [ + [ + 126618, + 126618 + ], + "mapped", + [ + 1592 + ] + ], + [ + [ + 126619, + 126619 + ], + "mapped", + [ + 1594 + ] + ], + [ + [ + 126620, + 126624 + ], + "disallowed" + ], + [ + [ + 126625, + 126625 + ], + "mapped", + [ + 1576 + ] + ], + [ + [ + 126626, + 126626 + ], + "mapped", + [ + 1580 + ] + ], + [ + [ + 126627, + 126627 + ], + "mapped", + [ + 1583 + ] + ], + [ + [ + 126628, + 126628 + ], + "disallowed" + ], + [ + [ + 126629, + 126629 + ], + "mapped", + [ + 1608 + ] + ], + [ + [ + 126630, + 126630 + ], + "mapped", + [ + 1586 + ] + ], + [ + [ + 126631, + 126631 + ], + "mapped", + [ + 1581 + ] + ], + [ + [ + 126632, + 126632 + ], + "mapped", + [ + 1591 + ] + ], + [ + [ + 126633, + 126633 + ], + "mapped", + [ + 1610 + ] + ], + [ + [ + 126634, + 126634 + ], + "disallowed" + ], + [ + [ + 126635, + 126635 + ], + "mapped", + [ + 1604 + ] + ], + [ + [ + 126636, + 126636 + ], + "mapped", + [ + 1605 + ] + ], + [ + [ + 126637, + 126637 + ], + "mapped", + [ + 1606 + ] + ], + [ + [ + 126638, + 126638 + ], + "mapped", + [ + 1587 + ] + ], + [ + [ + 126639, + 126639 + ], + "mapped", + [ + 1593 + ] + ], + [ + [ + 126640, + 126640 + ], + "mapped", + [ + 1601 + ] + ], + [ + [ + 126641, + 126641 + ], + "mapped", + [ + 1589 + ] + ], + [ + [ + 126642, + 126642 + ], + "mapped", + [ + 1602 + ] + ], + [ + [ + 126643, + 126643 + ], + "mapped", + [ + 1585 + ] + ], + [ + [ + 126644, + 126644 + ], + "mapped", + [ + 1588 + ] + ], + [ + [ + 126645, + 126645 + ], + "mapped", + [ + 1578 + ] + ], + [ + [ + 126646, + 126646 + ], + "mapped", + [ + 1579 + ] + ], + [ + [ + 126647, + 126647 + ], + "mapped", + [ + 1582 + ] + ], + [ + [ + 126648, + 126648 + ], + "mapped", + [ + 1584 + ] + ], + [ + [ + 126649, + 126649 + ], + "mapped", + [ + 1590 + ] + ], + [ + [ + 126650, + 126650 + ], + "mapped", + [ + 1592 + ] + ], + [ + [ + 126651, + 126651 + ], + "mapped", + [ + 1594 + ] + ], + [ + [ + 126652, + 126703 + ], + "disallowed" + ], + [ + [ + 126704, + 126705 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 126706, + 126975 + ], + "disallowed" + ], + [ + [ + 126976, + 127019 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 127020, + 127023 + ], + "disallowed" + ], + [ + [ + 127024, + 127123 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 127124, + 127135 + ], + "disallowed" + ], + [ + [ + 127136, + 127150 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 127151, + 127152 + ], + "disallowed" + ], + [ + [ + 127153, + 127166 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 127167, + 127167 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 127168, + 127168 + ], + "disallowed" + ], + [ + [ + 127169, + 127183 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 127184, + 127184 + ], + "disallowed" + ], + [ + [ + 127185, + 127199 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 127200, + 127221 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 127222, + 127231 + ], + "disallowed" + ], + [ + [ + 127232, + 127232 + ], + "disallowed" + ], + [ + [ + 127233, + 127233 + ], + "disallowed_STD3_mapped", + [ + 48, + 44 + ] + ], + [ + [ + 127234, + 127234 + ], + "disallowed_STD3_mapped", + [ + 49, + 44 + ] + ], + [ + [ + 127235, + 127235 + ], + "disallowed_STD3_mapped", + [ + 50, + 44 + ] + ], + [ + [ + 127236, + 127236 + ], + "disallowed_STD3_mapped", + [ + 51, + 44 + ] + ], + [ + [ + 127237, + 127237 + ], + "disallowed_STD3_mapped", + [ + 52, + 44 + ] + ], + [ + [ + 127238, + 127238 + ], + "disallowed_STD3_mapped", + [ + 53, + 44 + ] + ], + [ + [ + 127239, + 127239 + ], + "disallowed_STD3_mapped", + [ + 54, + 44 + ] + ], + [ + [ + 127240, + 127240 + ], + "disallowed_STD3_mapped", + [ + 55, + 44 + ] + ], + [ + [ + 127241, + 127241 + ], + "disallowed_STD3_mapped", + [ + 56, + 44 + ] + ], + [ + [ + 127242, + 127242 + ], + "disallowed_STD3_mapped", + [ + 57, + 44 + ] + ], + [ + [ + 127243, + 127244 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 127245, + 127247 + ], + "disallowed" + ], + [ + [ + 127248, + 127248 + ], + "disallowed_STD3_mapped", + [ + 40, + 97, + 41 + ] + ], + [ + [ + 127249, + 127249 + ], + "disallowed_STD3_mapped", + [ + 40, + 98, + 41 + ] + ], + [ + [ + 127250, + 127250 + ], + "disallowed_STD3_mapped", + [ + 40, + 99, + 41 + ] + ], + [ + [ + 127251, + 127251 + ], + "disallowed_STD3_mapped", + [ + 40, + 100, + 41 + ] + ], + [ + [ + 127252, + 127252 + ], + "disallowed_STD3_mapped", + [ + 40, + 101, + 41 + ] + ], + [ + [ + 127253, + 127253 + ], + "disallowed_STD3_mapped", + [ + 40, + 102, + 41 + ] + ], + [ + [ + 127254, + 127254 + ], + "disallowed_STD3_mapped", + [ + 40, + 103, + 41 + ] + ], + [ + [ + 127255, + 127255 + ], + "disallowed_STD3_mapped", + [ + 40, + 104, + 41 + ] + ], + [ + [ + 127256, + 127256 + ], + "disallowed_STD3_mapped", + [ + 40, + 105, + 41 + ] + ], + [ + [ + 127257, + 127257 + ], + "disallowed_STD3_mapped", + [ + 40, + 106, + 41 + ] + ], + [ + [ + 127258, + 127258 + ], + "disallowed_STD3_mapped", + [ + 40, + 107, + 41 + ] + ], + [ + [ + 127259, + 127259 + ], + "disallowed_STD3_mapped", + [ + 40, + 108, + 41 + ] + ], + [ + [ + 127260, + 127260 + ], + "disallowed_STD3_mapped", + [ + 40, + 109, + 41 + ] + ], + [ + [ + 127261, + 127261 + ], + "disallowed_STD3_mapped", + [ + 40, + 110, + 41 + ] + ], + [ + [ + 127262, + 127262 + ], + "disallowed_STD3_mapped", + [ + 40, + 111, + 41 + ] + ], + [ + [ + 127263, + 127263 + ], + "disallowed_STD3_mapped", + [ + 40, + 112, + 41 + ] + ], + [ + [ + 127264, + 127264 + ], + "disallowed_STD3_mapped", + [ + 40, + 113, + 41 + ] + ], + [ + [ + 127265, + 127265 + ], + "disallowed_STD3_mapped", + [ + 40, + 114, + 41 + ] + ], + [ + [ + 127266, + 127266 + ], + "disallowed_STD3_mapped", + [ + 40, + 115, + 41 + ] + ], + [ + [ + 127267, + 127267 + ], + "disallowed_STD3_mapped", + [ + 40, + 116, + 41 + ] + ], + [ + [ + 127268, + 127268 + ], + "disallowed_STD3_mapped", + [ + 40, + 117, + 41 + ] + ], + [ + [ + 127269, + 127269 + ], + "disallowed_STD3_mapped", + [ + 40, + 118, + 41 + ] + ], + [ + [ + 127270, + 127270 + ], + "disallowed_STD3_mapped", + [ + 40, + 119, + 41 + ] + ], + [ + [ + 127271, + 127271 + ], + "disallowed_STD3_mapped", + [ + 40, + 120, + 41 + ] + ], + [ + [ + 127272, + 127272 + ], + "disallowed_STD3_mapped", + [ + 40, + 121, + 41 + ] + ], + [ + [ + 127273, + 127273 + ], + "disallowed_STD3_mapped", + [ + 40, + 122, + 41 + ] + ], + [ + [ + 127274, + 127274 + ], + "mapped", + [ + 12308, + 115, + 12309 + ] + ], + [ + [ + 127275, + 127275 + ], + "mapped", + [ + 99 + ] + ], + [ + [ + 127276, + 127276 + ], + "mapped", + [ + 114 + ] + ], + [ + [ + 127277, + 127277 + ], + "mapped", + [ + 99, + 100 + ] + ], + [ + [ + 127278, + 127278 + ], + "mapped", + [ + 119, + 122 + ] + ], + [ + [ + 127279, + 127279 + ], + "disallowed" + ], + [ + [ + 127280, + 127280 + ], + "mapped", + [ + 97 + ] + ], + [ + [ + 127281, + 127281 + ], + "mapped", + [ + 98 + ] + ], + [ + [ + 127282, + 127282 + ], + "mapped", + [ + 99 + ] + ], + [ + [ + 127283, + 127283 + ], + "mapped", + [ + 100 + ] + ], + [ + [ + 127284, + 127284 + ], + "mapped", + [ + 101 + ] + ], + [ + [ + 127285, + 127285 + ], + "mapped", + [ + 102 + ] + ], + [ + [ + 127286, + 127286 + ], + "mapped", + [ + 103 + ] + ], + [ + [ + 127287, + 127287 + ], + "mapped", + [ + 104 + ] + ], + [ + [ + 127288, + 127288 + ], + "mapped", + [ + 105 + ] + ], + [ + [ + 127289, + 127289 + ], + "mapped", + [ + 106 + ] + ], + [ + [ + 127290, + 127290 + ], + "mapped", + [ + 107 + ] + ], + [ + [ + 127291, + 127291 + ], + "mapped", + [ + 108 + ] + ], + [ + [ + 127292, + 127292 + ], + "mapped", + [ + 109 + ] + ], + [ + [ + 127293, + 127293 + ], + "mapped", + [ + 110 + ] + ], + [ + [ + 127294, + 127294 + ], + "mapped", + [ + 111 + ] + ], + [ + [ + 127295, + 127295 + ], + "mapped", + [ + 112 + ] + ], + [ + [ + 127296, + 127296 + ], + "mapped", + [ + 113 + ] + ], + [ + [ + 127297, + 127297 + ], + "mapped", + [ + 114 + ] + ], + [ + [ + 127298, + 127298 + ], + "mapped", + [ + 115 + ] + ], + [ + [ + 127299, + 127299 + ], + "mapped", + [ + 116 + ] + ], + [ + [ + 127300, + 127300 + ], + "mapped", + [ + 117 + ] + ], + [ + [ + 127301, + 127301 + ], + "mapped", + [ + 118 + ] + ], + [ + [ + 127302, + 127302 + ], + "mapped", + [ + 119 + ] + ], + [ + [ + 127303, + 127303 + ], + "mapped", + [ + 120 + ] + ], + [ + [ + 127304, + 127304 + ], + "mapped", + [ + 121 + ] + ], + [ + [ + 127305, + 127305 + ], + "mapped", + [ + 122 + ] + ], + [ + [ + 127306, + 127306 + ], + "mapped", + [ + 104, + 118 + ] + ], + [ + [ + 127307, + 127307 + ], + "mapped", + [ + 109, + 118 + ] + ], + [ + [ + 127308, + 127308 + ], + "mapped", + [ + 115, + 100 + ] + ], + [ + [ + 127309, + 127309 + ], + "mapped", + [ + 115, + 115 + ] + ], + [ + [ + 127310, + 127310 + ], + "mapped", + [ + 112, + 112, + 118 + ] + ], + [ + [ + 127311, + 127311 + ], + "mapped", + [ + 119, + 99 + ] + ], + [ + [ + 127312, + 127318 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 127319, + 127319 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 127320, + 127326 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 127327, + 127327 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 127328, + 127337 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 127338, + 127338 + ], + "mapped", + [ + 109, + 99 + ] + ], + [ + [ + 127339, + 127339 + ], + "mapped", + [ + 109, + 100 + ] + ], + [ + [ + 127340, + 127343 + ], + "disallowed" + ], + [ + [ + 127344, + 127352 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 127353, + 127353 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 127354, + 127354 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 127355, + 127356 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 127357, + 127358 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 127359, + 127359 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 127360, + 127369 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 127370, + 127373 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 127374, + 127375 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 127376, + 127376 + ], + "mapped", + [ + 100, + 106 + ] + ], + [ + [ + 127377, + 127386 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 127387, + 127461 + ], + "disallowed" + ], + [ + [ + 127462, + 127487 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 127488, + 127488 + ], + "mapped", + [ + 12411, + 12363 + ] + ], + [ + [ + 127489, + 127489 + ], + "mapped", + [ + 12467, + 12467 + ] + ], + [ + [ + 127490, + 127490 + ], + "mapped", + [ + 12469 + ] + ], + [ + [ + 127491, + 127503 + ], + "disallowed" + ], + [ + [ + 127504, + 127504 + ], + "mapped", + [ + 25163 + ] + ], + [ + [ + 127505, + 127505 + ], + "mapped", + [ + 23383 + ] + ], + [ + [ + 127506, + 127506 + ], + "mapped", + [ + 21452 + ] + ], + [ + [ + 127507, + 127507 + ], + "mapped", + [ + 12487 + ] + ], + [ + [ + 127508, + 127508 + ], + "mapped", + [ + 20108 + ] + ], + [ + [ + 127509, + 127509 + ], + "mapped", + [ + 22810 + ] + ], + [ + [ + 127510, + 127510 + ], + "mapped", + [ + 35299 + ] + ], + [ + [ + 127511, + 127511 + ], + "mapped", + [ + 22825 + ] + ], + [ + [ + 127512, + 127512 + ], + "mapped", + [ + 20132 + ] + ], + [ + [ + 127513, + 127513 + ], + "mapped", + [ + 26144 + ] + ], + [ + [ + 127514, + 127514 + ], + "mapped", + [ + 28961 + ] + ], + [ + [ + 127515, + 127515 + ], + "mapped", + [ + 26009 + ] + ], + [ + [ + 127516, + 127516 + ], + "mapped", + [ + 21069 + ] + ], + [ + [ + 127517, + 127517 + ], + "mapped", + [ + 24460 + ] + ], + [ + [ + 127518, + 127518 + ], + "mapped", + [ + 20877 + ] + ], + [ + [ + 127519, + 127519 + ], + "mapped", + [ + 26032 + ] + ], + [ + [ + 127520, + 127520 + ], + "mapped", + [ + 21021 + ] + ], + [ + [ + 127521, + 127521 + ], + "mapped", + [ + 32066 + ] + ], + [ + [ + 127522, + 127522 + ], + "mapped", + [ + 29983 + ] + ], + [ + [ + 127523, + 127523 + ], + "mapped", + [ + 36009 + ] + ], + [ + [ + 127524, + 127524 + ], + "mapped", + [ + 22768 + ] + ], + [ + [ + 127525, + 127525 + ], + "mapped", + [ + 21561 + ] + ], + [ + [ + 127526, + 127526 + ], + "mapped", + [ + 28436 + ] + ], + [ + [ + 127527, + 127527 + ], + "mapped", + [ + 25237 + ] + ], + [ + [ + 127528, + 127528 + ], + "mapped", + [ + 25429 + ] + ], + [ + [ + 127529, + 127529 + ], + "mapped", + [ + 19968 + ] + ], + [ + [ + 127530, + 127530 + ], + "mapped", + [ + 19977 + ] + ], + [ + [ + 127531, + 127531 + ], + "mapped", + [ + 36938 + ] + ], + [ + [ + 127532, + 127532 + ], + "mapped", + [ + 24038 + ] + ], + [ + [ + 127533, + 127533 + ], + "mapped", + [ + 20013 + ] + ], + [ + [ + 127534, + 127534 + ], + "mapped", + [ + 21491 + ] + ], + [ + [ + 127535, + 127535 + ], + "mapped", + [ + 25351 + ] + ], + [ + [ + 127536, + 127536 + ], + "mapped", + [ + 36208 + ] + ], + [ + [ + 127537, + 127537 + ], + "mapped", + [ + 25171 + ] + ], + [ + [ + 127538, + 127538 + ], + "mapped", + [ + 31105 + ] + ], + [ + [ + 127539, + 127539 + ], + "mapped", + [ + 31354 + ] + ], + [ + [ + 127540, + 127540 + ], + "mapped", + [ + 21512 + ] + ], + [ + [ + 127541, + 127541 + ], + "mapped", + [ + 28288 + ] + ], + [ + [ + 127542, + 127542 + ], + "mapped", + [ + 26377 + ] + ], + [ + [ + 127543, + 127543 + ], + "mapped", + [ + 26376 + ] + ], + [ + [ + 127544, + 127544 + ], + "mapped", + [ + 30003 + ] + ], + [ + [ + 127545, + 127545 + ], + "mapped", + [ + 21106 + ] + ], + [ + [ + 127546, + 127546 + ], + "mapped", + [ + 21942 + ] + ], + [ + [ + 127547, + 127551 + ], + "disallowed" + ], + [ + [ + 127552, + 127552 + ], + "mapped", + [ + 12308, + 26412, + 12309 + ] + ], + [ + [ + 127553, + 127553 + ], + "mapped", + [ + 12308, + 19977, + 12309 + ] + ], + [ + [ + 127554, + 127554 + ], + "mapped", + [ + 12308, + 20108, + 12309 + ] + ], + [ + [ + 127555, + 127555 + ], + "mapped", + [ + 12308, + 23433, + 12309 + ] + ], + [ + [ + 127556, + 127556 + ], + "mapped", + [ + 12308, + 28857, + 12309 + ] + ], + [ + [ + 127557, + 127557 + ], + "mapped", + [ + 12308, + 25171, + 12309 + ] + ], + [ + [ + 127558, + 127558 + ], + "mapped", + [ + 12308, + 30423, + 12309 + ] + ], + [ + [ + 127559, + 127559 + ], + "mapped", + [ + 12308, + 21213, + 12309 + ] + ], + [ + [ + 127560, + 127560 + ], + "mapped", + [ + 12308, + 25943, + 12309 + ] + ], + [ + [ + 127561, + 127567 + ], + "disallowed" + ], + [ + [ + 127568, + 127568 + ], + "mapped", + [ + 24471 + ] + ], + [ + [ + 127569, + 127569 + ], + "mapped", + [ + 21487 + ] + ], + [ + [ + 127570, + 127743 + ], + "disallowed" + ], + [ + [ + 127744, + 127776 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 127777, + 127788 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 127789, + 127791 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 127792, + 127797 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 127798, + 127798 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 127799, + 127868 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 127869, + 127869 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 127870, + 127871 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 127872, + 127891 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 127892, + 127903 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 127904, + 127940 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 127941, + 127941 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 127942, + 127946 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 127947, + 127950 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 127951, + 127955 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 127956, + 127967 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 127968, + 127984 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 127985, + 127991 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 127992, + 127999 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 128000, + 128062 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 128063, + 128063 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 128064, + 128064 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 128065, + 128065 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 128066, + 128247 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 128248, + 128248 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 128249, + 128252 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 128253, + 128254 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 128255, + 128255 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 128256, + 128317 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 128318, + 128319 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 128320, + 128323 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 128324, + 128330 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 128331, + 128335 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 128336, + 128359 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 128360, + 128377 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 128378, + 128378 + ], + "disallowed" + ], + [ + [ + 128379, + 128419 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 128420, + 128420 + ], + "disallowed" + ], + [ + [ + 128421, + 128506 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 128507, + 128511 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 128512, + 128512 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 128513, + 128528 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 128529, + 128529 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 128530, + 128532 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 128533, + 128533 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 128534, + 128534 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 128535, + 128535 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 128536, + 128536 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 128537, + 128537 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 128538, + 128538 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 128539, + 128539 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 128540, + 128542 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 128543, + 128543 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 128544, + 128549 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 128550, + 128551 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 128552, + 128555 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 128556, + 128556 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 128557, + 128557 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 128558, + 128559 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 128560, + 128563 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 128564, + 128564 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 128565, + 128576 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 128577, + 128578 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 128579, + 128580 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 128581, + 128591 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 128592, + 128639 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 128640, + 128709 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 128710, + 128719 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 128720, + 128720 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 128721, + 128735 + ], + "disallowed" + ], + [ + [ + 128736, + 128748 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 128749, + 128751 + ], + "disallowed" + ], + [ + [ + 128752, + 128755 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 128756, + 128767 + ], + "disallowed" + ], + [ + [ + 128768, + 128883 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 128884, + 128895 + ], + "disallowed" + ], + [ + [ + 128896, + 128980 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 128981, + 129023 + ], + "disallowed" + ], + [ + [ + 129024, + 129035 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 129036, + 129039 + ], + "disallowed" + ], + [ + [ + 129040, + 129095 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 129096, + 129103 + ], + "disallowed" + ], + [ + [ + 129104, + 129113 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 129114, + 129119 + ], + "disallowed" + ], + [ + [ + 129120, + 129159 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 129160, + 129167 + ], + "disallowed" + ], + [ + [ + 129168, + 129197 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 129198, + 129295 + ], + "disallowed" + ], + [ + [ + 129296, + 129304 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 129305, + 129407 + ], + "disallowed" + ], + [ + [ + 129408, + 129412 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 129413, + 129471 + ], + "disallowed" + ], + [ + [ + 129472, + 129472 + ], + "valid", + [ + ], + "NV8" + ], + [ + [ + 129473, + 131069 + ], + "disallowed" + ], + [ + [ + 131070, + 131071 + ], + "disallowed" + ], + [ + [ + 131072, + 173782 + ], + "valid" + ], + [ + [ + 173783, + 173823 + ], + "disallowed" + ], + [ + [ + 173824, + 177972 + ], + "valid" + ], + [ + [ + 177973, + 177983 + ], + "disallowed" + ], + [ + [ + 177984, + 178205 + ], + "valid" + ], + [ + [ + 178206, + 178207 + ], + "disallowed" + ], + [ + [ + 178208, + 183969 + ], + "valid" + ], + [ + [ + 183970, + 194559 + ], + "disallowed" + ], + [ + [ + 194560, + 194560 + ], + "mapped", + [ + 20029 + ] + ], + [ + [ + 194561, + 194561 + ], + "mapped", + [ + 20024 + ] + ], + [ + [ + 194562, + 194562 + ], + "mapped", + [ + 20033 + ] + ], + [ + [ + 194563, + 194563 + ], + "mapped", + [ + 131362 + ] + ], + [ + [ + 194564, + 194564 + ], + "mapped", + [ + 20320 + ] + ], + [ + [ + 194565, + 194565 + ], + "mapped", + [ + 20398 + ] + ], + [ + [ + 194566, + 194566 + ], + "mapped", + [ + 20411 + ] + ], + [ + [ + 194567, + 194567 + ], + "mapped", + [ + 20482 + ] + ], + [ + [ + 194568, + 194568 + ], + "mapped", + [ + 20602 + ] + ], + [ + [ + 194569, + 194569 + ], + "mapped", + [ + 20633 + ] + ], + [ + [ + 194570, + 194570 + ], + "mapped", + [ + 20711 + ] + ], + [ + [ + 194571, + 194571 + ], + "mapped", + [ + 20687 + ] + ], + [ + [ + 194572, + 194572 + ], + "mapped", + [ + 13470 + ] + ], + [ + [ + 194573, + 194573 + ], + "mapped", + [ + 132666 + ] + ], + [ + [ + 194574, + 194574 + ], + "mapped", + [ + 20813 + ] + ], + [ + [ + 194575, + 194575 + ], + "mapped", + [ + 20820 + ] + ], + [ + [ + 194576, + 194576 + ], + "mapped", + [ + 20836 + ] + ], + [ + [ + 194577, + 194577 + ], + "mapped", + [ + 20855 + ] + ], + [ + [ + 194578, + 194578 + ], + "mapped", + [ + 132380 + ] + ], + [ + [ + 194579, + 194579 + ], + "mapped", + [ + 13497 + ] + ], + [ + [ + 194580, + 194580 + ], + "mapped", + [ + 20839 + ] + ], + [ + [ + 194581, + 194581 + ], + "mapped", + [ + 20877 + ] + ], + [ + [ + 194582, + 194582 + ], + "mapped", + [ + 132427 + ] + ], + [ + [ + 194583, + 194583 + ], + "mapped", + [ + 20887 + ] + ], + [ + [ + 194584, + 194584 + ], + "mapped", + [ + 20900 + ] + ], + [ + [ + 194585, + 194585 + ], + "mapped", + [ + 20172 + ] + ], + [ + [ + 194586, + 194586 + ], + "mapped", + [ + 20908 + ] + ], + [ + [ + 194587, + 194587 + ], + "mapped", + [ + 20917 + ] + ], + [ + [ + 194588, + 194588 + ], + "mapped", + [ + 168415 + ] + ], + [ + [ + 194589, + 194589 + ], + "mapped", + [ + 20981 + ] + ], + [ + [ + 194590, + 194590 + ], + "mapped", + [ + 20995 + ] + ], + [ + [ + 194591, + 194591 + ], + "mapped", + [ + 13535 + ] + ], + [ + [ + 194592, + 194592 + ], + "mapped", + [ + 21051 + ] + ], + [ + [ + 194593, + 194593 + ], + "mapped", + [ + 21062 + ] + ], + [ + [ + 194594, + 194594 + ], + "mapped", + [ + 21106 + ] + ], + [ + [ + 194595, + 194595 + ], + "mapped", + [ + 21111 + ] + ], + [ + [ + 194596, + 194596 + ], + "mapped", + [ + 13589 + ] + ], + [ + [ + 194597, + 194597 + ], + "mapped", + [ + 21191 + ] + ], + [ + [ + 194598, + 194598 + ], + "mapped", + [ + 21193 + ] + ], + [ + [ + 194599, + 194599 + ], + "mapped", + [ + 21220 + ] + ], + [ + [ + 194600, + 194600 + ], + "mapped", + [ + 21242 + ] + ], + [ + [ + 194601, + 194601 + ], + "mapped", + [ + 21253 + ] + ], + [ + [ + 194602, + 194602 + ], + "mapped", + [ + 21254 + ] + ], + [ + [ + 194603, + 194603 + ], + "mapped", + [ + 21271 + ] + ], + [ + [ + 194604, + 194604 + ], + "mapped", + [ + 21321 + ] + ], + [ + [ + 194605, + 194605 + ], + "mapped", + [ + 21329 + ] + ], + [ + [ + 194606, + 194606 + ], + "mapped", + [ + 21338 + ] + ], + [ + [ + 194607, + 194607 + ], + "mapped", + [ + 21363 + ] + ], + [ + [ + 194608, + 194608 + ], + "mapped", + [ + 21373 + ] + ], + [ + [ + 194609, + 194611 + ], + "mapped", + [ + 21375 + ] + ], + [ + [ + 194612, + 194612 + ], + "mapped", + [ + 133676 + ] + ], + [ + [ + 194613, + 194613 + ], + "mapped", + [ + 28784 + ] + ], + [ + [ + 194614, + 194614 + ], + "mapped", + [ + 21450 + ] + ], + [ + [ + 194615, + 194615 + ], + "mapped", + [ + 21471 + ] + ], + [ + [ + 194616, + 194616 + ], + "mapped", + [ + 133987 + ] + ], + [ + [ + 194617, + 194617 + ], + "mapped", + [ + 21483 + ] + ], + [ + [ + 194618, + 194618 + ], + "mapped", + [ + 21489 + ] + ], + [ + [ + 194619, + 194619 + ], + "mapped", + [ + 21510 + ] + ], + [ + [ + 194620, + 194620 + ], + "mapped", + [ + 21662 + ] + ], + [ + [ + 194621, + 194621 + ], + "mapped", + [ + 21560 + ] + ], + [ + [ + 194622, + 194622 + ], + "mapped", + [ + 21576 + ] + ], + [ + [ + 194623, + 194623 + ], + "mapped", + [ + 21608 + ] + ], + [ + [ + 194624, + 194624 + ], + "mapped", + [ + 21666 + ] + ], + [ + [ + 194625, + 194625 + ], + "mapped", + [ + 21750 + ] + ], + [ + [ + 194626, + 194626 + ], + "mapped", + [ + 21776 + ] + ], + [ + [ + 194627, + 194627 + ], + "mapped", + [ + 21843 + ] + ], + [ + [ + 194628, + 194628 + ], + "mapped", + [ + 21859 + ] + ], + [ + [ + 194629, + 194630 + ], + "mapped", + [ + 21892 + ] + ], + [ + [ + 194631, + 194631 + ], + "mapped", + [ + 21913 + ] + ], + [ + [ + 194632, + 194632 + ], + "mapped", + [ + 21931 + ] + ], + [ + [ + 194633, + 194633 + ], + "mapped", + [ + 21939 + ] + ], + [ + [ + 194634, + 194634 + ], + "mapped", + [ + 21954 + ] + ], + [ + [ + 194635, + 194635 + ], + "mapped", + [ + 22294 + ] + ], + [ + [ + 194636, + 194636 + ], + "mapped", + [ + 22022 + ] + ], + [ + [ + 194637, + 194637 + ], + "mapped", + [ + 22295 + ] + ], + [ + [ + 194638, + 194638 + ], + "mapped", + [ + 22097 + ] + ], + [ + [ + 194639, + 194639 + ], + "mapped", + [ + 22132 + ] + ], + [ + [ + 194640, + 194640 + ], + "mapped", + [ + 20999 + ] + ], + [ + [ + 194641, + 194641 + ], + "mapped", + [ + 22766 + ] + ], + [ + [ + 194642, + 194642 + ], + "mapped", + [ + 22478 + ] + ], + [ + [ + 194643, + 194643 + ], + "mapped", + [ + 22516 + ] + ], + [ + [ + 194644, + 194644 + ], + "mapped", + [ + 22541 + ] + ], + [ + [ + 194645, + 194645 + ], + "mapped", + [ + 22411 + ] + ], + [ + [ + 194646, + 194646 + ], + "mapped", + [ + 22578 + ] + ], + [ + [ + 194647, + 194647 + ], + "mapped", + [ + 22577 + ] + ], + [ + [ + 194648, + 194648 + ], + "mapped", + [ + 22700 + ] + ], + [ + [ + 194649, + 194649 + ], + "mapped", + [ + 136420 + ] + ], + [ + [ + 194650, + 194650 + ], + "mapped", + [ + 22770 + ] + ], + [ + [ + 194651, + 194651 + ], + "mapped", + [ + 22775 + ] + ], + [ + [ + 194652, + 194652 + ], + "mapped", + [ + 22790 + ] + ], + [ + [ + 194653, + 194653 + ], + "mapped", + [ + 22810 + ] + ], + [ + [ + 194654, + 194654 + ], + "mapped", + [ + 22818 + ] + ], + [ + [ + 194655, + 194655 + ], + "mapped", + [ + 22882 + ] + ], + [ + [ + 194656, + 194656 + ], + "mapped", + [ + 136872 + ] + ], + [ + [ + 194657, + 194657 + ], + "mapped", + [ + 136938 + ] + ], + [ + [ + 194658, + 194658 + ], + "mapped", + [ + 23020 + ] + ], + [ + [ + 194659, + 194659 + ], + "mapped", + [ + 23067 + ] + ], + [ + [ + 194660, + 194660 + ], + "mapped", + [ + 23079 + ] + ], + [ + [ + 194661, + 194661 + ], + "mapped", + [ + 23000 + ] + ], + [ + [ + 194662, + 194662 + ], + "mapped", + [ + 23142 + ] + ], + [ + [ + 194663, + 194663 + ], + "mapped", + [ + 14062 + ] + ], + [ + [ + 194664, + 194664 + ], + "disallowed" + ], + [ + [ + 194665, + 194665 + ], + "mapped", + [ + 23304 + ] + ], + [ + [ + 194666, + 194667 + ], + "mapped", + [ + 23358 + ] + ], + [ + [ + 194668, + 194668 + ], + "mapped", + [ + 137672 + ] + ], + [ + [ + 194669, + 194669 + ], + "mapped", + [ + 23491 + ] + ], + [ + [ + 194670, + 194670 + ], + "mapped", + [ + 23512 + ] + ], + [ + [ + 194671, + 194671 + ], + "mapped", + [ + 23527 + ] + ], + [ + [ + 194672, + 194672 + ], + "mapped", + [ + 23539 + ] + ], + [ + [ + 194673, + 194673 + ], + "mapped", + [ + 138008 + ] + ], + [ + [ + 194674, + 194674 + ], + "mapped", + [ + 23551 + ] + ], + [ + [ + 194675, + 194675 + ], + "mapped", + [ + 23558 + ] + ], + [ + [ + 194676, + 194676 + ], + "disallowed" + ], + [ + [ + 194677, + 194677 + ], + "mapped", + [ + 23586 + ] + ], + [ + [ + 194678, + 194678 + ], + "mapped", + [ + 14209 + ] + ], + [ + [ + 194679, + 194679 + ], + "mapped", + [ + 23648 + ] + ], + [ + [ + 194680, + 194680 + ], + "mapped", + [ + 23662 + ] + ], + [ + [ + 194681, + 194681 + ], + "mapped", + [ + 23744 + ] + ], + [ + [ + 194682, + 194682 + ], + "mapped", + [ + 23693 + ] + ], + [ + [ + 194683, + 194683 + ], + "mapped", + [ + 138724 + ] + ], + [ + [ + 194684, + 194684 + ], + "mapped", + [ + 23875 + ] + ], + [ + [ + 194685, + 194685 + ], + "mapped", + [ + 138726 + ] + ], + [ + [ + 194686, + 194686 + ], + "mapped", + [ + 23918 + ] + ], + [ + [ + 194687, + 194687 + ], + "mapped", + [ + 23915 + ] + ], + [ + [ + 194688, + 194688 + ], + "mapped", + [ + 23932 + ] + ], + [ + [ + 194689, + 194689 + ], + "mapped", + [ + 24033 + ] + ], + [ + [ + 194690, + 194690 + ], + "mapped", + [ + 24034 + ] + ], + [ + [ + 194691, + 194691 + ], + "mapped", + [ + 14383 + ] + ], + [ + [ + 194692, + 194692 + ], + "mapped", + [ + 24061 + ] + ], + [ + [ + 194693, + 194693 + ], + "mapped", + [ + 24104 + ] + ], + [ + [ + 194694, + 194694 + ], + "mapped", + [ + 24125 + ] + ], + [ + [ + 194695, + 194695 + ], + "mapped", + [ + 24169 + ] + ], + [ + [ + 194696, + 194696 + ], + "mapped", + [ + 14434 + ] + ], + [ + [ + 194697, + 194697 + ], + "mapped", + [ + 139651 + ] + ], + [ + [ + 194698, + 194698 + ], + "mapped", + [ + 14460 + ] + ], + [ + [ + 194699, + 194699 + ], + "mapped", + [ + 24240 + ] + ], + [ + [ + 194700, + 194700 + ], + "mapped", + [ + 24243 + ] + ], + [ + [ + 194701, + 194701 + ], + "mapped", + [ + 24246 + ] + ], + [ + [ + 194702, + 194702 + ], + "mapped", + [ + 24266 + ] + ], + [ + [ + 194703, + 194703 + ], + "mapped", + [ + 172946 + ] + ], + [ + [ + 194704, + 194704 + ], + "mapped", + [ + 24318 + ] + ], + [ + [ + 194705, + 194706 + ], + "mapped", + [ + 140081 + ] + ], + [ + [ + 194707, + 194707 + ], + "mapped", + [ + 33281 + ] + ], + [ + [ + 194708, + 194709 + ], + "mapped", + [ + 24354 + ] + ], + [ + [ + 194710, + 194710 + ], + "mapped", + [ + 14535 + ] + ], + [ + [ + 194711, + 194711 + ], + "mapped", + [ + 144056 + ] + ], + [ + [ + 194712, + 194712 + ], + "mapped", + [ + 156122 + ] + ], + [ + [ + 194713, + 194713 + ], + "mapped", + [ + 24418 + ] + ], + [ + [ + 194714, + 194714 + ], + "mapped", + [ + 24427 + ] + ], + [ + [ + 194715, + 194715 + ], + "mapped", + [ + 14563 + ] + ], + [ + [ + 194716, + 194716 + ], + "mapped", + [ + 24474 + ] + ], + [ + [ + 194717, + 194717 + ], + "mapped", + [ + 24525 + ] + ], + [ + [ + 194718, + 194718 + ], + "mapped", + [ + 24535 + ] + ], + [ + [ + 194719, + 194719 + ], + "mapped", + [ + 24569 + ] + ], + [ + [ + 194720, + 194720 + ], + "mapped", + [ + 24705 + ] + ], + [ + [ + 194721, + 194721 + ], + "mapped", + [ + 14650 + ] + ], + [ + [ + 194722, + 194722 + ], + "mapped", + [ + 14620 + ] + ], + [ + [ + 194723, + 194723 + ], + "mapped", + [ + 24724 + ] + ], + [ + [ + 194724, + 194724 + ], + "mapped", + [ + 141012 + ] + ], + [ + [ + 194725, + 194725 + ], + "mapped", + [ + 24775 + ] + ], + [ + [ + 194726, + 194726 + ], + "mapped", + [ + 24904 + ] + ], + [ + [ + 194727, + 194727 + ], + "mapped", + [ + 24908 + ] + ], + [ + [ + 194728, + 194728 + ], + "mapped", + [ + 24910 + ] + ], + [ + [ + 194729, + 194729 + ], + "mapped", + [ + 24908 + ] + ], + [ + [ + 194730, + 194730 + ], + "mapped", + [ + 24954 + ] + ], + [ + [ + 194731, + 194731 + ], + "mapped", + [ + 24974 + ] + ], + [ + [ + 194732, + 194732 + ], + "mapped", + [ + 25010 + ] + ], + [ + [ + 194733, + 194733 + ], + "mapped", + [ + 24996 + ] + ], + [ + [ + 194734, + 194734 + ], + "mapped", + [ + 25007 + ] + ], + [ + [ + 194735, + 194735 + ], + "mapped", + [ + 25054 + ] + ], + [ + [ + 194736, + 194736 + ], + "mapped", + [ + 25074 + ] + ], + [ + [ + 194737, + 194737 + ], + "mapped", + [ + 25078 + ] + ], + [ + [ + 194738, + 194738 + ], + "mapped", + [ + 25104 + ] + ], + [ + [ + 194739, + 194739 + ], + "mapped", + [ + 25115 + ] + ], + [ + [ + 194740, + 194740 + ], + "mapped", + [ + 25181 + ] + ], + [ + [ + 194741, + 194741 + ], + "mapped", + [ + 25265 + ] + ], + [ + [ + 194742, + 194742 + ], + "mapped", + [ + 25300 + ] + ], + [ + [ + 194743, + 194743 + ], + "mapped", + [ + 25424 + ] + ], + [ + [ + 194744, + 194744 + ], + "mapped", + [ + 142092 + ] + ], + [ + [ + 194745, + 194745 + ], + "mapped", + [ + 25405 + ] + ], + [ + [ + 194746, + 194746 + ], + "mapped", + [ + 25340 + ] + ], + [ + [ + 194747, + 194747 + ], + "mapped", + [ + 25448 + ] + ], + [ + [ + 194748, + 194748 + ], + "mapped", + [ + 25475 + ] + ], + [ + [ + 194749, + 194749 + ], + "mapped", + [ + 25572 + ] + ], + [ + [ + 194750, + 194750 + ], + "mapped", + [ + 142321 + ] + ], + [ + [ + 194751, + 194751 + ], + "mapped", + [ + 25634 + ] + ], + [ + [ + 194752, + 194752 + ], + "mapped", + [ + 25541 + ] + ], + [ + [ + 194753, + 194753 + ], + "mapped", + [ + 25513 + ] + ], + [ + [ + 194754, + 194754 + ], + "mapped", + [ + 14894 + ] + ], + [ + [ + 194755, + 194755 + ], + "mapped", + [ + 25705 + ] + ], + [ + [ + 194756, + 194756 + ], + "mapped", + [ + 25726 + ] + ], + [ + [ + 194757, + 194757 + ], + "mapped", + [ + 25757 + ] + ], + [ + [ + 194758, + 194758 + ], + "mapped", + [ + 25719 + ] + ], + [ + [ + 194759, + 194759 + ], + "mapped", + [ + 14956 + ] + ], + [ + [ + 194760, + 194760 + ], + "mapped", + [ + 25935 + ] + ], + [ + [ + 194761, + 194761 + ], + "mapped", + [ + 25964 + ] + ], + [ + [ + 194762, + 194762 + ], + "mapped", + [ + 143370 + ] + ], + [ + [ + 194763, + 194763 + ], + "mapped", + [ + 26083 + ] + ], + [ + [ + 194764, + 194764 + ], + "mapped", + [ + 26360 + ] + ], + [ + [ + 194765, + 194765 + ], + "mapped", + [ + 26185 + ] + ], + [ + [ + 194766, + 194766 + ], + "mapped", + [ + 15129 + ] + ], + [ + [ + 194767, + 194767 + ], + "mapped", + [ + 26257 + ] + ], + [ + [ + 194768, + 194768 + ], + "mapped", + [ + 15112 + ] + ], + [ + [ + 194769, + 194769 + ], + "mapped", + [ + 15076 + ] + ], + [ + [ + 194770, + 194770 + ], + "mapped", + [ + 20882 + ] + ], + [ + [ + 194771, + 194771 + ], + "mapped", + [ + 20885 + ] + ], + [ + [ + 194772, + 194772 + ], + "mapped", + [ + 26368 + ] + ], + [ + [ + 194773, + 194773 + ], + "mapped", + [ + 26268 + ] + ], + [ + [ + 194774, + 194774 + ], + "mapped", + [ + 32941 + ] + ], + [ + [ + 194775, + 194775 + ], + "mapped", + [ + 17369 + ] + ], + [ + [ + 194776, + 194776 + ], + "mapped", + [ + 26391 + ] + ], + [ + [ + 194777, + 194777 + ], + "mapped", + [ + 26395 + ] + ], + [ + [ + 194778, + 194778 + ], + "mapped", + [ + 26401 + ] + ], + [ + [ + 194779, + 194779 + ], + "mapped", + [ + 26462 + ] + ], + [ + [ + 194780, + 194780 + ], + "mapped", + [ + 26451 + ] + ], + [ + [ + 194781, + 194781 + ], + "mapped", + [ + 144323 + ] + ], + [ + [ + 194782, + 194782 + ], + "mapped", + [ + 15177 + ] + ], + [ + [ + 194783, + 194783 + ], + "mapped", + [ + 26618 + ] + ], + [ + [ + 194784, + 194784 + ], + "mapped", + [ + 26501 + ] + ], + [ + [ + 194785, + 194785 + ], + "mapped", + [ + 26706 + ] + ], + [ + [ + 194786, + 194786 + ], + "mapped", + [ + 26757 + ] + ], + [ + [ + 194787, + 194787 + ], + "mapped", + [ + 144493 + ] + ], + [ + [ + 194788, + 194788 + ], + "mapped", + [ + 26766 + ] + ], + [ + [ + 194789, + 194789 + ], + "mapped", + [ + 26655 + ] + ], + [ + [ + 194790, + 194790 + ], + "mapped", + [ + 26900 + ] + ], + [ + [ + 194791, + 194791 + ], + "mapped", + [ + 15261 + ] + ], + [ + [ + 194792, + 194792 + ], + "mapped", + [ + 26946 + ] + ], + [ + [ + 194793, + 194793 + ], + "mapped", + [ + 27043 + ] + ], + [ + [ + 194794, + 194794 + ], + "mapped", + [ + 27114 + ] + ], + [ + [ + 194795, + 194795 + ], + "mapped", + [ + 27304 + ] + ], + [ + [ + 194796, + 194796 + ], + "mapped", + [ + 145059 + ] + ], + [ + [ + 194797, + 194797 + ], + "mapped", + [ + 27355 + ] + ], + [ + [ + 194798, + 194798 + ], + "mapped", + [ + 15384 + ] + ], + [ + [ + 194799, + 194799 + ], + "mapped", + [ + 27425 + ] + ], + [ + [ + 194800, + 194800 + ], + "mapped", + [ + 145575 + ] + ], + [ + [ + 194801, + 194801 + ], + "mapped", + [ + 27476 + ] + ], + [ + [ + 194802, + 194802 + ], + "mapped", + [ + 15438 + ] + ], + [ + [ + 194803, + 194803 + ], + "mapped", + [ + 27506 + ] + ], + [ + [ + 194804, + 194804 + ], + "mapped", + [ + 27551 + ] + ], + [ + [ + 194805, + 194805 + ], + "mapped", + [ + 27578 + ] + ], + [ + [ + 194806, + 194806 + ], + "mapped", + [ + 27579 + ] + ], + [ + [ + 194807, + 194807 + ], + "mapped", + [ + 146061 + ] + ], + [ + [ + 194808, + 194808 + ], + "mapped", + [ + 138507 + ] + ], + [ + [ + 194809, + 194809 + ], + "mapped", + [ + 146170 + ] + ], + [ + [ + 194810, + 194810 + ], + "mapped", + [ + 27726 + ] + ], + [ + [ + 194811, + 194811 + ], + "mapped", + [ + 146620 + ] + ], + [ + [ + 194812, + 194812 + ], + "mapped", + [ + 27839 + ] + ], + [ + [ + 194813, + 194813 + ], + "mapped", + [ + 27853 + ] + ], + [ + [ + 194814, + 194814 + ], + "mapped", + [ + 27751 + ] + ], + [ + [ + 194815, + 194815 + ], + "mapped", + [ + 27926 + ] + ], + [ + [ + 194816, + 194816 + ], + "mapped", + [ + 27966 + ] + ], + [ + [ + 194817, + 194817 + ], + "mapped", + [ + 28023 + ] + ], + [ + [ + 194818, + 194818 + ], + "mapped", + [ + 27969 + ] + ], + [ + [ + 194819, + 194819 + ], + "mapped", + [ + 28009 + ] + ], + [ + [ + 194820, + 194820 + ], + "mapped", + [ + 28024 + ] + ], + [ + [ + 194821, + 194821 + ], + "mapped", + [ + 28037 + ] + ], + [ + [ + 194822, + 194822 + ], + "mapped", + [ + 146718 + ] + ], + [ + [ + 194823, + 194823 + ], + "mapped", + [ + 27956 + ] + ], + [ + [ + 194824, + 194824 + ], + "mapped", + [ + 28207 + ] + ], + [ + [ + 194825, + 194825 + ], + "mapped", + [ + 28270 + ] + ], + [ + [ + 194826, + 194826 + ], + "mapped", + [ + 15667 + ] + ], + [ + [ + 194827, + 194827 + ], + "mapped", + [ + 28363 + ] + ], + [ + [ + 194828, + 194828 + ], + "mapped", + [ + 28359 + ] + ], + [ + [ + 194829, + 194829 + ], + "mapped", + [ + 147153 + ] + ], + [ + [ + 194830, + 194830 + ], + "mapped", + [ + 28153 + ] + ], + [ + [ + 194831, + 194831 + ], + "mapped", + [ + 28526 + ] + ], + [ + [ + 194832, + 194832 + ], + "mapped", + [ + 147294 + ] + ], + [ + [ + 194833, + 194833 + ], + "mapped", + [ + 147342 + ] + ], + [ + [ + 194834, + 194834 + ], + "mapped", + [ + 28614 + ] + ], + [ + [ + 194835, + 194835 + ], + "mapped", + [ + 28729 + ] + ], + [ + [ + 194836, + 194836 + ], + "mapped", + [ + 28702 + ] + ], + [ + [ + 194837, + 194837 + ], + "mapped", + [ + 28699 + ] + ], + [ + [ + 194838, + 194838 + ], + "mapped", + [ + 15766 + ] + ], + [ + [ + 194839, + 194839 + ], + "mapped", + [ + 28746 + ] + ], + [ + [ + 194840, + 194840 + ], + "mapped", + [ + 28797 + ] + ], + [ + [ + 194841, + 194841 + ], + "mapped", + [ + 28791 + ] + ], + [ + [ + 194842, + 194842 + ], + "mapped", + [ + 28845 + ] + ], + [ + [ + 194843, + 194843 + ], + "mapped", + [ + 132389 + ] + ], + [ + [ + 194844, + 194844 + ], + "mapped", + [ + 28997 + ] + ], + [ + [ + 194845, + 194845 + ], + "mapped", + [ + 148067 + ] + ], + [ + [ + 194846, + 194846 + ], + "mapped", + [ + 29084 + ] + ], + [ + [ + 194847, + 194847 + ], + "disallowed" + ], + [ + [ + 194848, + 194848 + ], + "mapped", + [ + 29224 + ] + ], + [ + [ + 194849, + 194849 + ], + "mapped", + [ + 29237 + ] + ], + [ + [ + 194850, + 194850 + ], + "mapped", + [ + 29264 + ] + ], + [ + [ + 194851, + 194851 + ], + "mapped", + [ + 149000 + ] + ], + [ + [ + 194852, + 194852 + ], + "mapped", + [ + 29312 + ] + ], + [ + [ + 194853, + 194853 + ], + "mapped", + [ + 29333 + ] + ], + [ + [ + 194854, + 194854 + ], + "mapped", + [ + 149301 + ] + ], + [ + [ + 194855, + 194855 + ], + "mapped", + [ + 149524 + ] + ], + [ + [ + 194856, + 194856 + ], + "mapped", + [ + 29562 + ] + ], + [ + [ + 194857, + 194857 + ], + "mapped", + [ + 29579 + ] + ], + [ + [ + 194858, + 194858 + ], + "mapped", + [ + 16044 + ] + ], + [ + [ + 194859, + 194859 + ], + "mapped", + [ + 29605 + ] + ], + [ + [ + 194860, + 194861 + ], + "mapped", + [ + 16056 + ] + ], + [ + [ + 194862, + 194862 + ], + "mapped", + [ + 29767 + ] + ], + [ + [ + 194863, + 194863 + ], + "mapped", + [ + 29788 + ] + ], + [ + [ + 194864, + 194864 + ], + "mapped", + [ + 29809 + ] + ], + [ + [ + 194865, + 194865 + ], + "mapped", + [ + 29829 + ] + ], + [ + [ + 194866, + 194866 + ], + "mapped", + [ + 29898 + ] + ], + [ + [ + 194867, + 194867 + ], + "mapped", + [ + 16155 + ] + ], + [ + [ + 194868, + 194868 + ], + "mapped", + [ + 29988 + ] + ], + [ + [ + 194869, + 194869 + ], + "mapped", + [ + 150582 + ] + ], + [ + [ + 194870, + 194870 + ], + "mapped", + [ + 30014 + ] + ], + [ + [ + 194871, + 194871 + ], + "mapped", + [ + 150674 + ] + ], + [ + [ + 194872, + 194872 + ], + "mapped", + [ + 30064 + ] + ], + [ + [ + 194873, + 194873 + ], + "mapped", + [ + 139679 + ] + ], + [ + [ + 194874, + 194874 + ], + "mapped", + [ + 30224 + ] + ], + [ + [ + 194875, + 194875 + ], + "mapped", + [ + 151457 + ] + ], + [ + [ + 194876, + 194876 + ], + "mapped", + [ + 151480 + ] + ], + [ + [ + 194877, + 194877 + ], + "mapped", + [ + 151620 + ] + ], + [ + [ + 194878, + 194878 + ], + "mapped", + [ + 16380 + ] + ], + [ + [ + 194879, + 194879 + ], + "mapped", + [ + 16392 + ] + ], + [ + [ + 194880, + 194880 + ], + "mapped", + [ + 30452 + ] + ], + [ + [ + 194881, + 194881 + ], + "mapped", + [ + 151795 + ] + ], + [ + [ + 194882, + 194882 + ], + "mapped", + [ + 151794 + ] + ], + [ + [ + 194883, + 194883 + ], + "mapped", + [ + 151833 + ] + ], + [ + [ + 194884, + 194884 + ], + "mapped", + [ + 151859 + ] + ], + [ + [ + 194885, + 194885 + ], + "mapped", + [ + 30494 + ] + ], + [ + [ + 194886, + 194887 + ], + "mapped", + [ + 30495 + ] + ], + [ + [ + 194888, + 194888 + ], + "mapped", + [ + 30538 + ] + ], + [ + [ + 194889, + 194889 + ], + "mapped", + [ + 16441 + ] + ], + [ + [ + 194890, + 194890 + ], + "mapped", + [ + 30603 + ] + ], + [ + [ + 194891, + 194891 + ], + "mapped", + [ + 16454 + ] + ], + [ + [ + 194892, + 194892 + ], + "mapped", + [ + 16534 + ] + ], + [ + [ + 194893, + 194893 + ], + "mapped", + [ + 152605 + ] + ], + [ + [ + 194894, + 194894 + ], + "mapped", + [ + 30798 + ] + ], + [ + [ + 194895, + 194895 + ], + "mapped", + [ + 30860 + ] + ], + [ + [ + 194896, + 194896 + ], + "mapped", + [ + 30924 + ] + ], + [ + [ + 194897, + 194897 + ], + "mapped", + [ + 16611 + ] + ], + [ + [ + 194898, + 194898 + ], + "mapped", + [ + 153126 + ] + ], + [ + [ + 194899, + 194899 + ], + "mapped", + [ + 31062 + ] + ], + [ + [ + 194900, + 194900 + ], + "mapped", + [ + 153242 + ] + ], + [ + [ + 194901, + 194901 + ], + "mapped", + [ + 153285 + ] + ], + [ + [ + 194902, + 194902 + ], + "mapped", + [ + 31119 + ] + ], + [ + [ + 194903, + 194903 + ], + "mapped", + [ + 31211 + ] + ], + [ + [ + 194904, + 194904 + ], + "mapped", + [ + 16687 + ] + ], + [ + [ + 194905, + 194905 + ], + "mapped", + [ + 31296 + ] + ], + [ + [ + 194906, + 194906 + ], + "mapped", + [ + 31306 + ] + ], + [ + [ + 194907, + 194907 + ], + "mapped", + [ + 31311 + ] + ], + [ + [ + 194908, + 194908 + ], + "mapped", + [ + 153980 + ] + ], + [ + [ + 194909, + 194910 + ], + "mapped", + [ + 154279 + ] + ], + [ + [ + 194911, + 194911 + ], + "disallowed" + ], + [ + [ + 194912, + 194912 + ], + "mapped", + [ + 16898 + ] + ], + [ + [ + 194913, + 194913 + ], + "mapped", + [ + 154539 + ] + ], + [ + [ + 194914, + 194914 + ], + "mapped", + [ + 31686 + ] + ], + [ + [ + 194915, + 194915 + ], + "mapped", + [ + 31689 + ] + ], + [ + [ + 194916, + 194916 + ], + "mapped", + [ + 16935 + ] + ], + [ + [ + 194917, + 194917 + ], + "mapped", + [ + 154752 + ] + ], + [ + [ + 194918, + 194918 + ], + "mapped", + [ + 31954 + ] + ], + [ + [ + 194919, + 194919 + ], + "mapped", + [ + 17056 + ] + ], + [ + [ + 194920, + 194920 + ], + "mapped", + [ + 31976 + ] + ], + [ + [ + 194921, + 194921 + ], + "mapped", + [ + 31971 + ] + ], + [ + [ + 194922, + 194922 + ], + "mapped", + [ + 32000 + ] + ], + [ + [ + 194923, + 194923 + ], + "mapped", + [ + 155526 + ] + ], + [ + [ + 194924, + 194924 + ], + "mapped", + [ + 32099 + ] + ], + [ + [ + 194925, + 194925 + ], + "mapped", + [ + 17153 + ] + ], + [ + [ + 194926, + 194926 + ], + "mapped", + [ + 32199 + ] + ], + [ + [ + 194927, + 194927 + ], + "mapped", + [ + 32258 + ] + ], + [ + [ + 194928, + 194928 + ], + "mapped", + [ + 32325 + ] + ], + [ + [ + 194929, + 194929 + ], + "mapped", + [ + 17204 + ] + ], + [ + [ + 194930, + 194930 + ], + "mapped", + [ + 156200 + ] + ], + [ + [ + 194931, + 194931 + ], + "mapped", + [ + 156231 + ] + ], + [ + [ + 194932, + 194932 + ], + "mapped", + [ + 17241 + ] + ], + [ + [ + 194933, + 194933 + ], + "mapped", + [ + 156377 + ] + ], + [ + [ + 194934, + 194934 + ], + "mapped", + [ + 32634 + ] + ], + [ + [ + 194935, + 194935 + ], + "mapped", + [ + 156478 + ] + ], + [ + [ + 194936, + 194936 + ], + "mapped", + [ + 32661 + ] + ], + [ + [ + 194937, + 194937 + ], + "mapped", + [ + 32762 + ] + ], + [ + [ + 194938, + 194938 + ], + "mapped", + [ + 32773 + ] + ], + [ + [ + 194939, + 194939 + ], + "mapped", + [ + 156890 + ] + ], + [ + [ + 194940, + 194940 + ], + "mapped", + [ + 156963 + ] + ], + [ + [ + 194941, + 194941 + ], + "mapped", + [ + 32864 + ] + ], + [ + [ + 194942, + 194942 + ], + "mapped", + [ + 157096 + ] + ], + [ + [ + 194943, + 194943 + ], + "mapped", + [ + 32880 + ] + ], + [ + [ + 194944, + 194944 + ], + "mapped", + [ + 144223 + ] + ], + [ + [ + 194945, + 194945 + ], + "mapped", + [ + 17365 + ] + ], + [ + [ + 194946, + 194946 + ], + "mapped", + [ + 32946 + ] + ], + [ + [ + 194947, + 194947 + ], + "mapped", + [ + 33027 + ] + ], + [ + [ + 194948, + 194948 + ], + "mapped", + [ + 17419 + ] + ], + [ + [ + 194949, + 194949 + ], + "mapped", + [ + 33086 + ] + ], + [ + [ + 194950, + 194950 + ], + "mapped", + [ + 23221 + ] + ], + [ + [ + 194951, + 194951 + ], + "mapped", + [ + 157607 + ] + ], + [ + [ + 194952, + 194952 + ], + "mapped", + [ + 157621 + ] + ], + [ + [ + 194953, + 194953 + ], + "mapped", + [ + 144275 + ] + ], + [ + [ + 194954, + 194954 + ], + "mapped", + [ + 144284 + ] + ], + [ + [ + 194955, + 194955 + ], + "mapped", + [ + 33281 + ] + ], + [ + [ + 194956, + 194956 + ], + "mapped", + [ + 33284 + ] + ], + [ + [ + 194957, + 194957 + ], + "mapped", + [ + 36766 + ] + ], + [ + [ + 194958, + 194958 + ], + "mapped", + [ + 17515 + ] + ], + [ + [ + 194959, + 194959 + ], + "mapped", + [ + 33425 + ] + ], + [ + [ + 194960, + 194960 + ], + "mapped", + [ + 33419 + ] + ], + [ + [ + 194961, + 194961 + ], + "mapped", + [ + 33437 + ] + ], + [ + [ + 194962, + 194962 + ], + "mapped", + [ + 21171 + ] + ], + [ + [ + 194963, + 194963 + ], + "mapped", + [ + 33457 + ] + ], + [ + [ + 194964, + 194964 + ], + "mapped", + [ + 33459 + ] + ], + [ + [ + 194965, + 194965 + ], + "mapped", + [ + 33469 + ] + ], + [ + [ + 194966, + 194966 + ], + "mapped", + [ + 33510 + ] + ], + [ + [ + 194967, + 194967 + ], + "mapped", + [ + 158524 + ] + ], + [ + [ + 194968, + 194968 + ], + "mapped", + [ + 33509 + ] + ], + [ + [ + 194969, + 194969 + ], + "mapped", + [ + 33565 + ] + ], + [ + [ + 194970, + 194970 + ], + "mapped", + [ + 33635 + ] + ], + [ + [ + 194971, + 194971 + ], + "mapped", + [ + 33709 + ] + ], + [ + [ + 194972, + 194972 + ], + "mapped", + [ + 33571 + ] + ], + [ + [ + 194973, + 194973 + ], + "mapped", + [ + 33725 + ] + ], + [ + [ + 194974, + 194974 + ], + "mapped", + [ + 33767 + ] + ], + [ + [ + 194975, + 194975 + ], + "mapped", + [ + 33879 + ] + ], + [ + [ + 194976, + 194976 + ], + "mapped", + [ + 33619 + ] + ], + [ + [ + 194977, + 194977 + ], + "mapped", + [ + 33738 + ] + ], + [ + [ + 194978, + 194978 + ], + "mapped", + [ + 33740 + ] + ], + [ + [ + 194979, + 194979 + ], + "mapped", + [ + 33756 + ] + ], + [ + [ + 194980, + 194980 + ], + "mapped", + [ + 158774 + ] + ], + [ + [ + 194981, + 194981 + ], + "mapped", + [ + 159083 + ] + ], + [ + [ + 194982, + 194982 + ], + "mapped", + [ + 158933 + ] + ], + [ + [ + 194983, + 194983 + ], + "mapped", + [ + 17707 + ] + ], + [ + [ + 194984, + 194984 + ], + "mapped", + [ + 34033 + ] + ], + [ + [ + 194985, + 194985 + ], + "mapped", + [ + 34035 + ] + ], + [ + [ + 194986, + 194986 + ], + "mapped", + [ + 34070 + ] + ], + [ + [ + 194987, + 194987 + ], + "mapped", + [ + 160714 + ] + ], + [ + [ + 194988, + 194988 + ], + "mapped", + [ + 34148 + ] + ], + [ + [ + 194989, + 194989 + ], + "mapped", + [ + 159532 + ] + ], + [ + [ + 194990, + 194990 + ], + "mapped", + [ + 17757 + ] + ], + [ + [ + 194991, + 194991 + ], + "mapped", + [ + 17761 + ] + ], + [ + [ + 194992, + 194992 + ], + "mapped", + [ + 159665 + ] + ], + [ + [ + 194993, + 194993 + ], + "mapped", + [ + 159954 + ] + ], + [ + [ + 194994, + 194994 + ], + "mapped", + [ + 17771 + ] + ], + [ + [ + 194995, + 194995 + ], + "mapped", + [ + 34384 + ] + ], + [ + [ + 194996, + 194996 + ], + "mapped", + [ + 34396 + ] + ], + [ + [ + 194997, + 194997 + ], + "mapped", + [ + 34407 + ] + ], + [ + [ + 194998, + 194998 + ], + "mapped", + [ + 34409 + ] + ], + [ + [ + 194999, + 194999 + ], + "mapped", + [ + 34473 + ] + ], + [ + [ + 195000, + 195000 + ], + "mapped", + [ + 34440 + ] + ], + [ + [ + 195001, + 195001 + ], + "mapped", + [ + 34574 + ] + ], + [ + [ + 195002, + 195002 + ], + "mapped", + [ + 34530 + ] + ], + [ + [ + 195003, + 195003 + ], + "mapped", + [ + 34681 + ] + ], + [ + [ + 195004, + 195004 + ], + "mapped", + [ + 34600 + ] + ], + [ + [ + 195005, + 195005 + ], + "mapped", + [ + 34667 + ] + ], + [ + [ + 195006, + 195006 + ], + "mapped", + [ + 34694 + ] + ], + [ + [ + 195007, + 195007 + ], + "disallowed" + ], + [ + [ + 195008, + 195008 + ], + "mapped", + [ + 34785 + ] + ], + [ + [ + 195009, + 195009 + ], + "mapped", + [ + 34817 + ] + ], + [ + [ + 195010, + 195010 + ], + "mapped", + [ + 17913 + ] + ], + [ + [ + 195011, + 195011 + ], + "mapped", + [ + 34912 + ] + ], + [ + [ + 195012, + 195012 + ], + "mapped", + [ + 34915 + ] + ], + [ + [ + 195013, + 195013 + ], + "mapped", + [ + 161383 + ] + ], + [ + [ + 195014, + 195014 + ], + "mapped", + [ + 35031 + ] + ], + [ + [ + 195015, + 195015 + ], + "mapped", + [ + 35038 + ] + ], + [ + [ + 195016, + 195016 + ], + "mapped", + [ + 17973 + ] + ], + [ + [ + 195017, + 195017 + ], + "mapped", + [ + 35066 + ] + ], + [ + [ + 195018, + 195018 + ], + "mapped", + [ + 13499 + ] + ], + [ + [ + 195019, + 195019 + ], + "mapped", + [ + 161966 + ] + ], + [ + [ + 195020, + 195020 + ], + "mapped", + [ + 162150 + ] + ], + [ + [ + 195021, + 195021 + ], + "mapped", + [ + 18110 + ] + ], + [ + [ + 195022, + 195022 + ], + "mapped", + [ + 18119 + ] + ], + [ + [ + 195023, + 195023 + ], + "mapped", + [ + 35488 + ] + ], + [ + [ + 195024, + 195024 + ], + "mapped", + [ + 35565 + ] + ], + [ + [ + 195025, + 195025 + ], + "mapped", + [ + 35722 + ] + ], + [ + [ + 195026, + 195026 + ], + "mapped", + [ + 35925 + ] + ], + [ + [ + 195027, + 195027 + ], + "mapped", + [ + 162984 + ] + ], + [ + [ + 195028, + 195028 + ], + "mapped", + [ + 36011 + ] + ], + [ + [ + 195029, + 195029 + ], + "mapped", + [ + 36033 + ] + ], + [ + [ + 195030, + 195030 + ], + "mapped", + [ + 36123 + ] + ], + [ + [ + 195031, + 195031 + ], + "mapped", + [ + 36215 + ] + ], + [ + [ + 195032, + 195032 + ], + "mapped", + [ + 163631 + ] + ], + [ + [ + 195033, + 195033 + ], + "mapped", + [ + 133124 + ] + ], + [ + [ + 195034, + 195034 + ], + "mapped", + [ + 36299 + ] + ], + [ + [ + 195035, + 195035 + ], + "mapped", + [ + 36284 + ] + ], + [ + [ + 195036, + 195036 + ], + "mapped", + [ + 36336 + ] + ], + [ + [ + 195037, + 195037 + ], + "mapped", + [ + 133342 + ] + ], + [ + [ + 195038, + 195038 + ], + "mapped", + [ + 36564 + ] + ], + [ + [ + 195039, + 195039 + ], + "mapped", + [ + 36664 + ] + ], + [ + [ + 195040, + 195040 + ], + "mapped", + [ + 165330 + ] + ], + [ + [ + 195041, + 195041 + ], + "mapped", + [ + 165357 + ] + ], + [ + [ + 195042, + 195042 + ], + "mapped", + [ + 37012 + ] + ], + [ + [ + 195043, + 195043 + ], + "mapped", + [ + 37105 + ] + ], + [ + [ + 195044, + 195044 + ], + "mapped", + [ + 37137 + ] + ], + [ + [ + 195045, + 195045 + ], + "mapped", + [ + 165678 + ] + ], + [ + [ + 195046, + 195046 + ], + "mapped", + [ + 37147 + ] + ], + [ + [ + 195047, + 195047 + ], + "mapped", + [ + 37432 + ] + ], + [ + [ + 195048, + 195048 + ], + "mapped", + [ + 37591 + ] + ], + [ + [ + 195049, + 195049 + ], + "mapped", + [ + 37592 + ] + ], + [ + [ + 195050, + 195050 + ], + "mapped", + [ + 37500 + ] + ], + [ + [ + 195051, + 195051 + ], + "mapped", + [ + 37881 + ] + ], + [ + [ + 195052, + 195052 + ], + "mapped", + [ + 37909 + ] + ], + [ + [ + 195053, + 195053 + ], + "mapped", + [ + 166906 + ] + ], + [ + [ + 195054, + 195054 + ], + "mapped", + [ + 38283 + ] + ], + [ + [ + 195055, + 195055 + ], + "mapped", + [ + 18837 + ] + ], + [ + [ + 195056, + 195056 + ], + "mapped", + [ + 38327 + ] + ], + [ + [ + 195057, + 195057 + ], + "mapped", + [ + 167287 + ] + ], + [ + [ + 195058, + 195058 + ], + "mapped", + [ + 18918 + ] + ], + [ + [ + 195059, + 195059 + ], + "mapped", + [ + 38595 + ] + ], + [ + [ + 195060, + 195060 + ], + "mapped", + [ + 23986 + ] + ], + [ + [ + 195061, + 195061 + ], + "mapped", + [ + 38691 + ] + ], + [ + [ + 195062, + 195062 + ], + "mapped", + [ + 168261 + ] + ], + [ + [ + 195063, + 195063 + ], + "mapped", + [ + 168474 + ] + ], + [ + [ + 195064, + 195064 + ], + "mapped", + [ + 19054 + ] + ], + [ + [ + 195065, + 195065 + ], + "mapped", + [ + 19062 + ] + ], + [ + [ + 195066, + 195066 + ], + "mapped", + [ + 38880 + ] + ], + [ + [ + 195067, + 195067 + ], + "mapped", + [ + 168970 + ] + ], + [ + [ + 195068, + 195068 + ], + "mapped", + [ + 19122 + ] + ], + [ + [ + 195069, + 195069 + ], + "mapped", + [ + 169110 + ] + ], + [ + [ + 195070, + 195071 + ], + "mapped", + [ + 38923 + ] + ], + [ + [ + 195072, + 195072 + ], + "mapped", + [ + 38953 + ] + ], + [ + [ + 195073, + 195073 + ], + "mapped", + [ + 169398 + ] + ], + [ + [ + 195074, + 195074 + ], + "mapped", + [ + 39138 + ] + ], + [ + [ + 195075, + 195075 + ], + "mapped", + [ + 19251 + ] + ], + [ + [ + 195076, + 195076 + ], + "mapped", + [ + 39209 + ] + ], + [ + [ + 195077, + 195077 + ], + "mapped", + [ + 39335 + ] + ], + [ + [ + 195078, + 195078 + ], + "mapped", + [ + 39362 + ] + ], + [ + [ + 195079, + 195079 + ], + "mapped", + [ + 39422 + ] + ], + [ + [ + 195080, + 195080 + ], + "mapped", + [ + 19406 + ] + ], + [ + [ + 195081, + 195081 + ], + "mapped", + [ + 170800 + ] + ], + [ + [ + 195082, + 195082 + ], + "mapped", + [ + 39698 + ] + ], + [ + [ + 195083, + 195083 + ], + "mapped", + [ + 40000 + ] + ], + [ + [ + 195084, + 195084 + ], + "mapped", + [ + 40189 + ] + ], + [ + [ + 195085, + 195085 + ], + "mapped", + [ + 19662 + ] + ], + [ + [ + 195086, + 195086 + ], + "mapped", + [ + 19693 + ] + ], + [ + [ + 195087, + 195087 + ], + "mapped", + [ + 40295 + ] + ], + [ + [ + 195088, + 195088 + ], + "mapped", + [ + 172238 + ] + ], + [ + [ + 195089, + 195089 + ], + "mapped", + [ + 19704 + ] + ], + [ + [ + 195090, + 195090 + ], + "mapped", + [ + 172293 + ] + ], + [ + [ + 195091, + 195091 + ], + "mapped", + [ + 172558 + ] + ], + [ + [ + 195092, + 195092 + ], + "mapped", + [ + 172689 + ] + ], + [ + [ + 195093, + 195093 + ], + "mapped", + [ + 40635 + ] + ], + [ + [ + 195094, + 195094 + ], + "mapped", + [ + 19798 + ] + ], + [ + [ + 195095, + 195095 + ], + "mapped", + [ + 40697 + ] + ], + [ + [ + 195096, + 195096 + ], + "mapped", + [ + 40702 + ] + ], + [ + [ + 195097, + 195097 + ], + "mapped", + [ + 40709 + ] + ], + [ + [ + 195098, + 195098 + ], + "mapped", + [ + 40719 + ] + ], + [ + [ + 195099, + 195099 + ], + "mapped", + [ + 40726 + ] + ], + [ + [ + 195100, + 195100 + ], + "mapped", + [ + 40763 + ] + ], + [ + [ + 195101, + 195101 + ], + "mapped", + [ + 173568 + ] + ], + [ + [ + 195102, + 196605 + ], + "disallowed" + ], + [ + [ + 196606, + 196607 + ], + "disallowed" + ], + [ + [ + 196608, + 262141 + ], + "disallowed" + ], + [ + [ + 262142, + 262143 + ], + "disallowed" + ], + [ + [ + 262144, + 327677 + ], + "disallowed" + ], + [ + [ + 327678, + 327679 + ], + "disallowed" + ], + [ + [ + 327680, + 393213 + ], + "disallowed" + ], + [ + [ + 393214, + 393215 + ], + "disallowed" + ], + [ + [ + 393216, + 458749 + ], + "disallowed" + ], + [ + [ + 458750, + 458751 + ], + "disallowed" + ], + [ + [ + 458752, + 524285 + ], + "disallowed" + ], + [ + [ + 524286, + 524287 + ], + "disallowed" + ], + [ + [ + 524288, + 589821 + ], + "disallowed" + ], + [ + [ + 589822, + 589823 + ], + "disallowed" + ], + [ + [ + 589824, + 655357 + ], + "disallowed" + ], + [ + [ + 655358, + 655359 + ], + "disallowed" + ], + [ + [ + 655360, + 720893 + ], + "disallowed" + ], + [ + [ + 720894, + 720895 + ], + "disallowed" + ], + [ + [ + 720896, + 786429 + ], + "disallowed" + ], + [ + [ + 786430, + 786431 + ], + "disallowed" + ], + [ + [ + 786432, + 851965 + ], + "disallowed" + ], + [ + [ + 851966, + 851967 + ], + "disallowed" + ], + [ + [ + 851968, + 917501 + ], + "disallowed" + ], + [ + [ + 917502, + 917503 + ], + "disallowed" + ], + [ + [ + 917504, + 917504 + ], + "disallowed" + ], + [ + [ + 917505, + 917505 + ], + "disallowed" + ], + [ + [ + 917506, + 917535 + ], + "disallowed" + ], + [ + [ + 917536, + 917631 + ], + "disallowed" + ], + [ + [ + 917632, + 917759 + ], + "disallowed" + ], + [ + [ + 917760, + 917999 + ], + "ignored" + ], + [ + [ + 918000, + 983037 + ], + "disallowed" + ], + [ + [ + 983038, + 983039 + ], + "disallowed" + ], + [ + [ + 983040, + 1048573 + ], + "disallowed" + ], + [ + [ + 1048574, + 1048575 + ], + "disallowed" + ], + [ + [ + 1048576, + 1114109 + ], + "disallowed" + ], + [ + [ + 1114110, + 1114111 + ], + "disallowed" + ] +]; + +var punycode = require$$0$j; +var mappingTable = require$$1; + +var PROCESSING_OPTIONS = { + TRANSITIONAL: 0, + NONTRANSITIONAL: 1 +}; + +function normalize(str) { // fix bug in v8 + return str.split('\u0000').map(function (s) { return s.normalize('NFC'); }).join('\u0000'); +} + +function findStatus(val) { + var start = 0; + var end = mappingTable.length - 1; + + while (start <= end) { + var mid = Math.floor((start + end) / 2); + + var target = mappingTable[mid]; + if (target[0][0] <= val && target[0][1] >= val) { + return target; + } else if (target[0][0] > val) { + end = mid - 1; + } else { + start = mid + 1; + } + } + + return null; +} + +var regexAstralSymbols = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g; + +function countSymbols(string) { + return string + // replace every surrogate pair with a BMP symbol + .replace(regexAstralSymbols, '_') + // then get the length + .length; +} + +function mapChars(domain_name, useSTD3, processing_option) { + var hasError = false; + var processed = ""; + + var len = countSymbols(domain_name); + for (var i = 0; i < len; ++i) { + var codePoint = domain_name.codePointAt(i); + var status = findStatus(codePoint); + + switch (status[1]) { + case "disallowed": + hasError = true; + processed += String.fromCodePoint(codePoint); + break; + case "ignored": + break; + case "mapped": + processed += String.fromCodePoint.apply(String, status[2]); + break; + case "deviation": + if (processing_option === PROCESSING_OPTIONS.TRANSITIONAL) { + processed += String.fromCodePoint.apply(String, status[2]); + } else { + processed += String.fromCodePoint(codePoint); + } + break; + case "valid": + processed += String.fromCodePoint(codePoint); + break; + case "disallowed_STD3_mapped": + if (useSTD3) { + hasError = true; + processed += String.fromCodePoint(codePoint); + } else { + processed += String.fromCodePoint.apply(String, status[2]); + } + break; + case "disallowed_STD3_valid": + if (useSTD3) { + hasError = true; + } + + processed += String.fromCodePoint(codePoint); + break; + } + } + + return { + string: processed, + error: hasError + }; +} + +var combiningMarksRegex = /[\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08E4-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C00-\u0C03\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0D01-\u0D03\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u109A-\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u180B-\u180D\u18A9\u1920-\u192B\u1930-\u193B\u19B0-\u19C0\u19C8\u19C9\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BE6-\u1BF3\u1C24-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF2-\u1CF4\u1CF8\u1CF9\u1DC0-\u1DF5\u1DFC-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C4\uA8E0-\uA8F1\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9E5\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2D]|\uD800[\uDDFD\uDEE0\uDF76-\uDF7A]|\uD802[\uDE01-\uDE03\uDE05\uDE06\uDE0C-\uDE0F\uDE38-\uDE3A\uDE3F\uDEE5\uDEE6]|\uD804[\uDC00-\uDC02\uDC38-\uDC46\uDC7F-\uDC82\uDCB0-\uDCBA\uDD00-\uDD02\uDD27-\uDD34\uDD73\uDD80-\uDD82\uDDB3-\uDDC0\uDE2C-\uDE37\uDEDF-\uDEEA\uDF01-\uDF03\uDF3C\uDF3E-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF57\uDF62\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDCB0-\uDCC3\uDDAF-\uDDB5\uDDB8-\uDDC0\uDE30-\uDE40\uDEAB-\uDEB7]|\uD81A[\uDEF0-\uDEF4\uDF30-\uDF36]|\uD81B[\uDF51-\uDF7E\uDF8F-\uDF92]|\uD82F[\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD83A[\uDCD0-\uDCD6]|\uDB40[\uDD00-\uDDEF]/; + +function validateLabel(label, processing_option) { + if (label.substr(0, 4) === "xn--") { + label = punycode.toUnicode(label); + PROCESSING_OPTIONS.NONTRANSITIONAL; + } + + var error = false; + + if (normalize(label) !== label || + (label[3] === "-" && label[4] === "-") || + label[0] === "-" || label[label.length - 1] === "-" || + label.indexOf(".") !== -1 || + label.search(combiningMarksRegex) === 0) { + error = true; + } + + var len = countSymbols(label); + for (var i = 0; i < len; ++i) { + var status = findStatus(label.codePointAt(i)); + if ((processing === PROCESSING_OPTIONS.TRANSITIONAL && status[1] !== "valid") || + (processing === PROCESSING_OPTIONS.NONTRANSITIONAL && + status[1] !== "valid" && status[1] !== "deviation")) { + error = true; + break; + } + } + + return { + label: label, + error: error + }; +} + +function processing(domain_name, useSTD3, processing_option) { + var result = mapChars(domain_name, useSTD3, processing_option); + result.string = normalize(result.string); + + var labels = result.string.split("."); + for (var i = 0; i < labels.length; ++i) { + try { + var validation = validateLabel(labels[i]); + labels[i] = validation.label; + result.error = result.error || validation.error; + } catch(e) { + result.error = true; + } + } + + return { + string: labels.join("."), + error: result.error + }; +} + +tr46.toASCII = function(domain_name, useSTD3, processing_option, verifyDnsLength) { + var result = processing(domain_name, useSTD3, processing_option); + var labels = result.string.split("."); + labels = labels.map(function(l) { + try { + return punycode.toASCII(l); + } catch(e) { + result.error = true; + return l; + } + }); + + if (verifyDnsLength) { + var total = labels.slice(0, labels.length - 1).join(".").length; + if (total.length > 253 || total.length === 0) { + result.error = true; + } + + for (var i=0; i < labels.length; ++i) { + if (labels.length > 63 || labels.length === 0) { + result.error = true; + break; + } + } + } + + if (result.error) return null; + return labels.join("."); +}; + +tr46.toUnicode = function(domain_name, useSTD3) { + var result = processing(domain_name, useSTD3, PROCESSING_OPTIONS.NONTRANSITIONAL); + + return { + domain: result.string, + error: result.error + }; +}; + +tr46.PROCESSING_OPTIONS = PROCESSING_OPTIONS; + +(function (module) { + const punycode = require$$0$j; + const tr46$1 = tr46; + + const specialSchemes = { + ftp: 21, + file: null, + gopher: 70, + http: 80, + https: 443, + ws: 80, + wss: 443 + }; + + const failure = Symbol("failure"); + + function countSymbols(str) { + return punycode.ucs2.decode(str).length; + } + + function at(input, idx) { + const c = input[idx]; + return isNaN(c) ? undefined : String.fromCodePoint(c); + } + + function isASCIIDigit(c) { + return c >= 0x30 && c <= 0x39; + } + + function isASCIIAlpha(c) { + return (c >= 0x41 && c <= 0x5A) || (c >= 0x61 && c <= 0x7A); + } + + function isASCIIAlphanumeric(c) { + return isASCIIAlpha(c) || isASCIIDigit(c); + } + + function isASCIIHex(c) { + return isASCIIDigit(c) || (c >= 0x41 && c <= 0x46) || (c >= 0x61 && c <= 0x66); + } + + function isSingleDot(buffer) { + return buffer === "." || buffer.toLowerCase() === "%2e"; + } + + function isDoubleDot(buffer) { + buffer = buffer.toLowerCase(); + return buffer === ".." || buffer === "%2e." || buffer === ".%2e" || buffer === "%2e%2e"; + } + + function isWindowsDriveLetterCodePoints(cp1, cp2) { + return isASCIIAlpha(cp1) && (cp2 === 58 || cp2 === 124); + } + + function isWindowsDriveLetterString(string) { + return string.length === 2 && isASCIIAlpha(string.codePointAt(0)) && (string[1] === ":" || string[1] === "|"); + } + + function isNormalizedWindowsDriveLetterString(string) { + return string.length === 2 && isASCIIAlpha(string.codePointAt(0)) && string[1] === ":"; + } + + function containsForbiddenHostCodePoint(string) { + return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|%|\/|:|\?|@|\[|\\|\]/) !== -1; + } + + function containsForbiddenHostCodePointExcludingPercent(string) { + return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|\?|@|\[|\\|\]/) !== -1; + } + + function isSpecialScheme(scheme) { + return specialSchemes[scheme] !== undefined; + } + + function isSpecial(url) { + return isSpecialScheme(url.scheme); + } + + function defaultPort(scheme) { + return specialSchemes[scheme]; + } + + function percentEncode(c) { + let hex = c.toString(16).toUpperCase(); + if (hex.length === 1) { + hex = "0" + hex; + } + + return "%" + hex; + } + + function utf8PercentEncode(c) { + const buf = new Buffer(c); + + let str = ""; + + for (let i = 0; i < buf.length; ++i) { + str += percentEncode(buf[i]); + } + + return str; + } + + function utf8PercentDecode(str) { + const input = new Buffer(str); + const output = []; + for (let i = 0; i < input.length; ++i) { + if (input[i] !== 37) { + output.push(input[i]); + } else if (input[i] === 37 && isASCIIHex(input[i + 1]) && isASCIIHex(input[i + 2])) { + output.push(parseInt(input.slice(i + 1, i + 3).toString(), 16)); + i += 2; + } else { + output.push(input[i]); + } + } + return new Buffer(output).toString(); + } + + function isC0ControlPercentEncode(c) { + return c <= 0x1F || c > 0x7E; + } + + const extraPathPercentEncodeSet = new Set([32, 34, 35, 60, 62, 63, 96, 123, 125]); + function isPathPercentEncode(c) { + return isC0ControlPercentEncode(c) || extraPathPercentEncodeSet.has(c); + } + + const extraUserinfoPercentEncodeSet = + new Set([47, 58, 59, 61, 64, 91, 92, 93, 94, 124]); + function isUserinfoPercentEncode(c) { + return isPathPercentEncode(c) || extraUserinfoPercentEncodeSet.has(c); + } + + function percentEncodeChar(c, encodeSetPredicate) { + const cStr = String.fromCodePoint(c); + + if (encodeSetPredicate(c)) { + return utf8PercentEncode(cStr); + } + + return cStr; + } + + function parseIPv4Number(input) { + let R = 10; + + if (input.length >= 2 && input.charAt(0) === "0" && input.charAt(1).toLowerCase() === "x") { + input = input.substring(2); + R = 16; + } else if (input.length >= 2 && input.charAt(0) === "0") { + input = input.substring(1); + R = 8; + } + + if (input === "") { + return 0; + } + + const regex = R === 10 ? /[^0-9]/ : (R === 16 ? /[^0-9A-Fa-f]/ : /[^0-7]/); + if (regex.test(input)) { + return failure; + } + + return parseInt(input, R); + } + + function parseIPv4(input) { + const parts = input.split("."); + if (parts[parts.length - 1] === "") { + if (parts.length > 1) { + parts.pop(); + } + } + + if (parts.length > 4) { + return input; + } + + const numbers = []; + for (const part of parts) { + if (part === "") { + return input; + } + const n = parseIPv4Number(part); + if (n === failure) { + return input; + } + + numbers.push(n); + } + + for (let i = 0; i < numbers.length - 1; ++i) { + if (numbers[i] > 255) { + return failure; + } + } + if (numbers[numbers.length - 1] >= Math.pow(256, 5 - numbers.length)) { + return failure; + } + + let ipv4 = numbers.pop(); + let counter = 0; + + for (const n of numbers) { + ipv4 += n * Math.pow(256, 3 - counter); + ++counter; + } + + return ipv4; + } + + function serializeIPv4(address) { + let output = ""; + let n = address; + + for (let i = 1; i <= 4; ++i) { + output = String(n % 256) + output; + if (i !== 4) { + output = "." + output; + } + n = Math.floor(n / 256); + } + + return output; + } + + function parseIPv6(input) { + const address = [0, 0, 0, 0, 0, 0, 0, 0]; + let pieceIndex = 0; + let compress = null; + let pointer = 0; + + input = punycode.ucs2.decode(input); + + if (input[pointer] === 58) { + if (input[pointer + 1] !== 58) { + return failure; + } + + pointer += 2; + ++pieceIndex; + compress = pieceIndex; + } + + while (pointer < input.length) { + if (pieceIndex === 8) { + return failure; + } + + if (input[pointer] === 58) { + if (compress !== null) { + return failure; + } + ++pointer; + ++pieceIndex; + compress = pieceIndex; + continue; + } + + let value = 0; + let length = 0; + + while (length < 4 && isASCIIHex(input[pointer])) { + value = value * 0x10 + parseInt(at(input, pointer), 16); + ++pointer; + ++length; + } + + if (input[pointer] === 46) { + if (length === 0) { + return failure; + } + + pointer -= length; + + if (pieceIndex > 6) { + return failure; + } + + let numbersSeen = 0; + + while (input[pointer] !== undefined) { + let ipv4Piece = null; + + if (numbersSeen > 0) { + if (input[pointer] === 46 && numbersSeen < 4) { + ++pointer; + } else { + return failure; + } + } + + if (!isASCIIDigit(input[pointer])) { + return failure; + } + + while (isASCIIDigit(input[pointer])) { + const number = parseInt(at(input, pointer)); + if (ipv4Piece === null) { + ipv4Piece = number; + } else if (ipv4Piece === 0) { + return failure; + } else { + ipv4Piece = ipv4Piece * 10 + number; + } + if (ipv4Piece > 255) { + return failure; + } + ++pointer; + } + + address[pieceIndex] = address[pieceIndex] * 0x100 + ipv4Piece; + + ++numbersSeen; + + if (numbersSeen === 2 || numbersSeen === 4) { + ++pieceIndex; + } + } + + if (numbersSeen !== 4) { + return failure; + } + + break; + } else if (input[pointer] === 58) { + ++pointer; + if (input[pointer] === undefined) { + return failure; + } + } else if (input[pointer] !== undefined) { + return failure; + } + + address[pieceIndex] = value; + ++pieceIndex; + } + + if (compress !== null) { + let swaps = pieceIndex - compress; + pieceIndex = 7; + while (pieceIndex !== 0 && swaps > 0) { + const temp = address[compress + swaps - 1]; + address[compress + swaps - 1] = address[pieceIndex]; + address[pieceIndex] = temp; + --pieceIndex; + --swaps; + } + } else if (compress === null && pieceIndex !== 8) { + return failure; + } + + return address; + } + + function serializeIPv6(address) { + let output = ""; + const seqResult = findLongestZeroSequence(address); + const compress = seqResult.idx; + let ignore0 = false; + + for (let pieceIndex = 0; pieceIndex <= 7; ++pieceIndex) { + if (ignore0 && address[pieceIndex] === 0) { + continue; + } else if (ignore0) { + ignore0 = false; + } + + if (compress === pieceIndex) { + const separator = pieceIndex === 0 ? "::" : ":"; + output += separator; + ignore0 = true; + continue; + } + + output += address[pieceIndex].toString(16); + + if (pieceIndex !== 7) { + output += ":"; + } + } + + return output; + } + + function parseHost(input, isSpecialArg) { + if (input[0] === "[") { + if (input[input.length - 1] !== "]") { + return failure; + } + + return parseIPv6(input.substring(1, input.length - 1)); + } + + if (!isSpecialArg) { + return parseOpaqueHost(input); + } + + const domain = utf8PercentDecode(input); + const asciiDomain = tr46$1.toASCII(domain, false, tr46$1.PROCESSING_OPTIONS.NONTRANSITIONAL, false); + if (asciiDomain === null) { + return failure; + } + + if (containsForbiddenHostCodePoint(asciiDomain)) { + return failure; + } + + const ipv4Host = parseIPv4(asciiDomain); + if (typeof ipv4Host === "number" || ipv4Host === failure) { + return ipv4Host; + } + + return asciiDomain; + } + + function parseOpaqueHost(input) { + if (containsForbiddenHostCodePointExcludingPercent(input)) { + return failure; + } + + let output = ""; + const decoded = punycode.ucs2.decode(input); + for (let i = 0; i < decoded.length; ++i) { + output += percentEncodeChar(decoded[i], isC0ControlPercentEncode); + } + return output; + } + + function findLongestZeroSequence(arr) { + let maxIdx = null; + let maxLen = 1; // only find elements > 1 + let currStart = null; + let currLen = 0; + + for (let i = 0; i < arr.length; ++i) { + if (arr[i] !== 0) { + if (currLen > maxLen) { + maxIdx = currStart; + maxLen = currLen; + } + + currStart = null; + currLen = 0; + } else { + if (currStart === null) { + currStart = i; + } + ++currLen; + } + } + + // if trailing zeros + if (currLen > maxLen) { + maxIdx = currStart; + maxLen = currLen; + } + + return { + idx: maxIdx, + len: maxLen + }; + } + + function serializeHost(host) { + if (typeof host === "number") { + return serializeIPv4(host); + } + + // IPv6 serializer + if (host instanceof Array) { + return "[" + serializeIPv6(host) + "]"; + } + + return host; + } + + function trimControlChars(url) { + return url.replace(/^[\u0000-\u001F\u0020]+|[\u0000-\u001F\u0020]+$/g, ""); + } + + function trimTabAndNewline(url) { + return url.replace(/\u0009|\u000A|\u000D/g, ""); + } + + function shortenPath(url) { + const path = url.path; + if (path.length === 0) { + return; + } + if (url.scheme === "file" && path.length === 1 && isNormalizedWindowsDriveLetter(path[0])) { + return; + } + + path.pop(); + } + + function includesCredentials(url) { + return url.username !== "" || url.password !== ""; + } + + function cannotHaveAUsernamePasswordPort(url) { + return url.host === null || url.host === "" || url.cannotBeABaseURL || url.scheme === "file"; + } + + function isNormalizedWindowsDriveLetter(string) { + return /^[A-Za-z]:$/.test(string); + } + + function URLStateMachine(input, base, encodingOverride, url, stateOverride) { + this.pointer = 0; + this.input = input; + this.base = base || null; + this.encodingOverride = encodingOverride || "utf-8"; + this.stateOverride = stateOverride; + this.url = url; + this.failure = false; + this.parseError = false; + + if (!this.url) { + this.url = { + scheme: "", + username: "", + password: "", + host: null, + port: null, + path: [], + query: null, + fragment: null, + + cannotBeABaseURL: false + }; + + const res = trimControlChars(this.input); + if (res !== this.input) { + this.parseError = true; + } + this.input = res; + } + + const res = trimTabAndNewline(this.input); + if (res !== this.input) { + this.parseError = true; + } + this.input = res; + + this.state = stateOverride || "scheme start"; + + this.buffer = ""; + this.atFlag = false; + this.arrFlag = false; + this.passwordTokenSeenFlag = false; + + this.input = punycode.ucs2.decode(this.input); + + for (; this.pointer <= this.input.length; ++this.pointer) { + const c = this.input[this.pointer]; + const cStr = isNaN(c) ? undefined : String.fromCodePoint(c); + + // exec state machine + const ret = this["parse " + this.state](c, cStr); + if (!ret) { + break; // terminate algorithm + } else if (ret === failure) { + this.failure = true; + break; + } + } + } + + URLStateMachine.prototype["parse scheme start"] = function parseSchemeStart(c, cStr) { + if (isASCIIAlpha(c)) { + this.buffer += cStr.toLowerCase(); + this.state = "scheme"; + } else if (!this.stateOverride) { + this.state = "no scheme"; + --this.pointer; + } else { + this.parseError = true; + return failure; + } + + return true; + }; + + URLStateMachine.prototype["parse scheme"] = function parseScheme(c, cStr) { + if (isASCIIAlphanumeric(c) || c === 43 || c === 45 || c === 46) { + this.buffer += cStr.toLowerCase(); + } else if (c === 58) { + if (this.stateOverride) { + if (isSpecial(this.url) && !isSpecialScheme(this.buffer)) { + return false; + } + + if (!isSpecial(this.url) && isSpecialScheme(this.buffer)) { + return false; + } + + if ((includesCredentials(this.url) || this.url.port !== null) && this.buffer === "file") { + return false; + } + + if (this.url.scheme === "file" && (this.url.host === "" || this.url.host === null)) { + return false; + } + } + this.url.scheme = this.buffer; + this.buffer = ""; + if (this.stateOverride) { + return false; + } + if (this.url.scheme === "file") { + if (this.input[this.pointer + 1] !== 47 || this.input[this.pointer + 2] !== 47) { + this.parseError = true; + } + this.state = "file"; + } else if (isSpecial(this.url) && this.base !== null && this.base.scheme === this.url.scheme) { + this.state = "special relative or authority"; + } else if (isSpecial(this.url)) { + this.state = "special authority slashes"; + } else if (this.input[this.pointer + 1] === 47) { + this.state = "path or authority"; + ++this.pointer; + } else { + this.url.cannotBeABaseURL = true; + this.url.path.push(""); + this.state = "cannot-be-a-base-URL path"; + } + } else if (!this.stateOverride) { + this.buffer = ""; + this.state = "no scheme"; + this.pointer = -1; + } else { + this.parseError = true; + return failure; + } + + return true; + }; + + URLStateMachine.prototype["parse no scheme"] = function parseNoScheme(c) { + if (this.base === null || (this.base.cannotBeABaseURL && c !== 35)) { + return failure; + } else if (this.base.cannotBeABaseURL && c === 35) { + this.url.scheme = this.base.scheme; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + this.url.fragment = ""; + this.url.cannotBeABaseURL = true; + this.state = "fragment"; + } else if (this.base.scheme === "file") { + this.state = "file"; + --this.pointer; + } else { + this.state = "relative"; + --this.pointer; + } + + return true; + }; + + URLStateMachine.prototype["parse special relative or authority"] = function parseSpecialRelativeOrAuthority(c) { + if (c === 47 && this.input[this.pointer + 1] === 47) { + this.state = "special authority ignore slashes"; + ++this.pointer; + } else { + this.parseError = true; + this.state = "relative"; + --this.pointer; + } + + return true; + }; + + URLStateMachine.prototype["parse path or authority"] = function parsePathOrAuthority(c) { + if (c === 47) { + this.state = "authority"; + } else { + this.state = "path"; + --this.pointer; + } + + return true; + }; + + URLStateMachine.prototype["parse relative"] = function parseRelative(c) { + this.url.scheme = this.base.scheme; + if (isNaN(c)) { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + } else if (c === 47) { + this.state = "relative slash"; + } else if (c === 63) { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.url.path = this.base.path.slice(); + this.url.query = ""; + this.state = "query"; + } else if (c === 35) { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + this.url.fragment = ""; + this.state = "fragment"; + } else if (isSpecial(this.url) && c === 92) { + this.parseError = true; + this.state = "relative slash"; + } else { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.url.path = this.base.path.slice(0, this.base.path.length - 1); + + this.state = "path"; + --this.pointer; + } + + return true; + }; + + URLStateMachine.prototype["parse relative slash"] = function parseRelativeSlash(c) { + if (isSpecial(this.url) && (c === 47 || c === 92)) { + if (c === 92) { + this.parseError = true; + } + this.state = "special authority ignore slashes"; + } else if (c === 47) { + this.state = "authority"; + } else { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.state = "path"; + --this.pointer; + } + + return true; + }; + + URLStateMachine.prototype["parse special authority slashes"] = function parseSpecialAuthoritySlashes(c) { + if (c === 47 && this.input[this.pointer + 1] === 47) { + this.state = "special authority ignore slashes"; + ++this.pointer; + } else { + this.parseError = true; + this.state = "special authority ignore slashes"; + --this.pointer; + } + + return true; + }; + + URLStateMachine.prototype["parse special authority ignore slashes"] = function parseSpecialAuthorityIgnoreSlashes(c) { + if (c !== 47 && c !== 92) { + this.state = "authority"; + --this.pointer; + } else { + this.parseError = true; + } + + return true; + }; + + URLStateMachine.prototype["parse authority"] = function parseAuthority(c, cStr) { + if (c === 64) { + this.parseError = true; + if (this.atFlag) { + this.buffer = "%40" + this.buffer; + } + this.atFlag = true; + + // careful, this is based on buffer and has its own pointer (this.pointer != pointer) and inner chars + const len = countSymbols(this.buffer); + for (let pointer = 0; pointer < len; ++pointer) { + const codePoint = this.buffer.codePointAt(pointer); + + if (codePoint === 58 && !this.passwordTokenSeenFlag) { + this.passwordTokenSeenFlag = true; + continue; + } + const encodedCodePoints = percentEncodeChar(codePoint, isUserinfoPercentEncode); + if (this.passwordTokenSeenFlag) { + this.url.password += encodedCodePoints; + } else { + this.url.username += encodedCodePoints; + } + } + this.buffer = ""; + } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || + (isSpecial(this.url) && c === 92)) { + if (this.atFlag && this.buffer === "") { + this.parseError = true; + return failure; + } + this.pointer -= countSymbols(this.buffer) + 1; + this.buffer = ""; + this.state = "host"; + } else { + this.buffer += cStr; + } + + return true; + }; + + URLStateMachine.prototype["parse hostname"] = + URLStateMachine.prototype["parse host"] = function parseHostName(c, cStr) { + if (this.stateOverride && this.url.scheme === "file") { + --this.pointer; + this.state = "file host"; + } else if (c === 58 && !this.arrFlag) { + if (this.buffer === "") { + this.parseError = true; + return failure; + } + + const host = parseHost(this.buffer, isSpecial(this.url)); + if (host === failure) { + return failure; + } + + this.url.host = host; + this.buffer = ""; + this.state = "port"; + if (this.stateOverride === "hostname") { + return false; + } + } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || + (isSpecial(this.url) && c === 92)) { + --this.pointer; + if (isSpecial(this.url) && this.buffer === "") { + this.parseError = true; + return failure; + } else if (this.stateOverride && this.buffer === "" && + (includesCredentials(this.url) || this.url.port !== null)) { + this.parseError = true; + return false; + } + + const host = parseHost(this.buffer, isSpecial(this.url)); + if (host === failure) { + return failure; + } + + this.url.host = host; + this.buffer = ""; + this.state = "path start"; + if (this.stateOverride) { + return false; + } + } else { + if (c === 91) { + this.arrFlag = true; + } else if (c === 93) { + this.arrFlag = false; + } + this.buffer += cStr; + } + + return true; + }; + + URLStateMachine.prototype["parse port"] = function parsePort(c, cStr) { + if (isASCIIDigit(c)) { + this.buffer += cStr; + } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || + (isSpecial(this.url) && c === 92) || + this.stateOverride) { + if (this.buffer !== "") { + const port = parseInt(this.buffer); + if (port > Math.pow(2, 16) - 1) { + this.parseError = true; + return failure; + } + this.url.port = port === defaultPort(this.url.scheme) ? null : port; + this.buffer = ""; + } + if (this.stateOverride) { + return false; + } + this.state = "path start"; + --this.pointer; + } else { + this.parseError = true; + return failure; + } + + return true; + }; + + const fileOtherwiseCodePoints = new Set([47, 92, 63, 35]); + + URLStateMachine.prototype["parse file"] = function parseFile(c) { + this.url.scheme = "file"; + + if (c === 47 || c === 92) { + if (c === 92) { + this.parseError = true; + } + this.state = "file slash"; + } else if (this.base !== null && this.base.scheme === "file") { + if (isNaN(c)) { + this.url.host = this.base.host; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + } else if (c === 63) { + this.url.host = this.base.host; + this.url.path = this.base.path.slice(); + this.url.query = ""; + this.state = "query"; + } else if (c === 35) { + this.url.host = this.base.host; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + this.url.fragment = ""; + this.state = "fragment"; + } else { + if (this.input.length - this.pointer - 1 === 0 || // remaining consists of 0 code points + !isWindowsDriveLetterCodePoints(c, this.input[this.pointer + 1]) || + (this.input.length - this.pointer - 1 >= 2 && // remaining has at least 2 code points + !fileOtherwiseCodePoints.has(this.input[this.pointer + 2]))) { + this.url.host = this.base.host; + this.url.path = this.base.path.slice(); + shortenPath(this.url); + } else { + this.parseError = true; + } + + this.state = "path"; + --this.pointer; + } + } else { + this.state = "path"; + --this.pointer; + } + + return true; + }; + + URLStateMachine.prototype["parse file slash"] = function parseFileSlash(c) { + if (c === 47 || c === 92) { + if (c === 92) { + this.parseError = true; + } + this.state = "file host"; + } else { + if (this.base !== null && this.base.scheme === "file") { + if (isNormalizedWindowsDriveLetterString(this.base.path[0])) { + this.url.path.push(this.base.path[0]); + } else { + this.url.host = this.base.host; + } + } + this.state = "path"; + --this.pointer; + } + + return true; + }; + + URLStateMachine.prototype["parse file host"] = function parseFileHost(c, cStr) { + if (isNaN(c) || c === 47 || c === 92 || c === 63 || c === 35) { + --this.pointer; + if (!this.stateOverride && isWindowsDriveLetterString(this.buffer)) { + this.parseError = true; + this.state = "path"; + } else if (this.buffer === "") { + this.url.host = ""; + if (this.stateOverride) { + return false; + } + this.state = "path start"; + } else { + let host = parseHost(this.buffer, isSpecial(this.url)); + if (host === failure) { + return failure; + } + if (host === "localhost") { + host = ""; + } + this.url.host = host; + + if (this.stateOverride) { + return false; + } + + this.buffer = ""; + this.state = "path start"; + } + } else { + this.buffer += cStr; + } + + return true; + }; + + URLStateMachine.prototype["parse path start"] = function parsePathStart(c) { + if (isSpecial(this.url)) { + if (c === 92) { + this.parseError = true; + } + this.state = "path"; + + if (c !== 47 && c !== 92) { + --this.pointer; + } + } else if (!this.stateOverride && c === 63) { + this.url.query = ""; + this.state = "query"; + } else if (!this.stateOverride && c === 35) { + this.url.fragment = ""; + this.state = "fragment"; + } else if (c !== undefined) { + this.state = "path"; + if (c !== 47) { + --this.pointer; + } + } + + return true; + }; + + URLStateMachine.prototype["parse path"] = function parsePath(c) { + if (isNaN(c) || c === 47 || (isSpecial(this.url) && c === 92) || + (!this.stateOverride && (c === 63 || c === 35))) { + if (isSpecial(this.url) && c === 92) { + this.parseError = true; + } + + if (isDoubleDot(this.buffer)) { + shortenPath(this.url); + if (c !== 47 && !(isSpecial(this.url) && c === 92)) { + this.url.path.push(""); + } + } else if (isSingleDot(this.buffer) && c !== 47 && + !(isSpecial(this.url) && c === 92)) { + this.url.path.push(""); + } else if (!isSingleDot(this.buffer)) { + if (this.url.scheme === "file" && this.url.path.length === 0 && isWindowsDriveLetterString(this.buffer)) { + if (this.url.host !== "" && this.url.host !== null) { + this.parseError = true; + this.url.host = ""; + } + this.buffer = this.buffer[0] + ":"; + } + this.url.path.push(this.buffer); + } + this.buffer = ""; + if (this.url.scheme === "file" && (c === undefined || c === 63 || c === 35)) { + while (this.url.path.length > 1 && this.url.path[0] === "") { + this.parseError = true; + this.url.path.shift(); + } + } + if (c === 63) { + this.url.query = ""; + this.state = "query"; + } + if (c === 35) { + this.url.fragment = ""; + this.state = "fragment"; + } + } else { + // TODO: If c is not a URL code point and not "%", parse error. + + if (c === 37 && + (!isASCIIHex(this.input[this.pointer + 1]) || + !isASCIIHex(this.input[this.pointer + 2]))) { + this.parseError = true; + } + + this.buffer += percentEncodeChar(c, isPathPercentEncode); + } + + return true; + }; + + URLStateMachine.prototype["parse cannot-be-a-base-URL path"] = function parseCannotBeABaseURLPath(c) { + if (c === 63) { + this.url.query = ""; + this.state = "query"; + } else if (c === 35) { + this.url.fragment = ""; + this.state = "fragment"; + } else { + // TODO: Add: not a URL code point + if (!isNaN(c) && c !== 37) { + this.parseError = true; + } + + if (c === 37 && + (!isASCIIHex(this.input[this.pointer + 1]) || + !isASCIIHex(this.input[this.pointer + 2]))) { + this.parseError = true; + } + + if (!isNaN(c)) { + this.url.path[0] = this.url.path[0] + percentEncodeChar(c, isC0ControlPercentEncode); + } + } + + return true; + }; + + URLStateMachine.prototype["parse query"] = function parseQuery(c, cStr) { + if (isNaN(c) || (!this.stateOverride && c === 35)) { + if (!isSpecial(this.url) || this.url.scheme === "ws" || this.url.scheme === "wss") { + this.encodingOverride = "utf-8"; + } + + const buffer = new Buffer(this.buffer); // TODO: Use encoding override instead + for (let i = 0; i < buffer.length; ++i) { + if (buffer[i] < 0x21 || buffer[i] > 0x7E || buffer[i] === 0x22 || buffer[i] === 0x23 || + buffer[i] === 0x3C || buffer[i] === 0x3E) { + this.url.query += percentEncode(buffer[i]); + } else { + this.url.query += String.fromCodePoint(buffer[i]); + } + } + + this.buffer = ""; + if (c === 35) { + this.url.fragment = ""; + this.state = "fragment"; + } + } else { + // TODO: If c is not a URL code point and not "%", parse error. + if (c === 37 && + (!isASCIIHex(this.input[this.pointer + 1]) || + !isASCIIHex(this.input[this.pointer + 2]))) { + this.parseError = true; + } + + this.buffer += cStr; + } + + return true; + }; + + URLStateMachine.prototype["parse fragment"] = function parseFragment(c) { + if (isNaN(c)) ; else if (c === 0x0) { + this.parseError = true; + } else { + // TODO: If c is not a URL code point and not "%", parse error. + if (c === 37 && + (!isASCIIHex(this.input[this.pointer + 1]) || + !isASCIIHex(this.input[this.pointer + 2]))) { + this.parseError = true; + } + + this.url.fragment += percentEncodeChar(c, isC0ControlPercentEncode); + } + + return true; + }; + + function serializeURL(url, excludeFragment) { + let output = url.scheme + ":"; + if (url.host !== null) { + output += "//"; + + if (url.username !== "" || url.password !== "") { + output += url.username; + if (url.password !== "") { + output += ":" + url.password; + } + output += "@"; + } + + output += serializeHost(url.host); + + if (url.port !== null) { + output += ":" + url.port; + } + } else if (url.host === null && url.scheme === "file") { + output += "//"; + } + + if (url.cannotBeABaseURL) { + output += url.path[0]; + } else { + for (const string of url.path) { + output += "/" + string; + } + } + + if (url.query !== null) { + output += "?" + url.query; + } + + if (!excludeFragment && url.fragment !== null) { + output += "#" + url.fragment; + } + + return output; + } + + function serializeOrigin(tuple) { + let result = tuple.scheme + "://"; + result += serializeHost(tuple.host); + + if (tuple.port !== null) { + result += ":" + tuple.port; + } + + return result; + } + + module.exports.serializeURL = serializeURL; + + module.exports.serializeURLOrigin = function (url) { + // https://url.spec.whatwg.org/#concept-url-origin + switch (url.scheme) { + case "blob": + try { + return module.exports.serializeURLOrigin(module.exports.parseURL(url.path[0])); + } catch (e) { + // serializing an opaque origin returns "null" + return "null"; + } + case "ftp": + case "gopher": + case "http": + case "https": + case "ws": + case "wss": + return serializeOrigin({ + scheme: url.scheme, + host: url.host, + port: url.port + }); + case "file": + // spec says "exercise to the reader", chrome says "file://" + return "file://"; + default: + // serializing an opaque origin returns "null" + return "null"; + } + }; + + module.exports.basicURLParse = function (input, options) { + if (options === undefined) { + options = {}; + } + + const usm = new URLStateMachine(input, options.baseURL, options.encodingOverride, options.url, options.stateOverride); + if (usm.failure) { + return "failure"; + } + + return usm.url; + }; + + module.exports.setTheUsername = function (url, username) { + url.username = ""; + const decoded = punycode.ucs2.decode(username); + for (let i = 0; i < decoded.length; ++i) { + url.username += percentEncodeChar(decoded[i], isUserinfoPercentEncode); + } + }; + + module.exports.setThePassword = function (url, password) { + url.password = ""; + const decoded = punycode.ucs2.decode(password); + for (let i = 0; i < decoded.length; ++i) { + url.password += percentEncodeChar(decoded[i], isUserinfoPercentEncode); + } + }; + + module.exports.serializeHost = serializeHost; + + module.exports.cannotHaveAUsernamePasswordPort = cannotHaveAUsernamePasswordPort; + + module.exports.serializeInteger = function (integer) { + return String(integer); + }; + + module.exports.parseURL = function (input, options) { + if (options === undefined) { + options = {}; + } + + // We don't handle blobs, so this just delegates: + return module.exports.basicURLParse(input, { baseURL: options.baseURL, encodingOverride: options.encodingOverride }); + }; +} (urlStateMachine)); + +var urlStateMachineExports = urlStateMachine.exports; + +const usm = urlStateMachineExports; + +URLImpl.implementation = class URLImpl { + constructor(constructorArgs) { + const url = constructorArgs[0]; + const base = constructorArgs[1]; + + let parsedBase = null; + if (base !== undefined) { + parsedBase = usm.basicURLParse(base); + if (parsedBase === "failure") { + throw new TypeError("Invalid base URL"); + } + } + + const parsedURL = usm.basicURLParse(url, { baseURL: parsedBase }); + if (parsedURL === "failure") { + throw new TypeError("Invalid URL"); + } + + this._url = parsedURL; + + // TODO: query stuff + } + + get href() { + return usm.serializeURL(this._url); + } + + set href(v) { + const parsedURL = usm.basicURLParse(v); + if (parsedURL === "failure") { + throw new TypeError("Invalid URL"); + } + + this._url = parsedURL; + } + + get origin() { + return usm.serializeURLOrigin(this._url); + } + + get protocol() { + return this._url.scheme + ":"; + } + + set protocol(v) { + usm.basicURLParse(v + ":", { url: this._url, stateOverride: "scheme start" }); + } + + get username() { + return this._url.username; + } + + set username(v) { + if (usm.cannotHaveAUsernamePasswordPort(this._url)) { + return; + } + + usm.setTheUsername(this._url, v); + } + + get password() { + return this._url.password; + } + + set password(v) { + if (usm.cannotHaveAUsernamePasswordPort(this._url)) { + return; + } + + usm.setThePassword(this._url, v); + } + + get host() { + const url = this._url; + + if (url.host === null) { + return ""; + } + + if (url.port === null) { + return usm.serializeHost(url.host); + } + + return usm.serializeHost(url.host) + ":" + usm.serializeInteger(url.port); + } + + set host(v) { + if (this._url.cannotBeABaseURL) { + return; + } + + usm.basicURLParse(v, { url: this._url, stateOverride: "host" }); + } + + get hostname() { + if (this._url.host === null) { + return ""; + } + + return usm.serializeHost(this._url.host); + } + + set hostname(v) { + if (this._url.cannotBeABaseURL) { + return; + } + + usm.basicURLParse(v, { url: this._url, stateOverride: "hostname" }); + } + + get port() { + if (this._url.port === null) { + return ""; + } + + return usm.serializeInteger(this._url.port); + } + + set port(v) { + if (usm.cannotHaveAUsernamePasswordPort(this._url)) { + return; + } + + if (v === "") { + this._url.port = null; + } else { + usm.basicURLParse(v, { url: this._url, stateOverride: "port" }); + } + } + + get pathname() { + if (this._url.cannotBeABaseURL) { + return this._url.path[0]; + } + + if (this._url.path.length === 0) { + return ""; + } + + return "/" + this._url.path.join("/"); + } + + set pathname(v) { + if (this._url.cannotBeABaseURL) { + return; + } + + this._url.path = []; + usm.basicURLParse(v, { url: this._url, stateOverride: "path start" }); + } + + get search() { + if (this._url.query === null || this._url.query === "") { + return ""; + } + + return "?" + this._url.query; + } + + set search(v) { + // TODO: query stuff + + const url = this._url; + + if (v === "") { + url.query = null; + return; + } + + const input = v[0] === "?" ? v.substring(1) : v; + url.query = ""; + usm.basicURLParse(input, { url, stateOverride: "query" }); + } + + get hash() { + if (this._url.fragment === null || this._url.fragment === "") { + return ""; + } + + return "#" + this._url.fragment; + } + + set hash(v) { + if (v === "") { + this._url.fragment = null; + return; + } + + const input = v[0] === "#" ? v.substring(1) : v; + this._url.fragment = ""; + usm.basicURLParse(input, { url: this._url, stateOverride: "fragment" }); + } + + toJSON() { + return this.href; + } +}; + +(function (module) { + + const conversions = lib; + const utils = utilsExports; + const Impl = URLImpl; + + const impl = utils.implSymbol; + + function URL(url) { + if (!this || this[impl] || !(this instanceof URL)) { + throw new TypeError("Failed to construct 'URL': Please use the 'new' operator, this DOM object constructor cannot be called as a function."); + } + if (arguments.length < 1) { + throw new TypeError("Failed to construct 'URL': 1 argument required, but only " + arguments.length + " present."); + } + const args = []; + for (let i = 0; i < arguments.length && i < 2; ++i) { + args[i] = arguments[i]; + } + args[0] = conversions["USVString"](args[0]); + if (args[1] !== undefined) { + args[1] = conversions["USVString"](args[1]); + } + + module.exports.setup(this, args); + } + + URL.prototype.toJSON = function toJSON() { + if (!this || !module.exports.is(this)) { + throw new TypeError("Illegal invocation"); + } + const args = []; + for (let i = 0; i < arguments.length && i < 0; ++i) { + args[i] = arguments[i]; + } + return this[impl].toJSON.apply(this[impl], args); + }; + Object.defineProperty(URL.prototype, "href", { + get() { + return this[impl].href; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].href = V; + }, + enumerable: true, + configurable: true + }); + + URL.prototype.toString = function () { + if (!this || !module.exports.is(this)) { + throw new TypeError("Illegal invocation"); + } + return this.href; + }; + + Object.defineProperty(URL.prototype, "origin", { + get() { + return this[impl].origin; + }, + enumerable: true, + configurable: true + }); + + Object.defineProperty(URL.prototype, "protocol", { + get() { + return this[impl].protocol; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].protocol = V; + }, + enumerable: true, + configurable: true + }); + + Object.defineProperty(URL.prototype, "username", { + get() { + return this[impl].username; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].username = V; + }, + enumerable: true, + configurable: true + }); + + Object.defineProperty(URL.prototype, "password", { + get() { + return this[impl].password; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].password = V; + }, + enumerable: true, + configurable: true + }); + + Object.defineProperty(URL.prototype, "host", { + get() { + return this[impl].host; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].host = V; + }, + enumerable: true, + configurable: true + }); + + Object.defineProperty(URL.prototype, "hostname", { + get() { + return this[impl].hostname; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].hostname = V; + }, + enumerable: true, + configurable: true + }); + + Object.defineProperty(URL.prototype, "port", { + get() { + return this[impl].port; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].port = V; + }, + enumerable: true, + configurable: true + }); + + Object.defineProperty(URL.prototype, "pathname", { + get() { + return this[impl].pathname; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].pathname = V; + }, + enumerable: true, + configurable: true + }); + + Object.defineProperty(URL.prototype, "search", { + get() { + return this[impl].search; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].search = V; + }, + enumerable: true, + configurable: true + }); + + Object.defineProperty(URL.prototype, "hash", { + get() { + return this[impl].hash; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].hash = V; + }, + enumerable: true, + configurable: true + }); + + + module.exports = { + is(obj) { + return !!obj && obj[impl] instanceof Impl.implementation; + }, + create(constructorArgs, privateData) { + let obj = Object.create(URL.prototype); + this.setup(obj, constructorArgs, privateData); + return obj; + }, + setup(obj, constructorArgs, privateData) { + if (!privateData) privateData = {}; + privateData.wrapper = obj; + + obj[impl] = new Impl.implementation(constructorArgs, privateData); + obj[impl][utils.wrapperSymbol] = obj; + }, + interface: URL, + expose: { + Window: { URL: URL }, + Worker: { URL: URL } + } + }; +} (URL$2)); + +var URLExports = URL$2.exports; + +publicApi.URL = URLExports.interface; +publicApi.serializeURL = urlStateMachineExports.serializeURL; +publicApi.serializeURLOrigin = urlStateMachineExports.serializeURLOrigin; +publicApi.basicURLParse = urlStateMachineExports.basicURLParse; +publicApi.setTheUsername = urlStateMachineExports.setTheUsername; +publicApi.setThePassword = urlStateMachineExports.setThePassword; +publicApi.serializeHost = urlStateMachineExports.serializeHost; +publicApi.serializeInteger = urlStateMachineExports.serializeInteger; +publicApi.parseURL = urlStateMachineExports.parseURL; + +// 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$3.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 = require('encoding').convert; +} catch (e) {} + +const INTERNALS = Symbol('Body internals'); + +// fix an issue where "PassThrough" isn't a named export for node <10 +const PassThrough = Stream$3.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$3) ; 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$3) { + 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$3)) { + 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 +}); + +const INTERNALS$1 = Symbol('Response internals'); + +// fix an issue where "STATUS_CODES" aren't a named export for node <10 +const STATUS_CODES = require$$0$a.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$1 = require$$0$e.URL || publicApi.URL; + +// fix an issue where "format", "parse" aren't a named export for node <10 +const parse_url = require$$0$e.parse; +const format_url = require$$0$e.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$1(urlStr).toString(); + } + + // Fallback to old implementation for arbitrary URLs + return parse_url(urlStr); +} + +'destroy' in Stream$3.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 } +}); + +/** + * 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'; + +require$$0$e.URL || publicApi.URL; + +// fix an issue where "PassThrough", "resolve" aren't a named export for node <10 +Stream$3.PassThrough; + +var getAPIDefinitionType2 = getAPIDefinitionType; + +function getUsedRefs(schema) { + return query(["$..['$ref']"], schema); +} +function accumulateUsedRefs(schema, $refs, $ref) { + let $refSchema; + if (typeof $ref === "string") + $refSchema = jsonpointer.get(schema, $ref.substring(1)); + if ($refSchema === void 0) { + return; + } + getUsedRefs($refSchema).forEach(({ value: currRef }) => { + if ($refs.has(currRef)) { + return; + } + $refs.add(currRef); + accumulateUsedRefs(schema, $refs, currRef); + }); +} +function reducer(definition, opts = {}) { + const reduceTags = "tags" in opts ? opts.tags.map((tag) => tag.toLowerCase()) : []; + const reducePaths = "paths" in opts ? Object.entries(opts.paths).reduce((acc, [key, value]) => { + const newKey = key.toLowerCase(); + const newValue = Array.isArray(value) ? value.map((v) => v.toLowerCase()) : value.toLowerCase(); + acc[newKey] = newValue; + return acc; + }, {}) : {}; + const $refs = /* @__PURE__ */ new Set(); + const usedTags = /* @__PURE__ */ new Set(); + if (getAPIDefinitionType2(definition) !== "openapi") { + throw new Error("Sorry, only OpenAPI definitions are supported."); + } + const reduced = JSON.parse(JSON.stringify(definition)); + if ("security" in reduced) { + Object.values(reduced.security).forEach((sec) => { + Object.keys(sec).forEach((scheme) => { + $refs.add(`#/components/securitySchemes/${scheme}`); + }); + }); + } + if ("paths" in reduced) { + Object.keys(reduced.paths).forEach((path) => { + const pathLC = path.toLowerCase(); + if (Object.keys(reducePaths).length) { + if (!(pathLC in reducePaths)) { + delete reduced.paths[path]; + return; + } + } + Object.keys(reduced.paths[path]).forEach((method) => { + if (method !== "parameters") { + if (Object.keys(reducePaths).length) { + if (reducePaths[pathLC] !== "*" && Array.isArray(reducePaths[pathLC]) && !reducePaths[pathLC].includes(method)) { + delete reduced.paths[path][method]; + return; + } + } + } + const operation = reduced.paths[path][method]; + if (reduceTags.length) { + if (!("tags" in operation)) { + delete reduced.paths[path][method]; + return; + } else if (!operation.tags.filter((tag) => reduceTags.includes(tag.toLowerCase())).length) { + delete reduced.paths[path][method]; + return; + } + } + if ("tags" in operation) { + operation.tags.forEach((tag) => { + usedTags.add(tag); + }); + } + getUsedRefs(operation).forEach(({ value: ref }) => { + $refs.add(ref); + }); + if ("security" in operation) { + Object.values(operation.security).forEach((sec) => { + Object.keys(sec).forEach((scheme) => { + $refs.add(`#/components/securitySchemes/${scheme}`); + }); + }); + } + }); + if (!Object.keys(reduced.paths[path]).length) { + delete reduced.paths[path]; + } + }); + if (!Object.keys(reduced.paths).length) { + throw new Error("All paths in the API definition were removed. Did you supply the right path name to reduce by?"); + } + } + $refs.forEach(($ref) => accumulateUsedRefs(reduced, $refs, $ref)); + if ("components" in reduced) { + Object.keys(reduced.components).forEach((componentType) => { + Object.keys(reduced.components[componentType]).forEach((component) => { + if (!$refs.has(`#/components/${componentType}/${component}`)) { + delete reduced.components[componentType][component]; + } + }); + if (!Object.keys(reduced.components[componentType]).length) { + delete reduced.components[componentType]; + } + }); + if (!Object.keys(reduced.components).length) { + delete reduced.components; + } + } + if ("tags" in reduced) { + reduced.tags.forEach((tag, k) => { + if (!usedTags.has(tag.name)) { + delete reduced.tags[k]; + } + }); + reduced.tags = reduced.tags.filter(Boolean); + if (!reduced.tags.length) { + delete reduced.tags; + } + } + return reduced; +} + +class OpenAPIReduceCommand extends Command { + constructor() { + super(); + this.command = 'openapi:reduce'; + this.usage = 'openapi:reduce [file|url] [options]'; + this.description = 'Reduce an OpenAPI definition into a smaller subset.'; + this.cmdCategory = CommandCategories.APIS; + this.hiddenArgs = ['spec']; + this.args = [ + { + name: 'spec', + type: String, + defaultOption: true, + }, + { + name: 'tag', + type: String, + multiple: true, + description: 'Tags to reduce by', + }, + { + name: 'path', + type: String, + multiple: true, + description: 'Paths to reduce by', + }, + { + name: 'method', + type: String, + multiple: true, + description: 'Methods to reduce by (can only be used alongside the `path` option)', + }, + { + name: 'out', + type: String, + description: 'Output file path to write reduced file to', + }, + this.getTitleArg(), + this.getWorkingDirArg(), + ]; + } + async run(opts) { + await super.run(opts); + const { spec, title, workingDirectory } = opts; + if (workingDirectory) { + const previousWorkingDirectory = process.cwd(); + process.chdir(workingDirectory); + Command.debug(`switching working directory from ${previousWorkingDirectory} to ${process.cwd()}`); + } + const { preparedSpec, specPath, specType } = await prepareOas(spec, 'openapi:reduce', { title }); + const parsedPreparedSpec = JSON.parse(preparedSpec); + if (specType !== 'OpenAPI') { + throw new Error('Sorry, this reducer feature in rdme only supports OpenAPI 3.0+ definitions.'); + } + if ((opts.path?.length || opts.method?.length) && opts.tag?.length) { + throw new Error('You can pass in either tags or paths/methods, but not both.'); + } + prompts$1.override({ + reduceBy: opts.tag?.length ? 'tags' : opts.path?.length ? 'paths' : undefined, + tags: opts.tag, + paths: opts.path, + methods: opts.method, + outputPath: opts.out, + }); + const promptResults = await promptTerminal([ + { + type: 'select', + name: 'reduceBy', + message: 'Would you like to reduce by paths or tags?', + choices: [ + { title: 'Tags', value: 'tags' }, + { title: 'Paths', value: 'paths' }, + ], + }, + { + type: (prev, values) => (values.reduceBy === 'tags' ? 'multiselect' : null), + name: 'tags', + message: 'Choose which tags to reduce by:', + min: 1, + choices: () => { + const tags = new Oas(parsedPreparedSpec).getTags(); + return tags.map(tag => ({ + title: tag, + value: tag, + })); + }, + }, + { + type: (prev, values) => (values.reduceBy === 'paths' ? 'multiselect' : null), + name: 'paths', + message: 'Choose which paths to reduce by:', + min: 1, + choices: () => { + return Object.keys(parsedPreparedSpec.paths).map(p => ({ + title: p, + value: p, + })); + }, + }, + { + type: (prev, values) => (values.reduceBy === 'paths' ? 'multiselect' : null), + name: 'methods', + message: 'Choose which HTTP methods that are available across these paths to reduce by:', + min: 1, + choices: (prev, values) => { + const paths = values.paths; + let methods = paths + .map((p) => Object.keys(parsedPreparedSpec.paths[p] || {})) + .flat() + .filter((method) => method.toLowerCase() !== 'parameters'); + // We have to catch this case so prompt doesn't crash + if (!methods.length && !opts.method?.length) { + throw new Error('All paths in the API definition were removed. Did you supply the right path name to reduce by?'); + } + methods = [...new Set(methods)]; + methods.sort(); + return methods.map((method) => ({ + title: method.toUpperCase(), + value: method, + })); + }, + }, + { + type: 'text', + name: 'outputPath', + message: 'Enter the path to save your reduced API definition to:', + initial: () => { + const extension = path$c.extname(specPath); + return `${path$c.basename(specPath).split(extension)[0]}.reduced${extension}`; + }, + validate: value => validateFilePath(value), + }, + ]); + Command.debug(`reducing by ${promptResults.reduceBy}`); + Command.debug(`options being supplied to the reducer: ${JSON.stringify({ + tags: promptResults.tags, + paths: promptResults.paths, + methods: promptResults.methods, + })}`); + Command.debug(`about to reduce spec located at ${specPath}`); + const spinner = ora({ ...oraOptions() }); + spinner.start('Reducing your API definition...'); + let reducedSpec; + try { + reducedSpec = reducer(parsedPreparedSpec, { + tags: promptResults.tags || [], + paths: (promptResults.paths || []).reduce((acc, p) => { + acc[p] = promptResults.methods; + return acc; + }, {}), + }); + spinner.succeed(`${spinner.text} done! ✅`); + } + catch (err) { + Command.debug(`reducer err: ${err.message}`); + spinner.fail(); + throw err; + } + Command.debug(`saving reduced spec to ${promptResults.outputPath}`); + fs$i.writeFileSync(promptResults.outputPath, JSON.stringify(reducedSpec, null, 2)); + Command.debug('reduced spec saved'); + return Promise.resolve(chalk$5.green(`Your reduced API definition has been saved to ${promptResults.outputPath}! 🤏`)); + } +} + +class OpenAPIValidateCommand extends Command { + constructor() { + super(); + this.command = 'openapi:validate'; + this.usage = 'openapi:validate [file|url] [options]'; + this.description = 'Validate your OpenAPI/Swagger definition.'; + this.cmdCategory = CommandCategories.APIS; + this.hiddenArgs = ['spec']; + this.args = [ + { + name: 'spec', + type: String, + defaultOption: true, + }, + this.getWorkingDirArg(), + this.getGitHubArg(), + ]; + } + async run(opts) { + await super.run(opts); + const { spec, workingDirectory } = opts; + if (workingDirectory) { + const previousWorkingDirectory = process.cwd(); + process.chdir(workingDirectory); + Command.debug(`switching working directory from ${previousWorkingDirectory} to ${process.cwd()}`); + } + const { specPath, specType } = await prepareOas(spec, 'openapi:validate'); + return Promise.resolve(chalk$5.green(`${specPath} is a valid ${specType} API definition!`)).then(msg => createGHA(msg, this.command, this.args, { ...opts, spec: specPath })); + } +} + +var __decorate$1 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +}; +let SwaggerCommand = class SwaggerCommand extends OpenAPICommand { + constructor() { + super(); + this.command = 'swagger'; + this.usage = 'swagger [file] [options]'; + this.description = 'Alias for `rdme openapi`. [deprecated]'; + } + async run(opts) { + Command.warn('`rdme swagger` has been deprecated. Please use `rdme openapi` instead.'); + return super.run(opts); + } +}; +SwaggerCommand = __decorate$1([ + isHidden$1 +], SwaggerCommand); +var SwaggerCommand$1 = SwaggerCommand; + +var __decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +}; +let ValidateAliasCommand = class ValidateAliasCommand extends OpenAPIValidateCommand { + constructor() { + super(); + this.command = 'validate'; + this.usage = 'validate [file] [options]'; + this.description = 'Alias for `rdme openapi:validate` [deprecated].'; + } + async run(opts) { + Command.warn('`rdme validate` has been deprecated. Please use `rdme openapi:validate` instead.'); + return super.run(opts); + } +}; +ValidateAliasCommand = __decorate([ + isHidden$1 +], ValidateAliasCommand); +var ValidateAliasCommand$1 = ValidateAliasCommand; + +/** + * Takes a CLI flag that is expected to be a 'true' or 'false' string + * and casts it to a boolean. + */ +function castStringOptToBool(opt, optName) { + if (!opt) { + return undefined; + } + if (opt === 'true') { + return true; + } + if (opt === 'false') { + return false; + } + throw new Error(`Invalid option passed for '${optName}'. Must be 'true' or 'false'.`); +} + +class CreateVersionCommand extends Command { + constructor() { + super(); + this.command = 'versions:create'; + this.usage = 'versions:create [options]'; + this.description = 'Create a new version for your project.'; + this.cmdCategory = CommandCategories.VERSIONS; + this.hiddenArgs = ['version']; + this.args = [ + this.getKeyArg(), + { + name: 'fork', + type: String, + description: "The semantic version which you'd like to fork from.", + }, + ...this.getVersionOpts(), + ]; + } + async run(opts) { + await super.run(opts); + let versionList; + const { key, version, fork, codename, main, beta, deprecated, isPublic } = opts; + if (!version || !semver$1.valid(semver$1.coerce(version))) { + return Promise.reject(new Error(`Please specify a semantic version. See \`${config.cli} help ${this.command}\` for help.`)); + } + if (!fork) { + versionList = await readmeAPIFetch('/api/v1/version', { + method: 'get', + headers: cleanHeaders(key), + }).then(handleRes); + } + const versionPrompt$1 = versionPrompt(versionList || []); + prompts$1.override({ + from: fork, + is_beta: castStringOptToBool(beta, 'beta'), + is_deprecated: castStringOptToBool(deprecated, 'deprecated'), + is_public: castStringOptToBool(isPublic, 'isPublic'), + is_stable: castStringOptToBool(main, 'main'), + }); + const promptResponse = await promptTerminal(versionPrompt$1); + const body = { + codename, + version, + from: promptResponse.from, + is_beta: promptResponse.is_beta, + is_deprecated: promptResponse.is_deprecated, + // if the "is public" question was never asked, we should omit that from the payload + is_hidden: typeof promptResponse.is_public === 'undefined' ? undefined : !promptResponse.is_public, + is_stable: promptResponse.is_stable, + }; + return readmeAPIFetch('/api/v1/version', { + method: 'post', + headers: cleanHeaders(key, new Headers$2({ + Accept: 'application/json', + 'Content-Type': 'application/json', + })), + body: JSON.stringify(body), + }) + .then(handleRes) + .then(() => { + return Promise.resolve(`Version ${version} created successfully.`); + }); + } +} + +class DeleteVersionCommand extends Command { + constructor() { + super(); + this.command = 'versions:delete'; + this.usage = 'versions:delete [options]'; + this.description = 'Delete a version associated with your ReadMe project.'; + this.cmdCategory = CommandCategories.VERSIONS; + this.hiddenArgs = ['version']; + this.args = [ + this.getKeyArg(), + { + name: 'version', + type: String, + defaultOption: true, + }, + ]; + } + async run(opts) { + await super.run(opts); + const { key, version } = opts; + const selectedVersion = await getProjectVersion(version, key); + Command.debug(`selectedVersion: ${selectedVersion}`); + return readmeAPIFetch(`/api/v1/version/${selectedVersion}`, { + method: 'delete', + headers: cleanHeaders(key), + }) + .then(handleRes) + .then(() => { + return Promise.resolve(`Version ${selectedVersion} deleted successfully.`); + }); + } +} + +class VersionsCommand extends Command { + constructor() { + super(); + this.command = 'versions'; + this.usage = 'versions [options]'; + this.description = 'List versions available in your project or get a version by SemVer (https://semver.org/).'; + this.cmdCategory = CommandCategories.VERSIONS; + this.args = [ + this.getKeyArg(), + { + name: 'version', + type: String, + description: 'A specific project version to view.', + }, + ]; + } + async run(opts) { + await super.run(opts); + const { key, version } = opts; + const uri = version ? `/api/v1/version/${version}` : '/api/v1/version'; + return readmeAPIFetch(uri, { + method: 'get', + headers: cleanHeaders(key), + }) + .then(handleRes) + .then(data => Promise.resolve(JSON.stringify(data, null, 2))); + } +} + +class UpdateVersionCommand extends Command { + constructor() { + super(); + this.command = 'versions:update'; + this.usage = 'versions:update [options]'; + this.description = 'Update an existing version for your project.'; + this.cmdCategory = CommandCategories.VERSIONS; + this.hiddenArgs = ['version']; + this.args = [ + this.getKeyArg(), + { + name: 'newVersion', + type: String, + description: 'What should the version be renamed to?', + }, + ...this.getVersionOpts(), + ]; + } + async run(opts) { + await super.run(opts); + const { key, version, newVersion, codename, main, beta, isPublic, deprecated } = opts; + const selectedVersion = await getProjectVersion(version, key); + Command.debug(`selectedVersion: ${selectedVersion}`); + // TODO: I think this fetch here is unnecessary but + // it will require a bigger refactor of getProjectVersion + const foundVersion = await readmeAPIFetch(`/api/v1/version/${selectedVersion}`, { + method: 'get', + headers: cleanHeaders(key), + }).then(handleRes); + prompts$1.override({ + is_beta: castStringOptToBool(beta, 'beta'), + is_deprecated: castStringOptToBool(deprecated, 'deprecated'), + is_public: castStringOptToBool(isPublic, 'isPublic'), + is_stable: castStringOptToBool(main, 'main'), + newVersion, + }); + const promptResponse = await promptTerminal(versionPrompt([], foundVersion)); + const body = { + codename, + // fall back to current version if user didn't enter one + version: promptResponse.newVersion || version, + is_beta: promptResponse.is_beta, + is_deprecated: promptResponse.is_deprecated, + // if the "is public" question was never asked, we should omit that from the payload + is_hidden: typeof promptResponse.is_public === 'undefined' ? undefined : !promptResponse.is_public, + is_stable: promptResponse.is_stable, + }; + return readmeAPIFetch(`/api/v1/version/${selectedVersion}`, { + method: 'put', + headers: cleanHeaders(key, new Headers$2({ + Accept: 'application/json', + 'Content-Type': 'application/json', + })), + body: JSON.stringify(body), + }) + .then(handleRes) + .then(() => { + return Promise.resolve(`Version ${selectedVersion} updated successfully.`); + }); + } +} + +class WhoAmICommand extends Command { + constructor() { + super(); + this.command = 'whoami'; + this.usage = 'whoami'; + this.description = 'Displays the current user and project authenticated with ReadMe.'; + this.cmdCategory = CommandCategories.ADMIN; + this.args = []; + } + async run(opts) { + await super.run(opts); + const { email, project } = getCurrentConfig(); + if (!email || !project) { + return Promise.reject(new Error(`Please login using \`${config.cli} login\`.`)); + } + return Promise.resolve(`You are currently logged in as ${chalk$5.green(email)} to the ${chalk$5.blue(project)} project.`); + } +} + +const commands = { + categories: CategoriesCommand, + 'categories:create': CategoriesCreateCommand, + changelogs: ChangelogsCommand$1, + custompages: CustomPagesCommand$1, + docs: DocsCommand, + 'docs:prune': DocsPruneCommand, + 'docs:edit': DocsEditCommand$1, + guides: GuidesCommand, + 'guides:prune': GuidesPruneCommand, + versions: VersionsCommand, + 'versions:create': CreateVersionCommand, + 'versions:delete': DeleteVersionCommand, + 'versions:update': UpdateVersionCommand, + login: LoginCommand, + logout: LogoutCommand, + oas: OASCommand$1, + open: OpenCommand, + openapi: OpenAPICommand, + 'openapi:convert': OpenAPIConvertCommand, + 'openapi:inspect': OpenAPIInspectCommand, + 'openapi:reduce': OpenAPIReduceCommand, + 'openapi:validate': OpenAPIValidateCommand, + swagger: SwaggerCommand$1, + validate: ValidateAliasCommand$1, + whoami: WhoAmICommand, +}; + +function getCategories() { + return { + apis: { + description: 'OpenAPI / Swagger', + commands: [], + }, + docs: { + description: 'Docs (a.k.a. Guides)', + commands: [], + }, + changelogs: { + description: 'Changelog', + commands: [], + }, + custompages: { + description: 'Custom Pages', + commands: [], + }, + versions: { + description: 'Versions', + commands: [], + }, + categories: { + description: 'Categories', + commands: [], + }, + admin: { + description: 'Administration', + commands: [], + }, + utilities: { + description: 'Other useful commands', + commands: [], + }, + }; +} +function list() { + return Object.entries(commands).map(([name, Cmd]) => { + return { + name, + command: new Cmd(), + }; + }); +} +function load(cmd) { + if (!(cmd in commands)) { + throw new Error('Command not found.'); + } + return new commands[cmd](); +} +function listByCategory() { + const categories = getCategories(); + const cmds = list(); + cmds.forEach(c => { + categories[c.command.cmdCategory].commands.push({ + name: c.command.command, + description: c.command.description, + hidden: c.command.hidden, + }); + }); + return categories; +} +function getSimilar(cmdCategory, excludeCommand) { + const categories = listByCategory(); + return categories[cmdCategory].commands.filter(cmd => cmd.name !== excludeCommand && !cmd.hidden); +} + +/** + * Takes any input and guarantees an array back. + * + * - Converts array-like objects (e.g. `arguments`, `Set`) to a real array. + * - Converts `undefined` to an empty array. + * - Converts any another other, singular value (including `null`, objects and iterables other than `Set`) into an array containing that value. + * - Ignores input which is already an array. + * + * @module array-back + * @example + * > const arrayify = require('array-back') + * + * > arrayify(undefined) + * [] + * + * > arrayify(null) + * [ null ] + * + * > arrayify(0) + * [ 0 ] + * + * > arrayify([ 1, 2 ]) + * [ 1, 2 ] + * + * > arrayify(new Set([ 1, 2 ])) + * [ 1, 2 ] + * + * > function f(){ return arrayify(arguments); } + * > f(1,2,3) + * [ 1, 2, 3 ] + */ + +function isObject$4 (input) { + return typeof input === 'object' && input !== null +} + +function isArrayLike$4 (input) { + return isObject$4(input) && typeof input.length === 'number' +} + +/** + * @param {*} - The input value to convert to an array + * @returns {Array} + * @alias module:array-back + */ +function arrayify$1 (input) { + if (Array.isArray(input)) { + return input + } else if (input === undefined) { + return [] + } else if (isArrayLike$4(input) || input instanceof Set) { + return Array.from(input) + } else { + return [input] + } +} + +var ansiStyles$1 = {exports: {}}; + +var colorName; +var hasRequiredColorName; + +function requireColorName () { + if (hasRequiredColorName) return colorName; + hasRequiredColorName = 1; + + colorName = { + "aliceblue": [240, 248, 255], + "antiquewhite": [250, 235, 215], + "aqua": [0, 255, 255], + "aquamarine": [127, 255, 212], + "azure": [240, 255, 255], + "beige": [245, 245, 220], + "bisque": [255, 228, 196], + "black": [0, 0, 0], + "blanchedalmond": [255, 235, 205], + "blue": [0, 0, 255], + "blueviolet": [138, 43, 226], + "brown": [165, 42, 42], + "burlywood": [222, 184, 135], + "cadetblue": [95, 158, 160], + "chartreuse": [127, 255, 0], + "chocolate": [210, 105, 30], + "coral": [255, 127, 80], + "cornflowerblue": [100, 149, 237], + "cornsilk": [255, 248, 220], + "crimson": [220, 20, 60], + "cyan": [0, 255, 255], + "darkblue": [0, 0, 139], + "darkcyan": [0, 139, 139], + "darkgoldenrod": [184, 134, 11], + "darkgray": [169, 169, 169], + "darkgreen": [0, 100, 0], + "darkgrey": [169, 169, 169], + "darkkhaki": [189, 183, 107], + "darkmagenta": [139, 0, 139], + "darkolivegreen": [85, 107, 47], + "darkorange": [255, 140, 0], + "darkorchid": [153, 50, 204], + "darkred": [139, 0, 0], + "darksalmon": [233, 150, 122], + "darkseagreen": [143, 188, 143], + "darkslateblue": [72, 61, 139], + "darkslategray": [47, 79, 79], + "darkslategrey": [47, 79, 79], + "darkturquoise": [0, 206, 209], + "darkviolet": [148, 0, 211], + "deeppink": [255, 20, 147], + "deepskyblue": [0, 191, 255], + "dimgray": [105, 105, 105], + "dimgrey": [105, 105, 105], + "dodgerblue": [30, 144, 255], + "firebrick": [178, 34, 34], + "floralwhite": [255, 250, 240], + "forestgreen": [34, 139, 34], + "fuchsia": [255, 0, 255], + "gainsboro": [220, 220, 220], + "ghostwhite": [248, 248, 255], + "gold": [255, 215, 0], + "goldenrod": [218, 165, 32], + "gray": [128, 128, 128], + "green": [0, 128, 0], + "greenyellow": [173, 255, 47], + "grey": [128, 128, 128], + "honeydew": [240, 255, 240], + "hotpink": [255, 105, 180], + "indianred": [205, 92, 92], + "indigo": [75, 0, 130], + "ivory": [255, 255, 240], + "khaki": [240, 230, 140], + "lavender": [230, 230, 250], + "lavenderblush": [255, 240, 245], + "lawngreen": [124, 252, 0], + "lemonchiffon": [255, 250, 205], + "lightblue": [173, 216, 230], + "lightcoral": [240, 128, 128], + "lightcyan": [224, 255, 255], + "lightgoldenrodyellow": [250, 250, 210], + "lightgray": [211, 211, 211], + "lightgreen": [144, 238, 144], + "lightgrey": [211, 211, 211], + "lightpink": [255, 182, 193], + "lightsalmon": [255, 160, 122], + "lightseagreen": [32, 178, 170], + "lightskyblue": [135, 206, 250], + "lightslategray": [119, 136, 153], + "lightslategrey": [119, 136, 153], + "lightsteelblue": [176, 196, 222], + "lightyellow": [255, 255, 224], + "lime": [0, 255, 0], + "limegreen": [50, 205, 50], + "linen": [250, 240, 230], + "magenta": [255, 0, 255], + "maroon": [128, 0, 0], + "mediumaquamarine": [102, 205, 170], + "mediumblue": [0, 0, 205], + "mediumorchid": [186, 85, 211], + "mediumpurple": [147, 112, 219], + "mediumseagreen": [60, 179, 113], + "mediumslateblue": [123, 104, 238], + "mediumspringgreen": [0, 250, 154], + "mediumturquoise": [72, 209, 204], + "mediumvioletred": [199, 21, 133], + "midnightblue": [25, 25, 112], + "mintcream": [245, 255, 250], + "mistyrose": [255, 228, 225], + "moccasin": [255, 228, 181], + "navajowhite": [255, 222, 173], + "navy": [0, 0, 128], + "oldlace": [253, 245, 230], + "olive": [128, 128, 0], + "olivedrab": [107, 142, 35], + "orange": [255, 165, 0], + "orangered": [255, 69, 0], + "orchid": [218, 112, 214], + "palegoldenrod": [238, 232, 170], + "palegreen": [152, 251, 152], + "paleturquoise": [175, 238, 238], + "palevioletred": [219, 112, 147], + "papayawhip": [255, 239, 213], + "peachpuff": [255, 218, 185], + "peru": [205, 133, 63], + "pink": [255, 192, 203], + "plum": [221, 160, 221], + "powderblue": [176, 224, 230], + "purple": [128, 0, 128], + "rebeccapurple": [102, 51, 153], + "red": [255, 0, 0], + "rosybrown": [188, 143, 143], + "royalblue": [65, 105, 225], + "saddlebrown": [139, 69, 19], + "salmon": [250, 128, 114], + "sandybrown": [244, 164, 96], + "seagreen": [46, 139, 87], + "seashell": [255, 245, 238], + "sienna": [160, 82, 45], + "silver": [192, 192, 192], + "skyblue": [135, 206, 235], + "slateblue": [106, 90, 205], + "slategray": [112, 128, 144], + "slategrey": [112, 128, 144], + "snow": [255, 250, 250], + "springgreen": [0, 255, 127], + "steelblue": [70, 130, 180], + "tan": [210, 180, 140], + "teal": [0, 128, 128], + "thistle": [216, 191, 216], + "tomato": [255, 99, 71], + "turquoise": [64, 224, 208], + "violet": [238, 130, 238], + "wheat": [245, 222, 179], + "white": [255, 255, 255], + "whitesmoke": [245, 245, 245], + "yellow": [255, 255, 0], + "yellowgreen": [154, 205, 50] + }; + return colorName; +} + +/* MIT license */ + +var conversions; +var hasRequiredConversions; + +function requireConversions () { + if (hasRequiredConversions) return conversions; + hasRequiredConversions = 1; + /* eslint-disable no-mixed-operators */ + const cssKeywords = requireColorName(); + + // NOTE: conversions should only return primitive values (i.e. arrays, or + // values that give correct `typeof` results). + // do not use box values types (i.e. Number(), String(), etc.) + + const reverseKeywords = {}; + for (const key of Object.keys(cssKeywords)) { + reverseKeywords[cssKeywords[key]] = key; + } + + const convert = { + rgb: {channels: 3, labels: 'rgb'}, + hsl: {channels: 3, labels: 'hsl'}, + hsv: {channels: 3, labels: 'hsv'}, + hwb: {channels: 3, labels: 'hwb'}, + cmyk: {channels: 4, labels: 'cmyk'}, + xyz: {channels: 3, labels: 'xyz'}, + lab: {channels: 3, labels: 'lab'}, + lch: {channels: 3, labels: 'lch'}, + hex: {channels: 1, labels: ['hex']}, + keyword: {channels: 1, labels: ['keyword']}, + ansi16: {channels: 1, labels: ['ansi16']}, + ansi256: {channels: 1, labels: ['ansi256']}, + hcg: {channels: 3, labels: ['h', 'c', 'g']}, + apple: {channels: 3, labels: ['r16', 'g16', 'b16']}, + gray: {channels: 1, labels: ['gray']} + }; + + conversions = convert; + + // Hide .channels and .labels properties + for (const model of Object.keys(convert)) { + if (!('channels' in convert[model])) { + throw new Error('missing channels property: ' + model); + } + + if (!('labels' in convert[model])) { + throw new Error('missing channel labels property: ' + model); + } + + if (convert[model].labels.length !== convert[model].channels) { + throw new Error('channel and label counts mismatch: ' + model); + } + + const {channels, labels} = convert[model]; + delete convert[model].channels; + delete convert[model].labels; + Object.defineProperty(convert[model], 'channels', {value: channels}); + Object.defineProperty(convert[model], 'labels', {value: labels}); + } + + convert.rgb.hsl = function (rgb) { + const r = rgb[0] / 255; + const g = rgb[1] / 255; + const b = rgb[2] / 255; + const min = Math.min(r, g, b); + const max = Math.max(r, g, b); + const delta = max - min; + let h; + let s; + + if (max === min) { + h = 0; + } else if (r === max) { + h = (g - b) / delta; + } else if (g === max) { + h = 2 + (b - r) / delta; + } else if (b === max) { + h = 4 + (r - g) / delta; + } + + h = Math.min(h * 60, 360); + + if (h < 0) { + h += 360; + } + + const l = (min + max) / 2; + + if (max === min) { + s = 0; + } else if (l <= 0.5) { + s = delta / (max + min); + } else { + s = delta / (2 - max - min); + } + + return [h, s * 100, l * 100]; + }; + + convert.rgb.hsv = function (rgb) { + let rdif; + let gdif; + let bdif; + let h; + let s; + + const r = rgb[0] / 255; + const g = rgb[1] / 255; + const b = rgb[2] / 255; + const v = Math.max(r, g, b); + const diff = v - Math.min(r, g, b); + const diffc = function (c) { + return (v - c) / 6 / diff + 1 / 2; + }; + + if (diff === 0) { + h = 0; + s = 0; + } else { + s = diff / v; + rdif = diffc(r); + gdif = diffc(g); + bdif = diffc(b); + + if (r === v) { + h = bdif - gdif; + } else if (g === v) { + h = (1 / 3) + rdif - bdif; + } else if (b === v) { + h = (2 / 3) + gdif - rdif; + } + + if (h < 0) { + h += 1; + } else if (h > 1) { + h -= 1; + } + } + + return [ + h * 360, + s * 100, + v * 100 + ]; + }; + + convert.rgb.hwb = function (rgb) { + const r = rgb[0]; + const g = rgb[1]; + let b = rgb[2]; + const h = convert.rgb.hsl(rgb)[0]; + const w = 1 / 255 * Math.min(r, Math.min(g, b)); + + b = 1 - 1 / 255 * Math.max(r, Math.max(g, b)); + + return [h, w * 100, b * 100]; + }; + + convert.rgb.cmyk = function (rgb) { + const r = rgb[0] / 255; + const g = rgb[1] / 255; + const b = rgb[2] / 255; + + const k = Math.min(1 - r, 1 - g, 1 - b); + const c = (1 - r - k) / (1 - k) || 0; + const m = (1 - g - k) / (1 - k) || 0; + const y = (1 - b - k) / (1 - k) || 0; + + return [c * 100, m * 100, y * 100, k * 100]; + }; + + function comparativeDistance(x, y) { + /* + See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance + */ + return ( + ((x[0] - y[0]) ** 2) + + ((x[1] - y[1]) ** 2) + + ((x[2] - y[2]) ** 2) + ); + } + + convert.rgb.keyword = function (rgb) { + const reversed = reverseKeywords[rgb]; + if (reversed) { + return reversed; + } + + let currentClosestDistance = Infinity; + let currentClosestKeyword; + + for (const keyword of Object.keys(cssKeywords)) { + const value = cssKeywords[keyword]; + + // Compute comparative distance + const distance = comparativeDistance(rgb, value); + + // Check if its less, if so set as closest + if (distance < currentClosestDistance) { + currentClosestDistance = distance; + currentClosestKeyword = keyword; + } + } + + return currentClosestKeyword; + }; + + convert.keyword.rgb = function (keyword) { + return cssKeywords[keyword]; + }; + + convert.rgb.xyz = function (rgb) { + let r = rgb[0] / 255; + let g = rgb[1] / 255; + let b = rgb[2] / 255; + + // Assume sRGB + r = r > 0.04045 ? (((r + 0.055) / 1.055) ** 2.4) : (r / 12.92); + g = g > 0.04045 ? (((g + 0.055) / 1.055) ** 2.4) : (g / 12.92); + b = b > 0.04045 ? (((b + 0.055) / 1.055) ** 2.4) : (b / 12.92); + + const x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805); + const y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722); + const z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505); + + return [x * 100, y * 100, z * 100]; + }; + + convert.rgb.lab = function (rgb) { + const xyz = convert.rgb.xyz(rgb); + let x = xyz[0]; + let y = xyz[1]; + let z = xyz[2]; + + x /= 95.047; + y /= 100; + z /= 108.883; + + x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116); + y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116); + z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116); + + const l = (116 * y) - 16; + const a = 500 * (x - y); + const b = 200 * (y - z); + + return [l, a, b]; + }; + + convert.hsl.rgb = function (hsl) { + const h = hsl[0] / 360; + const s = hsl[1] / 100; + const l = hsl[2] / 100; + let t2; + let t3; + let val; + + if (s === 0) { + val = l * 255; + return [val, val, val]; + } + + if (l < 0.5) { + t2 = l * (1 + s); + } else { + t2 = l + s - l * s; + } + + const t1 = 2 * l - t2; + + const rgb = [0, 0, 0]; + for (let i = 0; i < 3; i++) { + t3 = h + 1 / 3 * -(i - 1); + if (t3 < 0) { + t3++; + } + + if (t3 > 1) { + t3--; + } + + if (6 * t3 < 1) { + val = t1 + (t2 - t1) * 6 * t3; + } else if (2 * t3 < 1) { + val = t2; + } else if (3 * t3 < 2) { + val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; + } else { + val = t1; + } + + rgb[i] = val * 255; + } + + return rgb; + }; + + convert.hsl.hsv = function (hsl) { + const h = hsl[0]; + let s = hsl[1] / 100; + let l = hsl[2] / 100; + let smin = s; + const lmin = Math.max(l, 0.01); + + l *= 2; + s *= (l <= 1) ? l : 2 - l; + smin *= lmin <= 1 ? lmin : 2 - lmin; + const v = (l + s) / 2; + const sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s); + + return [h, sv * 100, v * 100]; + }; + + convert.hsv.rgb = function (hsv) { + const h = hsv[0] / 60; + const s = hsv[1] / 100; + let v = hsv[2] / 100; + const hi = Math.floor(h) % 6; + + const f = h - Math.floor(h); + const p = 255 * v * (1 - s); + const q = 255 * v * (1 - (s * f)); + const t = 255 * v * (1 - (s * (1 - f))); + v *= 255; + + switch (hi) { + case 0: + return [v, t, p]; + case 1: + return [q, v, p]; + case 2: + return [p, v, t]; + case 3: + return [p, q, v]; + case 4: + return [t, p, v]; + case 5: + return [v, p, q]; + } + }; + + convert.hsv.hsl = function (hsv) { + const h = hsv[0]; + const s = hsv[1] / 100; + const v = hsv[2] / 100; + const vmin = Math.max(v, 0.01); + let sl; + let l; + + l = (2 - s) * v; + const lmin = (2 - s) * vmin; + sl = s * vmin; + sl /= (lmin <= 1) ? lmin : 2 - lmin; + sl = sl || 0; + l /= 2; + + return [h, sl * 100, l * 100]; + }; + + // http://dev.w3.org/csswg/css-color/#hwb-to-rgb + convert.hwb.rgb = function (hwb) { + const h = hwb[0] / 360; + let wh = hwb[1] / 100; + let bl = hwb[2] / 100; + const ratio = wh + bl; + let f; + + // Wh + bl cant be > 1 + if (ratio > 1) { + wh /= ratio; + bl /= ratio; + } + + const i = Math.floor(6 * h); + const v = 1 - bl; + f = 6 * h - i; + + if ((i & 0x01) !== 0) { + f = 1 - f; + } + + const n = wh + f * (v - wh); // Linear interpolation + + let r; + let g; + let b; + /* eslint-disable max-statements-per-line,no-multi-spaces */ + switch (i) { + default: + case 6: + case 0: r = v; g = n; b = wh; break; + case 1: r = n; g = v; b = wh; break; + case 2: r = wh; g = v; b = n; break; + case 3: r = wh; g = n; b = v; break; + case 4: r = n; g = wh; b = v; break; + case 5: r = v; g = wh; b = n; break; + } + /* eslint-enable max-statements-per-line,no-multi-spaces */ + + return [r * 255, g * 255, b * 255]; + }; + + convert.cmyk.rgb = function (cmyk) { + const c = cmyk[0] / 100; + const m = cmyk[1] / 100; + const y = cmyk[2] / 100; + const k = cmyk[3] / 100; + + const r = 1 - Math.min(1, c * (1 - k) + k); + const g = 1 - Math.min(1, m * (1 - k) + k); + const b = 1 - Math.min(1, y * (1 - k) + k); + + return [r * 255, g * 255, b * 255]; + }; + + convert.xyz.rgb = function (xyz) { + const x = xyz[0] / 100; + const y = xyz[1] / 100; + const z = xyz[2] / 100; + let r; + let g; + let b; + + r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986); + g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415); + b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570); + + // Assume sRGB + r = r > 0.0031308 + ? ((1.055 * (r ** (1.0 / 2.4))) - 0.055) + : r * 12.92; + + g = g > 0.0031308 + ? ((1.055 * (g ** (1.0 / 2.4))) - 0.055) + : g * 12.92; + + b = b > 0.0031308 + ? ((1.055 * (b ** (1.0 / 2.4))) - 0.055) + : b * 12.92; + + r = Math.min(Math.max(0, r), 1); + g = Math.min(Math.max(0, g), 1); + b = Math.min(Math.max(0, b), 1); + + return [r * 255, g * 255, b * 255]; + }; + + convert.xyz.lab = function (xyz) { + let x = xyz[0]; + let y = xyz[1]; + let z = xyz[2]; + + x /= 95.047; + y /= 100; + z /= 108.883; + + x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116); + y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116); + z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116); + + const l = (116 * y) - 16; + const a = 500 * (x - y); + const b = 200 * (y - z); + + return [l, a, b]; + }; + + convert.lab.xyz = function (lab) { + const l = lab[0]; + const a = lab[1]; + const b = lab[2]; + let x; + let y; + let z; + + y = (l + 16) / 116; + x = a / 500 + y; + z = y - b / 200; + + const y2 = y ** 3; + const x2 = x ** 3; + const z2 = z ** 3; + y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787; + x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787; + z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787; + + x *= 95.047; + y *= 100; + z *= 108.883; + + return [x, y, z]; + }; + + convert.lab.lch = function (lab) { + const l = lab[0]; + const a = lab[1]; + const b = lab[2]; + let h; + + const hr = Math.atan2(b, a); + h = hr * 360 / 2 / Math.PI; + + if (h < 0) { + h += 360; + } + + const c = Math.sqrt(a * a + b * b); + + return [l, c, h]; + }; + + convert.lch.lab = function (lch) { + const l = lch[0]; + const c = lch[1]; + const h = lch[2]; + + const hr = h / 360 * 2 * Math.PI; + const a = c * Math.cos(hr); + const b = c * Math.sin(hr); + + return [l, a, b]; + }; + + convert.rgb.ansi16 = function (args, saturation = null) { + const [r, g, b] = args; + let value = saturation === null ? convert.rgb.hsv(args)[2] : saturation; // Hsv -> ansi16 optimization + + value = Math.round(value / 50); + + if (value === 0) { + return 30; + } + + let ansi = 30 + + ((Math.round(b / 255) << 2) + | (Math.round(g / 255) << 1) + | Math.round(r / 255)); + + if (value === 2) { + ansi += 60; + } + + return ansi; + }; + + convert.hsv.ansi16 = function (args) { + // Optimization here; we already know the value and don't need to get + // it converted for us. + return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]); + }; + + convert.rgb.ansi256 = function (args) { + const r = args[0]; + const g = args[1]; + const b = args[2]; + + // We use the extended greyscale palette here, with the exception of + // black and white. normal palette only has 4 greyscale shades. + if (r === g && g === b) { + if (r < 8) { + return 16; + } + + if (r > 248) { + return 231; + } + + return Math.round(((r - 8) / 247) * 24) + 232; + } + + const ansi = 16 + + (36 * Math.round(r / 255 * 5)) + + (6 * Math.round(g / 255 * 5)) + + Math.round(b / 255 * 5); + + return ansi; + }; + + convert.ansi16.rgb = function (args) { + let color = args % 10; + + // Handle greyscale + if (color === 0 || color === 7) { + if (args > 50) { + color += 3.5; + } + + color = color / 10.5 * 255; + + return [color, color, color]; + } + + const mult = (~~(args > 50) + 1) * 0.5; + const r = ((color & 1) * mult) * 255; + const g = (((color >> 1) & 1) * mult) * 255; + const b = (((color >> 2) & 1) * mult) * 255; + + return [r, g, b]; + }; + + convert.ansi256.rgb = function (args) { + // Handle greyscale + if (args >= 232) { + const c = (args - 232) * 10 + 8; + return [c, c, c]; + } + + args -= 16; + + let rem; + const r = Math.floor(args / 36) / 5 * 255; + const g = Math.floor((rem = args % 36) / 6) / 5 * 255; + const b = (rem % 6) / 5 * 255; + + return [r, g, b]; + }; + + convert.rgb.hex = function (args) { + const integer = ((Math.round(args[0]) & 0xFF) << 16) + + ((Math.round(args[1]) & 0xFF) << 8) + + (Math.round(args[2]) & 0xFF); + + const string = integer.toString(16).toUpperCase(); + return '000000'.substring(string.length) + string; + }; + + convert.hex.rgb = function (args) { + const match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i); + if (!match) { + return [0, 0, 0]; + } + + let colorString = match[0]; + + if (match[0].length === 3) { + colorString = colorString.split('').map(char => { + return char + char; + }).join(''); + } + + const integer = parseInt(colorString, 16); + const r = (integer >> 16) & 0xFF; + const g = (integer >> 8) & 0xFF; + const b = integer & 0xFF; + + return [r, g, b]; + }; + + convert.rgb.hcg = function (rgb) { + const r = rgb[0] / 255; + const g = rgb[1] / 255; + const b = rgb[2] / 255; + const max = Math.max(Math.max(r, g), b); + const min = Math.min(Math.min(r, g), b); + const chroma = (max - min); + let grayscale; + let hue; + + if (chroma < 1) { + grayscale = min / (1 - chroma); + } else { + grayscale = 0; + } + + if (chroma <= 0) { + hue = 0; + } else + if (max === r) { + hue = ((g - b) / chroma) % 6; + } else + if (max === g) { + hue = 2 + (b - r) / chroma; + } else { + hue = 4 + (r - g) / chroma; + } + + hue /= 6; + hue %= 1; + + return [hue * 360, chroma * 100, grayscale * 100]; + }; + + convert.hsl.hcg = function (hsl) { + const s = hsl[1] / 100; + const l = hsl[2] / 100; + + const c = l < 0.5 ? (2.0 * s * l) : (2.0 * s * (1.0 - l)); + + let f = 0; + if (c < 1.0) { + f = (l - 0.5 * c) / (1.0 - c); + } + + return [hsl[0], c * 100, f * 100]; + }; + + convert.hsv.hcg = function (hsv) { + const s = hsv[1] / 100; + const v = hsv[2] / 100; + + const c = s * v; + let f = 0; + + if (c < 1.0) { + f = (v - c) / (1 - c); + } + + return [hsv[0], c * 100, f * 100]; + }; + + convert.hcg.rgb = function (hcg) { + const h = hcg[0] / 360; + const c = hcg[1] / 100; + const g = hcg[2] / 100; + + if (c === 0.0) { + return [g * 255, g * 255, g * 255]; + } + + const pure = [0, 0, 0]; + const hi = (h % 1) * 6; + const v = hi % 1; + const w = 1 - v; + let mg = 0; + + /* eslint-disable max-statements-per-line */ + switch (Math.floor(hi)) { + case 0: + pure[0] = 1; pure[1] = v; pure[2] = 0; break; + case 1: + pure[0] = w; pure[1] = 1; pure[2] = 0; break; + case 2: + pure[0] = 0; pure[1] = 1; pure[2] = v; break; + case 3: + pure[0] = 0; pure[1] = w; pure[2] = 1; break; + case 4: + pure[0] = v; pure[1] = 0; pure[2] = 1; break; + default: + pure[0] = 1; pure[1] = 0; pure[2] = w; + } + /* eslint-enable max-statements-per-line */ + + mg = (1.0 - c) * g; + + return [ + (c * pure[0] + mg) * 255, + (c * pure[1] + mg) * 255, + (c * pure[2] + mg) * 255 + ]; + }; + + convert.hcg.hsv = function (hcg) { + const c = hcg[1] / 100; + const g = hcg[2] / 100; + + const v = c + g * (1.0 - c); + let f = 0; + + if (v > 0.0) { + f = c / v; + } + + return [hcg[0], f * 100, v * 100]; + }; + + convert.hcg.hsl = function (hcg) { + const c = hcg[1] / 100; + const g = hcg[2] / 100; + + const l = g * (1.0 - c) + 0.5 * c; + let s = 0; + + if (l > 0.0 && l < 0.5) { + s = c / (2 * l); + } else + if (l >= 0.5 && l < 1.0) { + s = c / (2 * (1 - l)); + } + + return [hcg[0], s * 100, l * 100]; + }; + + convert.hcg.hwb = function (hcg) { + const c = hcg[1] / 100; + const g = hcg[2] / 100; + const v = c + g * (1.0 - c); + return [hcg[0], (v - c) * 100, (1 - v) * 100]; + }; + + convert.hwb.hcg = function (hwb) { + const w = hwb[1] / 100; + const b = hwb[2] / 100; + const v = 1 - b; + const c = v - w; + let g = 0; + + if (c < 1) { + g = (v - c) / (1 - c); + } + + return [hwb[0], c * 100, g * 100]; + }; + + convert.apple.rgb = function (apple) { + return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255]; + }; + + convert.rgb.apple = function (rgb) { + return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535]; + }; + + convert.gray.rgb = function (args) { + return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255]; + }; + + convert.gray.hsl = function (args) { + return [0, 0, args[0]]; + }; + + convert.gray.hsv = convert.gray.hsl; + + convert.gray.hwb = function (gray) { + return [0, 100, gray[0]]; + }; + + convert.gray.cmyk = function (gray) { + return [0, 0, 0, gray[0]]; + }; + + convert.gray.lab = function (gray) { + return [gray[0], 0, 0]; + }; + + convert.gray.hex = function (gray) { + const val = Math.round(gray[0] / 100 * 255) & 0xFF; + const integer = (val << 16) + (val << 8) + val; + + const string = integer.toString(16).toUpperCase(); + return '000000'.substring(string.length) + string; + }; + + convert.rgb.gray = function (rgb) { + const val = (rgb[0] + rgb[1] + rgb[2]) / 3; + return [val / 255 * 100]; + }; + return conversions; +} + +var route; +var hasRequiredRoute; + +function requireRoute () { + if (hasRequiredRoute) return route; + hasRequiredRoute = 1; + const conversions = requireConversions(); + + /* + This function routes a model to all other models. + + all functions that are routed have a property `.conversion` attached + to the returned synthetic function. This property is an array + of strings, each with the steps in between the 'from' and 'to' + color models (inclusive). + + conversions that are not possible simply are not included. + */ + + function buildGraph() { + const graph = {}; + // https://jsperf.com/object-keys-vs-for-in-with-closure/3 + const models = Object.keys(conversions); + + for (let len = models.length, i = 0; i < len; i++) { + graph[models[i]] = { + // http://jsperf.com/1-vs-infinity + // micro-opt, but this is simple. + distance: -1, + parent: null + }; + } + + return graph; + } + + // https://en.wikipedia.org/wiki/Breadth-first_search + function deriveBFS(fromModel) { + const graph = buildGraph(); + const queue = [fromModel]; // Unshift -> queue -> pop + + graph[fromModel].distance = 0; + + while (queue.length) { + const current = queue.pop(); + const adjacents = Object.keys(conversions[current]); + + for (let len = adjacents.length, i = 0; i < len; i++) { + const adjacent = adjacents[i]; + const node = graph[adjacent]; + + if (node.distance === -1) { + node.distance = graph[current].distance + 1; + node.parent = current; + queue.unshift(adjacent); + } + } + } + + return graph; + } + + function link(from, to) { + return function (args) { + return to(from(args)); + }; + } + + function wrapConversion(toModel, graph) { + const path = [graph[toModel].parent, toModel]; + let fn = conversions[graph[toModel].parent][toModel]; + + let cur = graph[toModel].parent; + while (graph[cur].parent) { + path.unshift(graph[cur].parent); + fn = link(conversions[graph[cur].parent][cur], fn); + cur = graph[cur].parent; + } + + fn.conversion = path; + return fn; + } + + route = function (fromModel) { + const graph = deriveBFS(fromModel); + const conversion = {}; + + const models = Object.keys(graph); + for (let len = models.length, i = 0; i < len; i++) { + const toModel = models[i]; + const node = graph[toModel]; + + if (node.parent === null) { + // No possible conversion, or this node is the source model. + continue; + } + + conversion[toModel] = wrapConversion(toModel, graph); + } + + return conversion; + }; + return route; +} + +var colorConvert; +var hasRequiredColorConvert; + +function requireColorConvert () { + if (hasRequiredColorConvert) return colorConvert; + hasRequiredColorConvert = 1; + const conversions = requireConversions(); + const route = requireRoute(); + + const convert = {}; + + const models = Object.keys(conversions); + + function wrapRaw(fn) { + const wrappedFn = function (...args) { + const arg0 = args[0]; + if (arg0 === undefined || arg0 === null) { + return arg0; + } + + if (arg0.length > 1) { + args = arg0; + } + + return fn(args); + }; + + // Preserve .conversion property if there is one + if ('conversion' in fn) { + wrappedFn.conversion = fn.conversion; + } + + return wrappedFn; + } + + function wrapRounded(fn) { + const wrappedFn = function (...args) { + const arg0 = args[0]; + + if (arg0 === undefined || arg0 === null) { + return arg0; + } + + if (arg0.length > 1) { + args = arg0; + } + + const result = fn(args); + + // We're assuming the result is an array here. + // see notice in conversions.js; don't use box types + // in conversion functions. + if (typeof result === 'object') { + for (let len = result.length, i = 0; i < len; i++) { + result[i] = Math.round(result[i]); + } + } + + return result; + }; + + // Preserve .conversion property if there is one + if ('conversion' in fn) { + wrappedFn.conversion = fn.conversion; + } + + return wrappedFn; + } + + models.forEach(fromModel => { + convert[fromModel] = {}; + + Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels}); + Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels}); + + const routes = route(fromModel); + const routeModels = Object.keys(routes); + + routeModels.forEach(toModel => { + const fn = routes[toModel]; + + convert[fromModel][toModel] = wrapRounded(fn); + convert[fromModel][toModel].raw = wrapRaw(fn); + }); + }); + + colorConvert = convert; + return colorConvert; +} + +ansiStyles$1.exports; + +(function (module) { + + const wrapAnsi16 = (fn, offset) => (...args) => { + const code = fn(...args); + return `\u001B[${code + offset}m`; + }; + + const wrapAnsi256 = (fn, offset) => (...args) => { + const code = fn(...args); + return `\u001B[${38 + offset};5;${code}m`; + }; + + const wrapAnsi16m = (fn, offset) => (...args) => { + const rgb = fn(...args); + return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; + }; + + const ansi2ansi = n => n; + const rgb2rgb = (r, g, b) => [r, g, b]; + + const setLazyProperty = (object, property, get) => { + Object.defineProperty(object, property, { + get: () => { + const value = get(); + + Object.defineProperty(object, property, { + value, + enumerable: true, + configurable: true + }); + + return value; + }, + enumerable: true, + configurable: true + }); + }; + + /** @type {typeof import('color-convert')} */ + let colorConvert; + const makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => { + if (colorConvert === undefined) { + colorConvert = requireColorConvert(); + } + + const offset = isBackground ? 10 : 0; + const styles = {}; + + for (const [sourceSpace, suite] of Object.entries(colorConvert)) { + const name = sourceSpace === 'ansi16' ? 'ansi' : sourceSpace; + if (sourceSpace === targetSpace) { + styles[name] = wrap(identity, offset); + } else if (typeof suite === 'object') { + styles[name] = wrap(suite[targetSpace], offset); + } + } + + return styles; + }; + + function assembleStyles() { + const codes = new Map(); + const styles = { + modifier: { + reset: [0, 0], + // 21 isn't widely supported and 22 does the same thing + bold: [1, 22], + dim: [2, 22], + italic: [3, 23], + underline: [4, 24], + inverse: [7, 27], + hidden: [8, 28], + strikethrough: [9, 29] + }, + color: { + black: [30, 39], + red: [31, 39], + green: [32, 39], + yellow: [33, 39], + blue: [34, 39], + magenta: [35, 39], + cyan: [36, 39], + white: [37, 39], + + // Bright color + blackBright: [90, 39], + redBright: [91, 39], + greenBright: [92, 39], + yellowBright: [93, 39], + blueBright: [94, 39], + magentaBright: [95, 39], + cyanBright: [96, 39], + whiteBright: [97, 39] + }, + bgColor: { + bgBlack: [40, 49], + bgRed: [41, 49], + bgGreen: [42, 49], + bgYellow: [43, 49], + bgBlue: [44, 49], + bgMagenta: [45, 49], + bgCyan: [46, 49], + bgWhite: [47, 49], + + // Bright color + bgBlackBright: [100, 49], + bgRedBright: [101, 49], + bgGreenBright: [102, 49], + bgYellowBright: [103, 49], + bgBlueBright: [104, 49], + bgMagentaBright: [105, 49], + bgCyanBright: [106, 49], + bgWhiteBright: [107, 49] + } + }; + + // Alias bright black as gray (and grey) + styles.color.gray = styles.color.blackBright; + styles.bgColor.bgGray = styles.bgColor.bgBlackBright; + styles.color.grey = styles.color.blackBright; + styles.bgColor.bgGrey = styles.bgColor.bgBlackBright; + + for (const [groupName, group] of Object.entries(styles)) { + for (const [styleName, style] of Object.entries(group)) { + styles[styleName] = { + open: `\u001B[${style[0]}m`, + close: `\u001B[${style[1]}m` + }; + + group[styleName] = styles[styleName]; + + codes.set(style[0], style[1]); + } + + Object.defineProperty(styles, groupName, { + value: group, + enumerable: false + }); + } + + Object.defineProperty(styles, 'codes', { + value: codes, + enumerable: false + }); + + styles.color.close = '\u001B[39m'; + styles.bgColor.close = '\u001B[49m'; + + setLazyProperty(styles.color, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, false)); + setLazyProperty(styles.color, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, false)); + setLazyProperty(styles.color, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, false)); + setLazyProperty(styles.bgColor, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, true)); + setLazyProperty(styles.bgColor, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, true)); + setLazyProperty(styles.bgColor, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, true)); + + return styles; + } + + // Make the export immutable + Object.defineProperty(module, 'exports', { + enumerable: true, + get: assembleStyles + }); +} (ansiStyles$1)); + +var ansiStylesExports = ansiStyles$1.exports; + +const stringReplaceAll$1 = (string, substring, replacer) => { + let index = string.indexOf(substring); + if (index === -1) { + return string; + } + + const substringLength = substring.length; + let endIndex = 0; + let returnValue = ''; + do { + returnValue += string.substr(endIndex, index - endIndex) + substring + replacer; + endIndex = index + substringLength; + index = string.indexOf(substring, endIndex); + } while (index !== -1); + + returnValue += string.substr(endIndex); + return returnValue; +}; + +const stringEncaseCRLFWithFirstIndex$1 = (string, prefix, postfix, index) => { + let endIndex = 0; + let returnValue = ''; + do { + const gotCR = string[index - 1] === '\r'; + returnValue += string.substr(endIndex, (gotCR ? index - 1 : index) - endIndex) + prefix + (gotCR ? '\r\n' : '\n') + postfix; + endIndex = index + 1; + index = string.indexOf('\n', endIndex); + } while (index !== -1); + + returnValue += string.substr(endIndex); + return returnValue; +}; + +var util = { + stringReplaceAll: stringReplaceAll$1, + stringEncaseCRLFWithFirstIndex: stringEncaseCRLFWithFirstIndex$1 +}; + +var templates; +var hasRequiredTemplates; + +function requireTemplates () { + if (hasRequiredTemplates) return templates; + hasRequiredTemplates = 1; + const TEMPLATE_REGEX = /(?:\\(u(?:[a-f\d]{4}|\{[a-f\d]{1,6}\})|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi; + const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g; + const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/; + const ESCAPE_REGEX = /\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi; + + const ESCAPES = new Map([ + ['n', '\n'], + ['r', '\r'], + ['t', '\t'], + ['b', '\b'], + ['f', '\f'], + ['v', '\v'], + ['0', '\0'], + ['\\', '\\'], + ['e', '\u001B'], + ['a', '\u0007'] + ]); + + function unescape(c) { + const u = c[0] === 'u'; + const bracket = c[1] === '{'; + + if ((u && !bracket && c.length === 5) || (c[0] === 'x' && c.length === 3)) { + return String.fromCharCode(parseInt(c.slice(1), 16)); + } + + if (u && bracket) { + return String.fromCodePoint(parseInt(c.slice(2, -1), 16)); + } + + return ESCAPES.get(c) || c; + } + + function parseArguments(name, arguments_) { + const results = []; + const chunks = arguments_.trim().split(/\s*,\s*/g); + let matches; + + for (const chunk of chunks) { + const number = Number(chunk); + if (!Number.isNaN(number)) { + results.push(number); + } else if ((matches = chunk.match(STRING_REGEX))) { + results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, character) => escape ? unescape(escape) : character)); + } else { + throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`); + } + } + + return results; + } + + function parseStyle(style) { + STYLE_REGEX.lastIndex = 0; + + const results = []; + let matches; + + while ((matches = STYLE_REGEX.exec(style)) !== null) { + const name = matches[1]; + + if (matches[2]) { + const args = parseArguments(name, matches[2]); + results.push([name].concat(args)); + } else { + results.push([name]); + } + } + + return results; + } + + function buildStyle(chalk, styles) { + const enabled = {}; + + for (const layer of styles) { + for (const style of layer.styles) { + enabled[style[0]] = layer.inverse ? null : style.slice(1); + } + } + + let current = chalk; + for (const [styleName, styles] of Object.entries(enabled)) { + if (!Array.isArray(styles)) { + continue; + } + + if (!(styleName in current)) { + throw new Error(`Unknown Chalk style: ${styleName}`); + } + + current = styles.length > 0 ? current[styleName](...styles) : current[styleName]; + } + + return current; + } + + templates = (chalk, temporary) => { + const styles = []; + const chunks = []; + let chunk = []; + + // eslint-disable-next-line max-params + temporary.replace(TEMPLATE_REGEX, (m, escapeCharacter, inverse, style, close, character) => { + if (escapeCharacter) { + chunk.push(unescape(escapeCharacter)); + } else if (style) { + const string = chunk.join(''); + chunk = []; + chunks.push(styles.length === 0 ? string : buildStyle(chalk, styles)(string)); + styles.push({inverse, styles: parseStyle(style)}); + } else if (close) { + if (styles.length === 0) { + throw new Error('Found extraneous } in Chalk template literal'); + } + + chunks.push(buildStyle(chalk, styles)(chunk.join(''))); + chunk = []; + styles.pop(); + } else { + chunk.push(character); + } + }); + + chunks.push(chunk.join('')); + + if (styles.length > 0) { + const errMessage = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`; + throw new Error(errMessage); + } + + return chunks.join(''); + }; + return templates; +} + +const ansiStyles = ansiStylesExports; +const {stdout: stdoutColor, stderr: stderrColor} = requireSupportsColor$2(); +const { + stringReplaceAll, + stringEncaseCRLFWithFirstIndex +} = util; + +const {isArray: isArray$1} = Array; + +// `supportsColor.level` → `ansiStyles.color[name]` mapping +const levelMapping = [ + 'ansi', + 'ansi', + 'ansi256', + 'ansi16m' +]; + +const styles = Object.create(null); + +const applyOptions = (object, options = {}) => { + if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) { + throw new Error('The `level` option should be an integer from 0 to 3'); + } + + // Detect level if not set manually + const colorLevel = stdoutColor ? stdoutColor.level : 0; + object.level = options.level === undefined ? colorLevel : options.level; +}; + +class ChalkClass { + constructor(options) { + // eslint-disable-next-line no-constructor-return + return chalkFactory(options); + } +} + +const chalkFactory = options => { + const chalk = {}; + applyOptions(chalk, options); + + chalk.template = (...arguments_) => chalkTag(chalk.template, ...arguments_); + + Object.setPrototypeOf(chalk, Chalk.prototype); + Object.setPrototypeOf(chalk.template, chalk); + + chalk.template.constructor = () => { + throw new Error('`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.'); + }; + + chalk.template.Instance = ChalkClass; + + return chalk.template; +}; + +function Chalk(options) { + return chalkFactory(options); +} + +for (const [styleName, style] of Object.entries(ansiStyles)) { + styles[styleName] = { + get() { + const builder = createBuilder(this, createStyler(style.open, style.close, this._styler), this._isEmpty); + Object.defineProperty(this, styleName, {value: builder}); + return builder; + } + }; +} + +styles.visible = { + get() { + const builder = createBuilder(this, this._styler, true); + Object.defineProperty(this, 'visible', {value: builder}); + return builder; + } +}; + +const usedModels = ['rgb', 'hex', 'keyword', 'hsl', 'hsv', 'hwb', 'ansi', 'ansi256']; + +for (const model of usedModels) { + styles[model] = { + get() { + const {level} = this; + return function (...arguments_) { + const styler = createStyler(ansiStyles.color[levelMapping[level]][model](...arguments_), ansiStyles.color.close, this._styler); + return createBuilder(this, styler, this._isEmpty); + }; + } + }; +} + +for (const model of usedModels) { + const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); + styles[bgModel] = { + get() { + const {level} = this; + return function (...arguments_) { + const styler = createStyler(ansiStyles.bgColor[levelMapping[level]][model](...arguments_), ansiStyles.bgColor.close, this._styler); + return createBuilder(this, styler, this._isEmpty); + }; + } + }; +} + +const proto = Object.defineProperties(() => {}, { + ...styles, + level: { + enumerable: true, + get() { + return this._generator.level; + }, + set(level) { + this._generator.level = level; + } + } +}); + +const createStyler = (open, close, parent) => { + let openAll; + let closeAll; + if (parent === undefined) { + openAll = open; + closeAll = close; + } else { + openAll = parent.openAll + open; + closeAll = close + parent.closeAll; + } + + return { + open, + close, + openAll, + closeAll, + parent + }; +}; + +const createBuilder = (self, _styler, _isEmpty) => { + const builder = (...arguments_) => { + if (isArray$1(arguments_[0]) && isArray$1(arguments_[0].raw)) { + // Called as a template literal, for example: chalk.red`2 + 3 = {bold ${2+3}}` + return applyStyle(builder, chalkTag(builder, ...arguments_)); + } + + // Single argument is hot path, implicit coercion is faster than anything + // eslint-disable-next-line no-implicit-coercion + return applyStyle(builder, (arguments_.length === 1) ? ('' + arguments_[0]) : arguments_.join(' ')); + }; + + // We alter the prototype because we must return a function, but there is + // no way to create a function with a different prototype + Object.setPrototypeOf(builder, proto); + + builder._generator = self; + builder._styler = _styler; + builder._isEmpty = _isEmpty; + + return builder; +}; + +const applyStyle = (self, string) => { + if (self.level <= 0 || !string) { + return self._isEmpty ? '' : string; + } + + let styler = self._styler; + + if (styler === undefined) { + return string; + } + + const {openAll, closeAll} = styler; + if (string.indexOf('\u001B') !== -1) { + while (styler !== undefined) { + // Replace any instances already present with a re-opening code + // otherwise only the part of the string until said closing code + // will be colored, and the rest will simply be 'plain'. + string = stringReplaceAll(string, styler.close, styler.open); + + styler = styler.parent; + } + } + + // We can move both next actions out of loop, because remaining actions in loop won't have + // any/visible effect on parts we add here. Close the styling before a linebreak and reopen + // after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92 + const lfIndex = string.indexOf('\n'); + if (lfIndex !== -1) { + string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex); + } + + return openAll + string + closeAll; +}; + +let template$1; +const chalkTag = (chalk, ...strings) => { + const [firstString] = strings; + + if (!isArray$1(firstString) || !isArray$1(firstString.raw)) { + // If chalk() was called by itself or with a string, + // return the string itself as a string. + return strings.join(' '); + } + + const arguments_ = strings.slice(1); + const parts = [firstString.raw[0]]; + + for (let i = 1; i < firstString.length; i++) { + parts.push( + String(arguments_[i - 1]).replace(/[{}\\]/g, '\\$&'), + String(firstString.raw[i]) + ); + } + + if (template$1 === undefined) { + template$1 = requireTemplates(); + } + + return template$1(chalk, parts.join('')); +}; + +Object.defineProperties(Chalk.prototype, styles); + +const chalk = Chalk(); // eslint-disable-line new-cap +chalk.supportsColor = stdoutColor; +chalk.stderr = Chalk({level: stderrColor ? stderrColor.level : 0}); // eslint-disable-line new-cap +chalk.stderr.supportsColor = stderrColor; + +var source = chalk; + +var chalk$1 = /*@__PURE__*/getDefaultExportFromCjs(source); + +// eslint-disable-next-line unicorn/better-regex +const TEMPLATE_REGEX = /(?:\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.))|(?:{(~)?(#?[\w:]+(?:\([^)]*\))?(?:\.#?[\w:]+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(})|((?:.|[\r\n\f])+?)/gi; +const STYLE_REGEX = /(?:^|\.)(?:(?:(\w+)(?:\(([^)]*)\))?)|(?:#(?=[:a-fA-F\d]{2,})([a-fA-F\d]{6})?(?::([a-fA-F\d]{6}))?))/g; +const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/; +const ESCAPE_REGEX = /\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi; + +const ESCAPES = new Map([ + ['n', '\n'], + ['r', '\r'], + ['t', '\t'], + ['b', '\b'], + ['f', '\f'], + ['v', '\v'], + ['0', '\0'], + ['\\', '\\'], + ['e', '\u001B'], + ['a', '\u0007'], +]); + +function unescape$1(c) { + const u = c[0] === 'u'; + const bracket = c[1] === '{'; + + if ((u && !bracket && c.length === 5) || (c[0] === 'x' && c.length === 3)) { + return String.fromCharCode(Number.parseInt(c.slice(1), 16)); + } + + if (u && bracket) { + return String.fromCodePoint(Number.parseInt(c.slice(2, -1), 16)); + } + + return ESCAPES.get(c) || c; +} + +function parseArguments(name, arguments_) { + const results = []; + const chunks = arguments_.trim().split(/\s*,\s*/g); + let matches; + + for (const chunk of chunks) { + const number = Number(chunk); + if (!Number.isNaN(number)) { + results.push(number); + } else if ((matches = chunk.match(STRING_REGEX))) { + results.push(matches[2].replace(ESCAPE_REGEX, (_, escape, character) => escape ? unescape$1(escape) : character)); + } else { + throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`); + } + } + + return results; +} + +function parseHex(hex) { + const n = Number.parseInt(hex, 16); + return [ + // eslint-disable-next-line no-bitwise + (n >> 16) & 0xFF, + // eslint-disable-next-line no-bitwise + (n >> 8) & 0xFF, + // eslint-disable-next-line no-bitwise + n & 0xFF, + ]; +} + +function parseStyle(style) { + STYLE_REGEX.lastIndex = 0; + + const results = []; + let matches; + + while ((matches = STYLE_REGEX.exec(style)) !== null) { + const name = matches[1]; + + if (matches[2]) { + results.push([name, ...parseArguments(name, matches[2])]); + } else if (matches[3] || matches[4]) { + if (matches[3]) { + results.push(['rgb', ...parseHex(matches[3])]); + } + + if (matches[4]) { + results.push(['bgRgb', ...parseHex(matches[4])]); + } + } else { + results.push([name]); + } + } + + return results; +} + +function buildStyle(styles) { + const enabled = {}; + + for (const layer of styles) { + for (const style of layer.styles) { + enabled[style[0]] = layer.inverse ? null : style.slice(1); + } + } + + let current = chalk$1; + for (const [styleName, styles] of Object.entries(enabled)) { + if (!Array.isArray(styles)) { + continue; + } + + if (!(styleName in current)) { + throw new Error(`Unknown Chalk style: ${styleName}`); + } + + current = styles.length > 0 ? current[styleName](...styles) : current[styleName]; + } + + return current; +} + +function template(string) { + const styles = []; + const chunks = []; + let chunk = []; + + // eslint-disable-next-line max-params + string.replace(TEMPLATE_REGEX, (_, escapeCharacter, inverse, style, close, character) => { + if (escapeCharacter) { + chunk.push(unescape$1(escapeCharacter)); + } else if (style) { + const string = chunk.join(''); + chunk = []; + chunks.push(styles.length === 0 ? string : buildStyle(styles)(string)); + styles.push({inverse, styles: parseStyle(style)}); + } else if (close) { + if (styles.length === 0) { + throw new Error('Found extraneous } in Chalk template literal'); + } + + chunks.push(buildStyle(styles)(chunk.join(''))); + chunk = []; + styles.pop(); + } else { + chunk.push(character); + } + }); + + chunks.push(chunk.join('')); + + if (styles.length > 0) { + throw new Error(`Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`); + } + + return chunks.join(''); +} + +function chalkTemplate(firstString, ...arguments_) { + if (!Array.isArray(firstString) || !Array.isArray(firstString.raw)) { + // If chalkTemplate() was called by itself or with a string + throw new TypeError('A tagged template literal must be provided'); + } + + const parts = [firstString.raw[0]]; + + for (let index = 1; index < firstString.raw.length; index++) { + parts.push( + String(arguments_[index - 1]).replace(/[{}\\]/g, '\\$&'), + String(firstString.raw[index]), + ); + } + + return template(parts.join('')); +} + +function chalkFormat (str) { + if (str) { + str = str.replace(/`/g, '\\`'); + return chalkTemplate(Object.assign([], { raw: [str] })) + } else { + return '' + } +} + +class Section { + constructor () { + this.lines = []; + } + + add (lines) { + if (lines) { + arrayify$1(lines).forEach(line => this.lines.push(line)); + } else { + this.lines.push(''); + } + } + + toString () { + return this.lines.join(require$$0$7.EOL) + } + + header (text) { + if (text) { + this.add(chalkFormat(`{bold ${text}}`)); + this.add(); + } + } +} + +/** + * Takes any input and guarantees an array back. + * + * - Converts array-like objects (e.g. `arguments`, `Set`) to a real array. + * - Converts `undefined` to an empty array. + * - Converts any another other, singular value (including `null`, objects and iterables other than `Set`) into an array containing that value. + * - Ignores input which is already an array. + * + * @module array-back + * @example + * > const arrayify = require('array-back') + * + * > arrayify(undefined) + * [] + * + * > arrayify(null) + * [ null ] + * + * > arrayify(0) + * [ 0 ] + * + * > arrayify([ 1, 2 ]) + * [ 1, 2 ] + * + * > arrayify(new Set([ 1, 2 ])) + * [ 1, 2 ] + * + * > function f(){ return arrayify(arguments); } + * > f(1,2,3) + * [ 1, 2, 3 ] + */ + +function isObject$3 (input) { + return typeof input === 'object' && input !== null +} + +function isArrayLike$3 (input) { + return isObject$3(input) && typeof input.length === 'number' +} + +/** + * @param {*} - The input value to convert to an array + * @returns {Array} + * @alias module:array-back + */ +function arrayify (input) { + if (Array.isArray(input)) { + return input + } else if (input === undefined) { + return [] + } else if (isArrayLike$3(input) || input instanceof Set) { + return Array.from(input) + } else { + return [input] + } +} + +const _value = new WeakMap(); +const _column = new WeakMap(); + +class Cell { + constructor (value, column) { + this.value = value; + _column.set(this, column); + } + + set value (val) { + _value.set(this, val); + } + + /** + * Must return a string or object with a `.toString()` method. + * @returns {string} + */ + get value () { + let cellValue = _value.get(this); + const column = _column.get(this); + if (column.get) { + cellValue = column.get(cellValue); + } + if (cellValue === undefined) { + cellValue = ''; + } else { + cellValue = String(cellValue); + } + return cellValue + } +} + +/** + * @module rows + */ + +/** +≈ Each row is a map of column/cell pairs. +*/ +class Rows { + constructor (rows, columns) { + this.list = []; + this.load(rows, columns); + } + + load (rows, columns) { + for (const row of arrayify(rows)) { + const map = new Map(columns.list.map(column => [column, new Cell(row[column.name], column)])); + this.list.push(map); + } + } +} + +/** + * Isomorphic, functional type-checking for Javascript. + * @module typical + * @typicalname t + * @example + * import * as t from 'typical' + * const allDefined = array.every(t.isDefined) + */ + +/** + * Returns true if input is a number (including infinity). It is a more reasonable alternative to `typeof n` which returns `number` for `NaN`. + * + * @param {*} n - The input to test + * @returns {boolean} `true` if input is a number + * @static + * @example + * > t.isNumber(0) + * true + * > t.isNumber(1) + * true + * > t.isNumber(1.1) + * true + * > t.isNumber(0xff) + * true + * > t.isNumber(0644) + * true + * > t.isNumber(6.2e5) + * true + * > t.isNumber(NaN) + * false + * > t.isNumber(Infinity) + * true + */ +function isNumber$1 (n) { + return !isNaN(parseFloat(n)) +} + +/** + * Returns true if input is a finite number. Identical to `isNumber` beside excluding infinity. + * + * @param {*} n - The input to test + * @returns {boolean} + * @static + * @example + * > t.isFiniteNumber(0) + * true + * > t.isFiniteNumber(1) + * true + * > t.isFiniteNumber(1.1) + * true + * > t.isFiniteNumber(0xff) + * true + * > t.isFiniteNumber(0644) + * true + * > t.isFiniteNumber(6.2e5) + * true + * > t.isFiniteNumber(NaN) + * false + * > t.isFiniteNumber(Infinity) + * false + */ +function isFiniteNumber$1 (n) { + return !isNaN(parseFloat(n)) && isFinite(n) +} + +/** + * A plain object is a simple object literal, it is not an instance of a class. Returns true if the input `typeof` is `object` and directly decends from `Object`. + * + * @param {*} input - The input to test + * @returns {boolean} + * @static + * @example + * > t.isPlainObject({ something: 'one' }) + * true + * > t.isPlainObject(new Date()) + * false + * > t.isPlainObject([ 0, 1 ]) + * false + * > t.isPlainObject(/test/) + * false + * > t.isPlainObject(1) + * false + * > t.isPlainObject('one') + * false + * > t.isPlainObject(null) + * false + * > t.isPlainObject((function * () {})()) + * false + * > t.isPlainObject(function * () {}) + * false + */ +function isPlainObject$2 (input) { + return input !== null && typeof input === 'object' && input.constructor === Object +} + +/** + * An array-like value has all the properties of an array yet is not an array instance. An example is the `arguments` object. Returns `true`` if the input value is an object, not `null`` and has a `length` property set with a numeric value. + * + * @param {*} input - The input to test + * @returns {boolean} + * @static + * @example + * function sum(x, y){ + * console.log(t.isArrayLike(arguments)) + * // prints `true` + * } + */ +function isArrayLike$2 (input) { + return isObject$2(input) && typeof input.length === 'number' +} + +/** + * Returns true if the typeof input is `'object'` but not null. + * @param {*} input - The input to test + * @returns {boolean} + * @static + */ +function isObject$2 (input) { + return typeof input === 'object' && input !== null +} + +/** + * Returns true if the input value is defined. + * @param {*} input - The input to test + * @returns {boolean} + * @static + */ +function isDefined$2 (input) { + return typeof input !== 'undefined' +} + +/** + * Returns true if the input value is undefined. + * @param {*} input - The input to test + * @returns {boolean} + * @static + */ +function isUndefined$1 (input) { + return !isDefined$2(input) +} + +/** + * Returns true if the input value is null. + * @param {*} input - The input to test + * @returns {boolean} + * @static + */ +function isNull$1 (input) { + return input === null +} + +/** + * Returns true if the input value is not one of `undefined`, `null`, or `NaN`. + * @param {*} input - The input to test + * @returns {boolean} + * @static + */ +function isDefinedValue$1 (input) { + return isDefined$2(input) && !isNull$1(input) && !Number.isNaN(input) +} + +/** + * Returns true if the input value is an ES2015 `class`. + * @param {*} input - The input to test + * @returns {boolean} + * @static + */ +function isClass$1 (input) { + if (typeof input === 'function') { + return /^class /.test(Function.prototype.toString.call(input)) + } else { + return false + } +} + +/** + * Returns true if the input is a string, number, symbol, boolean, null or undefined value. + * @param {*} input - The input to test + * @returns {boolean} + * @static + */ +function isPrimitive$1 (input) { + if (input === null) return true + switch (typeof input) { + case 'string': + case 'number': + case 'symbol': + case 'undefined': + case 'boolean': + return true + default: + return false + } +} + +/** + * Returns true if the input is a Promise. + * @param {*} input - The input to test + * @returns {boolean} + * @static + */ +function isPromise$1 (input) { + if (input) { + const isPromise = isDefined$2(Promise) && input instanceof Promise; + const isThenable = input.then && typeof input.then === 'function'; + return !!(isPromise || isThenable) + } else { + return false + } +} + +/** + * Returns true if the input is an iterable (`Map`, `Set`, `Array`, Generator etc.). + * @param {*} input - The input to test + * @returns {boolean} + * @static + * @example + * > t.isIterable('string') + * true + * > t.isIterable(new Map()) + * true + * > t.isIterable([]) + * true + * > t.isIterable((function * () {})()) + * true + * > t.isIterable(Promise.resolve()) + * false + * > t.isIterable(Promise) + * false + * > t.isIterable(true) + * false + * > t.isIterable({}) + * false + * > t.isIterable(0) + * false + * > t.isIterable(1.1) + * false + * > t.isIterable(NaN) + * false + * > t.isIterable(Infinity) + * false + * > t.isIterable(function () {}) + * false + * > t.isIterable(Date) + * false + * > t.isIterable() + * false + * > t.isIterable({ then: function () {} }) + * false + */ +function isIterable$1 (input) { + if (input === null || !isDefined$2(input)) { + return false + } else { + return ( + typeof input[Symbol.iterator] === 'function' || + typeof input[Symbol.asyncIterator] === 'function' + ) + } +} + +/** + * Returns true if the input value is a string. The equivalent of `typeof input === 'string'` for use in funcitonal contexts. + * @param {*} input - The input to test + * @returns {boolean} + * @static + */ +function isString$1 (input) { + return typeof input === 'string' +} + +/** + * Returns true if the input value is a function. The equivalent of `typeof input === 'function'` for use in funcitonal contexts. + * @param {*} input - The input to test + * @returns {boolean} + * @static + */ +function isFunction$2 (input) { + return typeof input === 'function' +} + +var t$1 = { + isNumber: isNumber$1, + isFiniteNumber: isFiniteNumber$1, + isPlainObject: isPlainObject$2, + isArrayLike: isArrayLike$2, + isObject: isObject$2, + isDefined: isDefined$2, + isUndefined: isUndefined$1, + isNull: isNull$1, + isDefinedValue: isDefinedValue$1, + isClass: isClass$1, + isPrimitive: isPrimitive$1, + isPromise: isPromise$1, + isIterable: isIterable$1, + isString: isString$1, + isFunction: isFunction$2 +}; + +/** + * @module padding + */ + +class Padding { + constructor (padding) { + this.left = padding.left; + this.right = padding.right; + } + + length () { + return this.left.length + this.right.length + } +} + +/** + * @module column + */ + +const _padding = new WeakMap(); + +// setting any column property which is a factor of the width should trigger autoSize() + +/** + * Represents the configuration and generatedWidth for a table column. + */ +class Column { + constructor (column = {}) { + this.name = column.name; + this.width = column.width; + this.maxWidth = column.maxWidth; + this.minWidth = column.minWidth; + this.noWrap = column.noWrap; + this.break = column.break; + this.contentWrappable = column.contentWrappable; + this.contentWidth = column.contentWidth; + this.minContentWidth = column.minContentWidth; + // this.get = column.get + this.padding = column.padding || { left: ' ', right: ' ' }; + this.generatedWidth = null; + } + + set padding (padding) { + _padding.set(this, new Padding(padding)); + } + + get padding () { + return _padding.get(this) + } + + /** + * The width of the content (excluding padding) after being wrapped + */ + get wrappedContentWidth () { + return Math.max(this.generatedWidth - this.padding.length(), 0) + } + + isResizable () { + return !this.isFixed() + } + + isFixed () { + return t$1.isDefined(this.width) || this.noWrap || !this.contentWrappable + } + + generateWidth () { + this.generatedWidth = this.width || (this.contentWidth + this.padding.length()); + } + + generateMinWidth () { + this.minWidth = this.minContentWidth + this.padding.length(); + } +} + +const _maxWidth = new WeakMap(); + +/** + * @module columns + */ + +class Columns { + constructor (columns) { + this.list = []; + for (const column of arrayify(columns)) { + this.add(column); + } + } + + /** + * sum of all generatedWidth fields + * @return {number} + */ + totalWidth () { + return this.list.length + ? this.list.map(col => col.generatedWidth).reduce((a, b) => a + b) + : 0 + } + + totalFixedWidth () { + return this.getFixed() + .map(col => col.generatedWidth) + .reduce((a, b) => a + b, 0) + } + + get (columnName) { + return this.list.find(column => column.name === columnName) + } + + getResizable () { + return this.list.filter(column => column.isResizable()) + } + + getFixed () { + return this.list.filter(column => column.isFixed()) + } + + add (column) { + const col = column instanceof Column ? column : new Column(column); + this.list.push(col); + return col + } + + get maxWidth () { + _maxWidth.get(this); + } + + set maxWidth (val) { + _maxWidth.set(this, val); + } + + /** + * sets `generatedWidth` for each column + * @chainable + */ + autoSize () { + const maxWidth = _maxWidth.get(this); + + /* size */ + for (const column of this.list) { + column.generateWidth(); + column.generateMinWidth(); + } + + /* adjust if user set a min or maxWidth */ + for (const column of this.list) { + if (t$1.isDefined(column.maxWidth) && column.generatedWidth > column.maxWidth) { + column.generatedWidth = column.maxWidth; + } + + if (t$1.isDefined(column.minWidth) && column.generatedWidth < column.minWidth) { + column.generatedWidth = column.minWidth; + } + } + + const width = { + total: this.totalWidth(), + view: maxWidth, + diff: this.totalWidth() - maxWidth, + totalFixed: this.totalFixedWidth(), + totalResizable: Math.max(maxWidth - this.totalFixedWidth(), 0) + }; + + /* adjust if short of space */ + if (width.diff > 0) { + /* share the available space between resizeable columns */ + const resizableColumns = this.getResizable(); + for (const column of resizableColumns) { + column.generatedWidth = Math.floor(width.totalResizable / resizableColumns.length); + } + + /* at this point, the generatedWidth should never end up bigger than the contentWidth */ + const grownColumns = this.list.filter(column => column.generatedWidth > column.contentWidth); + const shrunkenColumns = this.list.filter(column => column.generatedWidth < column.contentWidth); + let salvagedSpace = 0; + for (const column of grownColumns) { + const currentGeneratedWidth = column.generatedWidth; + column.generateWidth(); + salvagedSpace += currentGeneratedWidth - column.generatedWidth; + } + for (const column of shrunkenColumns) { + column.generatedWidth += Math.floor(salvagedSpace / shrunkenColumns.length); + } + + /* if, after autosizing, we still don't fit within maxWidth then give up */ + } + + return this + } + + /** + * Factory method returning all distinct columns from input + * @param {object[]} - input recordset + * @return {module:columns} + */ + static getColumns (rows) { + const columns = new Columns(); + for (const row of arrayify(rows)) { + for (const columnName in row) { + let column = columns.get(columnName); + if (!column) { + /* The default column if not specified */ + column = columns.add({ name: columnName, contentWidth: 0, minContentWidth: 0 }); + } + } + } + return columns + } +} + +/** + * @module wordwrapjs + */ + +/** + * Wordwrap options. + * @typedef {Object} WordwrapOptions + * @property {number} [width=30] - The max column width in characters. + * @property {boolean} [break=false] - If true, words exceeding the specified `width` will be forcefully broken + * @property {boolean} [noTrim=false] - By default, each line output is trimmed. If `noTrim` is set, no line-trimming occurs - all whitespace from the input text is left in. + * @property {string} [eol='\n'] - The end of line character to use. Defaults to `\n`. + */ + +const re = { + chunk: /[^\s-]+?-\b|\S+|\s+|\r\n?|\n/g, + ansiEscapeSequence: /\u001b.*?m/g +}; + +/** + * @alias module:wordwrapjs + * @typicalname wordwrap + */ +class Wordwrap { + /** + * @param {string} text - The input text to wrap. + * @param {module:wordwrapjs~WordwrapOptions} [options] + */ + constructor (text = '', options = {}) { + this._lines = String(text).split(/\r\n|\n/g); + this.options = { + eol: '\n', + width: 30, + ...options + }; + } + + lines () { + /* trim each line of the supplied text */ + return this._lines.map(trimLine, this) + + /* split each line into an array of chunks, else mark it empty */ + .map(line => line.match(re.chunk) || ['~~empty~~']) + + /* optionally, break each word on the line into pieces */ + .map(lineWords => this.options.break + ? lineWords.map(breakWord, this) + : lineWords + ) + .map(lineWords => lineWords.flat()) + + /* transforming the line of words to one or more new lines wrapped to size */ + .map(lineWords => { + return lineWords + .reduce((lines, word) => { + const currentLine = lines[lines.length - 1]; + if (replaceAnsi(word).length + replaceAnsi(currentLine).length > this.options.width) { + lines.push(word); + } else { + lines[lines.length - 1] += word; + } + return lines + }, ['']) + }) + .flat() + + /* trim the wrapped lines */ + .map(trimLine, this) + + /* filter out empty lines */ + .filter(line => line.trim()) + + /* restore the user's original empty lines */ + .map(line => line.replace('~~empty~~', '')) + } + + wrap () { + return this.lines().join(this.options.eol) + } + + toString () { + return this.wrap() + } + + /** + * @param {string} text - the input text to wrap + * @param {module:wordwrapjs~WordwrapOptions} [options] + */ + static wrap (text, options) { + const block = new this(text, options); + return block.wrap() + } + + /** + * Wraps the input text, returning an array of strings (lines). + * @param {string} text - input text + * @param {module:wordwrapjs~WordwrapOptions} [options] + */ + static lines (text, options) { + const block = new this(text, options); + return block.lines() + } + + /** + * Returns true if the input text would be wrapped if passed into `.wrap()`. + * @param {string} text - input text + * @return {boolean} + */ + static isWrappable (text = '') { + const matches = String(text).match(re.chunk); + return matches ? matches.length > 1 : false + } + + /** + * Splits the input text into an array of words and whitespace. + * @param {string} text - input text + * @returns {string[]} + */ + static getChunks (text) { + return text.match(re.chunk) || [] + } +} + +function trimLine (line) { + return this.options.noTrim ? line : line.trim() +} + +function replaceAnsi (string) { + return string.replace(re.ansiEscapeSequence, '') +} + +/** + * break a word into several pieces + * @param {string} word + * @private + */ +function breakWord (word) { + if (replaceAnsi(word).length > this.options.width) { + const letters = word.split(''); + let piece; + const pieces = []; + while ((piece = letters.splice(0, this.options.width)).length) { + pieces.push(piece.join('')); + } + return pieces + } else { + return word + } +} + +/** + * lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright jQuery Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ + +/** Used as references for various `Number` constants. */ +var MAX_SAFE_INTEGER = 9007199254740991; + +/** `Object#toString` result references. */ +var argsTag = '[object Arguments]', + funcTag = '[object Function]', + genTag = '[object GeneratorFunction]'; + +/** Used to detect unsigned integer values. */ +var reIsUint = /^(?:0|[1-9]\d*)$/; + +/** + * A faster alternative to `Function#apply`, this function invokes `func` + * with the `this` binding of `thisArg` and the arguments of `args`. + * + * @private + * @param {Function} func The function to invoke. + * @param {*} thisArg The `this` binding of `func`. + * @param {Array} args The arguments to invoke `func` with. + * @returns {*} Returns the result of `func`. + */ +function apply(func, thisArg, args) { + switch (args.length) { + case 0: return func.call(thisArg); + case 1: return func.call(thisArg, args[0]); + case 2: return func.call(thisArg, args[0], args[1]); + case 3: return func.call(thisArg, args[0], args[1], args[2]); + } + return func.apply(thisArg, args); +} + +/** + * The base implementation of `_.times` without support for iteratee shorthands + * or max array length checks. + * + * @private + * @param {number} n The number of times to invoke `iteratee`. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the array of results. + */ +function baseTimes(n, iteratee) { + var index = -1, + result = Array(n); + + while (++index < n) { + result[index] = iteratee(index); + } + return result; +} + +/** + * Creates a unary function that invokes `func` with its argument transformed. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ +function overArg(func, transform) { + return function(arg) { + return func(transform(arg)); + }; +} + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty$1 = objectProto.hasOwnProperty; + +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; + +/** Built-in value references. */ +var propertyIsEnumerable = objectProto.propertyIsEnumerable; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeKeys = overArg(Object.keys, Object), + nativeMax = Math.max; + +/** + * Creates an array of the enumerable property names of the array-like `value`. + * + * @private + * @param {*} value The value to query. + * @param {boolean} inherited Specify returning inherited property names. + * @returns {Array} Returns the array of property names. + */ +function arrayLikeKeys(value, inherited) { + // Safari 8.1 makes `arguments.callee` enumerable in strict mode. + // Safari 9 makes `arguments.length` enumerable in strict mode. + var result = (isArray(value) || isArguments(value)) + ? baseTimes(value.length, String) + : []; + + var length = result.length, + skipIndexes = !!length; + + for (var key in value) { + if ((inherited || hasOwnProperty$1.call(value, key)) && + !(skipIndexes && (key == 'length' || isIndex(key, length)))) { + result.push(key); + } + } + return result; +} + +/** + * Assigns `value` to `key` of `object` if the existing value is not equivalent + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ +function assignValue(object, key, value) { + var objValue = object[key]; + if (!(hasOwnProperty$1.call(object, key) && eq(objValue, value)) || + (value === undefined && !(key in object))) { + object[key] = value; + } +} + +/** + * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ +function baseKeys(object) { + if (!isPrototype(object)) { + return nativeKeys(object); + } + var result = []; + for (var key in Object(object)) { + if (hasOwnProperty$1.call(object, key) && key != 'constructor') { + result.push(key); + } + } + return result; +} + +/** + * The base implementation of `_.rest` which doesn't validate or coerce arguments. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. + */ +function baseRest(func, start) { + start = nativeMax(start === undefined ? (func.length - 1) : start, 0); + return function() { + var args = arguments, + index = -1, + length = nativeMax(args.length - start, 0), + array = Array(length); + + while (++index < length) { + array[index] = args[start + index]; + } + index = -1; + var otherArgs = Array(start + 1); + while (++index < start) { + otherArgs[index] = args[index]; + } + otherArgs[start] = array; + return apply(func, this, otherArgs); + }; +} + +/** + * Copies properties of `source` to `object`. + * + * @private + * @param {Object} source The object to copy properties from. + * @param {Array} props The property identifiers to copy. + * @param {Object} [object={}] The object to copy properties to. + * @param {Function} [customizer] The function to customize copied values. + * @returns {Object} Returns `object`. + */ +function copyObject(source, props, object, customizer) { + object || (object = {}); + + var index = -1, + length = props.length; + + while (++index < length) { + var key = props[index]; + + var newValue = customizer + ? customizer(object[key], source[key], key, object, source) + : undefined; + + assignValue(object, key, newValue === undefined ? source[key] : newValue); + } + return object; +} + +/** + * Creates a function like `_.assign`. + * + * @private + * @param {Function} assigner The function to assign values. + * @returns {Function} Returns the new assigner function. + */ +function createAssigner(assigner) { + return baseRest(function(object, sources) { + var index = -1, + length = sources.length, + customizer = length > 1 ? sources[length - 1] : undefined, + guard = length > 2 ? sources[2] : undefined; + + customizer = (assigner.length > 3 && typeof customizer == 'function') + ? (length--, customizer) + : undefined; + + if (guard && isIterateeCall(sources[0], sources[1], guard)) { + customizer = length < 3 ? undefined : customizer; + length = 1; + } + object = Object(object); + while (++index < length) { + var source = sources[index]; + if (source) { + assigner(object, source, index, customizer); + } + } + return object; + }); +} + +/** + * Checks if `value` is a valid array-like index. + * + * @private + * @param {*} value The value to check. + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + */ +function isIndex(value, length) { + length = length == null ? MAX_SAFE_INTEGER : length; + return !!length && + (typeof value == 'number' || reIsUint.test(value)) && + (value > -1 && value % 1 == 0 && value < length); +} + +/** + * Checks if the given arguments are from an iteratee call. + * + * @private + * @param {*} value The potential iteratee value argument. + * @param {*} index The potential iteratee index or key argument. + * @param {*} object The potential iteratee object argument. + * @returns {boolean} Returns `true` if the arguments are from an iteratee call, + * else `false`. + */ +function isIterateeCall(value, index, object) { + if (!isObject$1(object)) { + return false; + } + var type = typeof index; + if (type == 'number' + ? (isArrayLike$1(object) && isIndex(index, object.length)) + : (type == 'string' && index in object) + ) { + return eq(object[index], value); + } + return false; +} + +/** + * Checks if `value` is likely a prototype object. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. + */ +function isPrototype(value) { + var Ctor = value && value.constructor, + proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; + + return value === proto; +} + +/** + * Performs a + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * comparison between two values to determine if they are equivalent. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.eq(object, object); + * // => true + * + * _.eq(object, other); + * // => false + * + * _.eq('a', 'a'); + * // => true + * + * _.eq('a', Object('a')); + * // => false + * + * _.eq(NaN, NaN); + * // => true + */ +function eq(value, other) { + return value === other || (value !== value && other !== other); +} + +/** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ +function isArguments(value) { + // Safari 8.1 makes `arguments.callee` enumerable in strict mode. + return isArrayLikeObject(value) && hasOwnProperty$1.call(value, 'callee') && + (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); +} + +/** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ +var isArray = Array.isArray; + +/** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ +function isArrayLike$1(value) { + return value != null && isLength(value.length) && !isFunction$1(value); +} + +/** + * This method is like `_.isArrayLike` except that it also checks if `value` + * is an object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array-like object, + * else `false`. + * @example + * + * _.isArrayLikeObject([1, 2, 3]); + * // => true + * + * _.isArrayLikeObject(document.body.children); + * // => true + * + * _.isArrayLikeObject('abc'); + * // => false + * + * _.isArrayLikeObject(_.noop); + * // => false + */ +function isArrayLikeObject(value) { + return isObjectLike(value) && isArrayLike$1(value); +} + +/** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ +function isFunction$1(value) { + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 8-9 which returns 'object' for typed array and other constructors. + var tag = isObject$1(value) ? objectToString.call(value) : ''; + return tag == funcTag || tag == genTag; +} + +/** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ +function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; +} + +/** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ +function isObject$1(value) { + var type = typeof value; + return !!value && (type == 'object' || type == 'function'); +} + +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} + +/** + * This method is like `_.assign` except that it accepts `customizer` + * which is invoked to produce the assigned values. If `customizer` returns + * `undefined`, assignment is handled by the method instead. The `customizer` + * is invoked with five arguments: (objValue, srcValue, key, object, source). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} sources The source objects. + * @param {Function} [customizer] The function to customize assigned values. + * @returns {Object} Returns `object`. + * @see _.assignInWith + * @example + * + * function customizer(objValue, srcValue) { + * return _.isUndefined(objValue) ? srcValue : objValue; + * } + * + * var defaults = _.partialRight(_.assignWith, customizer); + * + * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); + * // => { 'a': 1, 'b': 2 } + */ +var assignWith = createAssigner(function(object, source, srcIndex, customizer) { + copyObject(source, keys(source), object, customizer); +}); + +/** + * Creates an array of the own enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. See the + * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * for more details. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keys(new Foo); + * // => ['a', 'b'] (iteration order is not guaranteed) + * + * _.keys('hi'); + * // => ['0', '1'] + */ +function keys(object) { + return isArrayLike$1(object) ? arrayLikeKeys(object) : baseKeys(object); +} + +var lodash_assignwith = assignWith; + +var assignWith$1 = /*@__PURE__*/getDefaultExportFromCjs(lodash_assignwith); + +/** + * Isomorphic, functional type-checking for Javascript. + * @module typical + * @typicalname t + * @example + * import * as t from 'typical' + * const allDefined = array.every(t.isDefined) + */ + + +/** + * A plain object is a simple object literal, it is not an instance of a class. Returns true if the input `typeof` is `object` and directly decends from `Object`. + * + * @param {*} input - The input to test + * @returns {boolean} + * @static + * @example + * > t.isPlainObject({ something: 'one' }) + * true + * > t.isPlainObject(new Date()) + * false + * > t.isPlainObject([ 0, 1 ]) + * false + * > t.isPlainObject(/test/) + * false + * > t.isPlainObject(1) + * false + * > t.isPlainObject('one') + * false + * > t.isPlainObject(null) + * false + * > t.isPlainObject((function * () {})()) + * false + * > t.isPlainObject(function * () {}) + * false + */ +function isPlainObject$1 (input) { + return input !== null && typeof input === 'object' && input.constructor === Object +} + +/** + * Returns true if the input value is defined. + * @param {*} input - The input to test + * @returns {boolean} + * @static + */ +function isDefined$1 (input) { + return typeof input !== 'undefined' +} + +function customiser (previousValue, newValue, key, object, source) { + /* deep merge plain objects */ + if (isPlainObject$1(previousValue) && isPlainObject$1(newValue)) { + return assignWith$1(previousValue, newValue, customiser) + /* overwrite arrays if the new array has items */ + } else if (Array.isArray(previousValue) && Array.isArray(newValue) && newValue.length) { + return newValue + /* ignore incoming arrays if empty */ + } else if (Array.isArray(newValue) && !newValue.length) { + return previousValue + } else if (!isDefined$1(previousValue) && Array.isArray(newValue)) { + return newValue + } +} + +function deepMerge (...args) { + return assignWith$1(...args, customiser) +} + +/** + * @module ansi + */ + +const ansiEscapeSequence = /\u001b.*?m/g; + +function remove (input) { + return input.replace(ansiEscapeSequence, '') +} + +function has (input) { + return ansiEscapeSequence.test(input) +} + +/** + * Array of arrays in.. Returns the length of the longest one + * @returns {number} + * @private + */ +function getLongestArray (arrays) { + const lengths = arrays.map(array => array.length); + return Math.max(...lengths) +} + +function padCell (cellValue, padding, width) { + const ansiLength = cellValue.length - remove(cellValue).length; + cellValue = cellValue || ''; + return (padding.left || '') + + cellValue.padEnd(width - padding.length() + ansiLength) + (padding.right || '') +} + +function getLongestWord (line) { + const words = Wordwrap.getChunks(line); + return words.reduce((max, word) => Math.max(word.length, max), 0) +} + +function removeEmptyColumns (data) { + const distinctColumnNames = data.reduce((columnNames, row) => { + for (const key of Object.keys(row)) { + if (!columnNames.includes(key)) { + columnNames.push(key); + } + } + return columnNames + }, []); + + const emptyColumns = distinctColumnNames.filter(columnName => { + const hasValue = data.some(row => { + const value = row[columnName]; + return (t$1.isDefined(value) && typeof value !== 'string') || (typeof value === 'string' && /\S+/.test(value)) + }); + return !hasValue + }); + + return data.map(row => { + for (const emptyCol of emptyColumns) { + delete row[emptyCol]; + } + return row + }) +} + +/** + * @module table-layout + */ + +/** + * Recordset data in (array of objects), text table out. + * @alias module:table-layout + */ +class Table { + /** + * @param {object[]} - input data + * @param [options] {object} - optional settings + * @param [options.maxWidth] {number} - maximum width of layout + * @param [options.noWrap] {boolean} - disable wrapping on all columns + * @param [options.noTrim] {boolean} - disable line-trimming + * @param [options.break] {boolean} - enable word-breaking on all columns + * @param [options.columns] {module:table-layout~columnOption} - array of column-specific options + * @param [options.ignoreEmptyColumns] {boolean} - If set, empty columns or columns containing only whitespace are not rendered. + * @param [options.padding] {object} - Padding values to set on each column. Per-column overrides can be set in the `options.columns` array. + * @param [options.padding.left] {string} - Defaults to a single space. + * @param [options.padding.right] {string} - Defaults to a single space. + * @param [options.eol] {string} - EOL character used. Defaults to `\n`. + * @alias module:table-layout + */ + constructor (data, options = {}) { + const defaults = { + padding: { + left: ' ', + right: ' ' + }, + maxWidth: 80, + columns: [], + eol: '\n' + }; + this.options = deepMerge(defaults, options); + this.rows = null; + this.columns = null; + this.load(data); + } + + /** + * Set the input data to display. Must be an array of objects. + * @param data {object[]} + */ + load (data) { + const options = this.options; + + /* remove empty columns */ + if (options.ignoreEmptyColumns) { + data = removeEmptyColumns(data); + } + + /* Create columns.. also removes ansi characters and measures column content width */ + this.columns = Columns.getColumns(data); + + /* load default column properties from options */ + this.columns.maxWidth = options.maxWidth; + for (const column of this.columns.list) { + column.padding = options.padding; + column.noWrap = options.noWrap; + column.break = options.break; + if (options.break) { + /* Force column to be wrappable */ + column.contentWrappable = true; + } + } + + /* load column properties from options.columns */ + for (const optionColumn of options.columns) { + const column = this.columns.get(optionColumn.name); + if (column) { + if (optionColumn.padding) { + column.padding.left = optionColumn.padding.left; + column.padding.right = optionColumn.padding.right; + } + column.width = optionColumn.width; + column.maxWidth = optionColumn.maxWidth; + column.minWidth = optionColumn.minWidth; + column.noWrap = optionColumn.noWrap; + column.break = optionColumn.break; + + if (optionColumn.break) { + /* Force column to be wrappable */ + column.contentWrappable = true; + } + + column.get = optionColumn.get; + } + } + + for (const row of arrayify(data)) { + for (const columnName in row) { + const column = this.columns.get(columnName); + + /* Remove ansi characters from cell value before calculating widths */ + const cell = new Cell(row[columnName], column); + let cellValue = cell.value; + if (has(cellValue)) { + cellValue = remove(cellValue); + } + + /* Update column content width if this if this cell is wider */ + if (cellValue.length > column.contentWidth) { + column.contentWidth = cellValue.length; + } + + /* Update column minContentWidth if this cell has a longer word */ + const longestWord = getLongestWord(cellValue); + if (longestWord > column.minContentWidth) { + column.minContentWidth = longestWord; + } + if (!column.contentWrappable) { + column.contentWrappable = Wordwrap.isWrappable(cellValue); + } + } + } + + this.columns.autoSize(); + this.rows = new Rows(data, this.columns); + return this + } + + getWrapped () { + this.columns.autoSize(); + return this.rows.list.map(row => { + const line = []; + for (const [column, cell] of row.entries()) { + if (column.noWrap) { + line.push(cell.value.split(/\r\n?|\n/)); + } else { + line.push(Wordwrap.lines(cell.value, { + width: column.wrappedContentWidth, + break: column.break, + noTrim: this.options.noTrim + })); + } + } + return line + }) + } + + getLines () { + const wrappedLines = this.getWrapped(); + const lines = []; + wrappedLines.forEach(wrapped => { + const mostLines = getLongestArray(wrapped); + for (let i = 0; i < mostLines; i++) { + const line = []; + wrapped.forEach(cell => { + line.push(cell[i] || ''); + }); + lines.push(line); + } + }); + return lines + } + + /** + * Identical to `.toString()` with the exception that the result will be an array of lines, rather than a single, multi-line string. + * @returns {string[]} + */ + renderLines () { + const lines = this.getLines(); + return lines.map(line => { + return line.reduce((prev, cell, index) => { + const column = this.columns.list[index]; + return prev + padCell(cell, column.padding, column.generatedWidth) + }, '') + }) + } + + /** + * Returns the input data as a text table. + * @returns {string} + */ + toString () { + return this.renderLines().join(this.options.eol) + this.options.eol + } +} + +/** + * Isomorphic, functional type-checking for Javascript. + * @module typical + * @typicalname t + * @example + * import * as t from 'typical' + * const allDefined = array.every(t.isDefined) + */ + +/** + * Returns true if input is a number (including infinity). It is a more reasonable alternative to `typeof n` which returns `number` for `NaN`. + * + * @param {*} n - The input to test + * @returns {boolean} `true` if input is a number + * @static + * @example + * > t.isNumber(0) + * true + * > t.isNumber(1) + * true + * > t.isNumber(1.1) + * true + * > t.isNumber(0xff) + * true + * > t.isNumber(0644) + * true + * > t.isNumber(6.2e5) + * true + * > t.isNumber(NaN) + * false + * > t.isNumber(Infinity) + * true + */ +function isNumber (n) { + return !isNaN(parseFloat(n)) +} + +/** + * Returns true if input is a finite number. Identical to `isNumber` beside excluding infinity. + * + * @param {*} n - The input to test + * @returns {boolean} + * @static + * @example + * > t.isFiniteNumber(0) + * true + * > t.isFiniteNumber(1) + * true + * > t.isFiniteNumber(1.1) + * true + * > t.isFiniteNumber(0xff) + * true + * > t.isFiniteNumber(0644) + * true + * > t.isFiniteNumber(6.2e5) + * true + * > t.isFiniteNumber(NaN) + * false + * > t.isFiniteNumber(Infinity) + * false + */ +function isFiniteNumber (n) { + return !isNaN(parseFloat(n)) && isFinite(n) +} + +/** + * A plain object is a simple object literal, it is not an instance of a class. Returns true if the input `typeof` is `object` and directly decends from `Object`. + * + * @param {*} input - The input to test + * @returns {boolean} + * @static + * @example + * > t.isPlainObject({ something: 'one' }) + * true + * > t.isPlainObject(new Date()) + * false + * > t.isPlainObject([ 0, 1 ]) + * false + * > t.isPlainObject(/test/) + * false + * > t.isPlainObject(1) + * false + * > t.isPlainObject('one') + * false + * > t.isPlainObject(null) + * false + * > t.isPlainObject((function * () {})()) + * false + * > t.isPlainObject(function * () {}) + * false + */ +function isPlainObject (input) { + return input !== null && typeof input === 'object' && input.constructor === Object +} + +/** + * An array-like value has all the properties of an array yet is not an array instance. An example is the `arguments` object. Returns `true`` if the input value is an object, not `null`` and has a `length` property set with a numeric value. + * + * @param {*} input - The input to test + * @returns {boolean} + * @static + * @example + * function sum(x, y){ + * console.log(t.isArrayLike(arguments)) + * // prints `true` + * } + */ +function isArrayLike (input) { + return isObject(input) && typeof input.length === 'number' +} + +/** + * Returns true if the typeof input is `'object'` but not null. + * @param {*} input - The input to test + * @returns {boolean} + * @static + */ +function isObject (input) { + return typeof input === 'object' && input !== null +} + +/** + * Returns true if the input value is defined. + * @param {*} input - The input to test + * @returns {boolean} + * @static + */ +function isDefined (input) { + return typeof input !== 'undefined' +} + +/** + * Returns true if the input value is undefined. + * @param {*} input - The input to test + * @returns {boolean} + * @static + */ +function isUndefined (input) { + return !isDefined(input) +} + +/** + * Returns true if the input value is null. + * @param {*} input - The input to test + * @returns {boolean} + * @static + */ +function isNull (input) { + return input === null +} + +/** + * Returns true if the input value is not one of `undefined`, `null`, or `NaN`. + * @param {*} input - The input to test + * @returns {boolean} + * @static + */ +function isDefinedValue (input) { + return isDefined(input) && !isNull(input) && !Number.isNaN(input) +} + +/** + * Returns true if the input value is an ES2015 `class`. + * @param {*} input - The input to test + * @returns {boolean} + * @static + */ +function isClass (input) { + if (typeof input === 'function') { + return /^class /.test(Function.prototype.toString.call(input)) + } else { + return false + } +} + +/** + * Returns true if the input is a string, number, symbol, boolean, null or undefined value. + * @param {*} input - The input to test + * @returns {boolean} + * @static + */ +function isPrimitive (input) { + if (input === null) return true + switch (typeof input) { + case 'string': + case 'number': + case 'symbol': + case 'undefined': + case 'boolean': + return true + default: + return false + } +} + +/** + * Returns true if the input is a Promise. + * @param {*} input - The input to test + * @returns {boolean} + * @static + */ +function isPromise (input) { + if (input) { + const isPromise = isDefined(Promise) && input instanceof Promise; + const isThenable = input.then && typeof input.then === 'function'; + return !!(isPromise || isThenable) + } else { + return false + } +} + +/** + * Returns true if the input is an iterable (`Map`, `Set`, `Array`, Generator etc.). + * @param {*} input - The input to test + * @returns {boolean} + * @static + * @example + * > t.isIterable('string') + * true + * > t.isIterable(new Map()) + * true + * > t.isIterable([]) + * true + * > t.isIterable((function * () {})()) + * true + * > t.isIterable(Promise.resolve()) + * false + * > t.isIterable(Promise) + * false + * > t.isIterable(true) + * false + * > t.isIterable({}) + * false + * > t.isIterable(0) + * false + * > t.isIterable(1.1) + * false + * > t.isIterable(NaN) + * false + * > t.isIterable(Infinity) + * false + * > t.isIterable(function () {}) + * false + * > t.isIterable(Date) + * false + * > t.isIterable() + * false + * > t.isIterable({ then: function () {} }) + * false + */ +function isIterable (input) { + if (input === null || !isDefined(input)) { + return false + } else { + return ( + typeof input[Symbol.iterator] === 'function' || + typeof input[Symbol.asyncIterator] === 'function' + ) + } +} + +/** + * Returns true if the input value is a string. The equivalent of `typeof input === 'string'` for use in funcitonal contexts. + * @param {*} input - The input to test + * @returns {boolean} + * @static + */ +function isString (input) { + return typeof input === 'string' +} + +/** + * Returns true if the input value is a function. The equivalent of `typeof input === 'function'` for use in funcitonal contexts. + * @param {*} input - The input to test + * @returns {boolean} + * @static + */ +function isFunction (input) { + return typeof input === 'function' +} + +var t = { + isNumber, + isFiniteNumber, + isPlainObject, + isArrayLike, + isObject, + isDefined, + isUndefined, + isNull, + isDefinedValue, + isClass, + isPrimitive, + isPromise, + isIterable, + isString, + isFunction +}; + +class OptionList extends Section { + constructor (data) { + super(); + let definitions = arrayify$1(data.optionList); + const hide = arrayify$1(data.hide); + const groups = arrayify$1(data.group); + + /* filter out hidden definitions */ + if (hide.length) { + definitions = definitions.filter(definition => { + return hide.indexOf(definition.name) === -1 + }); + } + + if (data.header) this.header(data.header); + + if (groups.length) { + definitions = definitions.filter(def => { + const noGroupMatch = groups.indexOf('_none') > -1 && !t.isDefined(def.group); + const groupMatch = intersect(arrayify$1(def.group), groups); + return (noGroupMatch || groupMatch) ? def : undefined + }); + } + + const rows = definitions.map(def => { + return { + option: getOptionNames(def, data.reverseNameOrder), + description: chalkFormat(def.description) + } + }); + + const tableOptions = data.tableOptions || { + padding: { left: ' ', right: ' ' }, + columns: [ + { name: 'option', noWrap: true }, + { name: 'description', maxWidth: 80 } + ] + }; + const table = new Table(rows, tableOptions); + this.add(table.renderLines()); + + this.add(); + } +} + +function getOptionNames (definition, reverseNameOrder) { + let type = definition.type ? definition.type.name.toLowerCase() : 'string'; + const multiple = (definition.multiple || definition.lazyMultiple) ? '[]' : ''; + if (type) { + type = type === 'boolean' ? '' : `{underline ${type}${multiple}}`; + } + type = chalkFormat(definition.typeLabel || type); + + let result = ''; + if (definition.alias) { + if (definition.name) { + if (reverseNameOrder) { + result = chalkFormat(`{bold --${definition.name}}, {bold -${definition.alias}} ${type}`); + } else { + result = chalkFormat(`{bold -${definition.alias}}, {bold --${definition.name}} ${type}`); + } + } else { + if (reverseNameOrder) { + result = chalkFormat(`{bold -${definition.alias}} ${type}`); + } else { + result = chalkFormat(`{bold -${definition.alias}} ${type}`); + } + } + } else { + result = chalkFormat(`{bold --${definition.name}} ${type}`); + } + return result +} + +function intersect (arr1, arr2) { + return arr1.some(function (item1) { + return arr2.some(function (item2) { + return item1 === item2 + }) + }) +} + +/** + * An OptionList section adds a table displaying the supplied option definitions. + * @typedef module:command-line-usage~optionList + * @property {string} [header] - The section header, always bold and underlined. + * @property optionList {OptionDefinition[]} - An array of [option definition](https://github.com/75lb/command-line-args/blob/master/doc/option-definition.md) objects. In addition to the regular definition properties, command-line-usage will look for: + * + * - `description` - a string describing the option. + * - `typeLabel` - a string to replace the default type string (e.g. ``). It's often more useful to set a more descriptive type label, like ``, ``, `` etc. + * @property {string|string[]} [group] - If specified, only options from this particular group will be printed. [Example](https://github.com/75lb/command-line-usage/blob/master/example/groups.js). + * @property {string|string[]} [hide] - The names of one of more option definitions to hide from the option list. [Example](https://github.com/75lb/command-line-usage/blob/master/example/hide.js). + * @property {boolean} [reverseNameOrder] - If true, the option alias will be displayed after the name, i.e. `--verbose, -v` instead of `-v, --verbose`). + * @property {object} [tableOptions] - An options object suitable for passing into [table-layout](https://github.com/75lb/table-layout#table-). See [here for an example](https://github.com/75lb/command-line-usage/blob/master/example/option-list-options.js). + * + * @example + * { + * header: 'Options', + * optionList: [ + * { + * name: 'help', + * alias: 'h', + * description: 'Display this usage guide.' + * }, + * { + * name: 'src', + * description: 'The input files to process', + * multiple: true, + * defaultOption: true, + * typeLabel: '{underline file} ...' + * }, + * { + * name: 'timeout', + * description: 'Timeout value in ms.', + * alias: 't', + * typeLabel: '{underline ms}' + * } + * ] + * } + */ + +class ContentSection extends Section { + constructor (section) { + super(); + this.header(section.header); + + if (section.content) { + /* add content without indentation or wrapping */ + if (section.raw) { + const content = arrayify$1(section.content).map(line => chalkFormat(line)); + this.add(content); + } else { + this.add(getContentLines(section.content)); + } + + this.add(); + } + } +} + +function getContentLines (content) { + const defaultPadding = { left: ' ', right: ' ' }; + + if (content) { + /* string content */ + if (t.isString(content)) { + const table = new Table({ column: chalkFormat(content) }, { + padding: defaultPadding, + maxWidth: 80 + }); + return table.renderLines() + + /* array of strings */ + } else if (Array.isArray(content) && content.every(t.isString)) { + const rows = content.map(string => ({ column: chalkFormat(string) })); + const table = new Table(rows, { + padding: defaultPadding, + maxWidth: 80 + }); + return table.renderLines() + + /* array of objects (use table-layout) */ + } else if (Array.isArray(content) && content.every(t.isPlainObject)) { + const table = new Table(content.map(row => ansiFormatRow(row)), { + padding: defaultPadding + }); + return table.renderLines() + + /* { options: object, data: object[] } */ + } else if (t.isPlainObject(content)) { + if (!content.options || !content.data) { + throw new Error('must have an "options" or "data" property\n' + JSON.stringify(content)) + } + const options = Object.assign( + { padding: defaultPadding }, + content.options + ); + + /* convert nowrap to noWrap to avoid breaking compatibility */ + if (options.columns) { + options.columns = options.columns.map(column => { + if (column.nowrap) { + column.noWrap = column.nowrap; + delete column.nowrap; + } + return column + }); + } + + const table = new Table( + content.data.map(row => ansiFormatRow(row)), + options + ); + return table.renderLines() + } else { + const message = `invalid input - 'content' must be a string, array of strings, or array of plain objects:\n\n${JSON.stringify(content)}`; + throw new Error(message) + } + } +} + +function ansiFormatRow (row) { + for (const key in row) { + row[key] = chalkFormat(row[key]); + } + return row +} + +/** + * A Content section comprises a header and one or more lines of content. + * @typedef module:command-line-usage~content + * @property header {string} - The section header, always bold and underlined. + * @property content {string|string[]|object[]} - Overloaded property, accepting data in one of four formats: + * + * 1. A single string (one line of text) + * 2. An array of strings (multiple lines of text) + * 3. An array of objects (recordset-style data). In this case, the data will be rendered in table format. The property names of each object are not important, so long as they are consistent throughout the array. + * 4. An object with two properties - `data` and `options`. In this case, the data and options will be passed directly to the underlying [table layout](https://github.com/75lb/table-layout) module for rendering. + * + * @property raw {boolean} - Set to true to avoid indentation and wrapping. Useful for banners. + * @example + * Simple string of content. For ansi formatting, use [chalk template literal syntax](https://github.com/chalk/chalk#tagged-template-literal). + * ```js + * { + * header: 'A typical app', + * content: 'Generates something {rgb(255,200,0).italic very {underline.bgRed important}}.' + * } + * ``` + * + * An array of strings is interpreted as lines, to be joined by the system newline character. + * ```js + * { + * header: 'A typical app', + * content: [ + * 'First line.', + * 'Second line.' + * ] + * } + * ``` + * + * An array of recordset-style objects are rendered in table layout. + * ```js + * { + * header: 'A typical app', + * content: [ + * { colA: 'First row, first column.', colB: 'First row, second column.'}, + * { colA: 'Second row, first column.', colB: 'Second row, second column.'} + * ] + * } + * ``` + * + * An object with `data` and `options` properties will be passed directly to the underlying [table layout](https://github.com/75lb/table-layout) module for rendering. + * ```js + * { + * header: 'A typical app', + * content: { + * data: [ + * { colA: 'First row, first column.', colB: 'First row, second column.'}, + * { colA: 'Second row, first column.', colB: 'Second row, second column.'} + * ], + * options: { + * maxWidth: 60 + * } + * } + * } + * ``` + */ + +/** + * @module command-line-usage + */ + +/** + * Generates a usage guide suitable for a command-line app. + * @param {Section|Section[]} - One or more section objects ({@link module:command-line-usage~content} or {@link module:command-line-usage~optionList}). + * @returns {string} + * @alias module:command-line-usage + */ +function commandLineUsage (sections) { + sections = arrayify$1(sections); + if (sections.length) { + const output = sections.map(section => { + if (section.optionList) { + return new OptionList(section) + } else { + return new ContentSection(section) + } + }); + return '\n' + output.join('\n') + } else { + return '' + } +} + +function formatCommands(cmds) { + return cmds + .sort((a, b) => (a.name > b.name ? 1 : -1)) + .filter(command => !command.hidden) + .map(command => { + return { + name: `${chalk$5.grey('$')} ${config.cli} ${command.name}`, + summary: command.description, + }; + }); +} +const owlbert = () => { + // http://asciiart.club + return ` 📖 ${chalk$5.blue.bold(config.cli)} + + ${chalk$5.bold('a utility for interacting with ReadMe')} + . + .\\\\ /. + ’ ‘ ‘ ‘ + ( nn\\\\ . . / ) + (nnnnn,.MM. AM .nn. + .nnnndMM----_______--M.’’ / + |nnn/nnnnnnnnnnnnnnnnn\\\\’mmm/ + /nnnn...nnnnnnnnnnn...mmmmm\\\\ + /nn ‘qnnnP’ ‘mmm\\\\ + /n’ .XXX. \\\\nnn/ .XX. \\\\mmb + An (XOXX) nnn (XOXX) mm\\\\ + /nn ‘XXXX’.~”~. ‘XXX”’ .mmmb + dnnn. ( )n. .mmmmb + .nnnnnn....n.\\\\ ./nnnnnnnnnmmmmmm\\\\ + (READnnnnnnnnnnn’Y’nnnnnnnnnnmmmmmmME) + REinnnnnnnnnnnnnnnnnnnnnnnnnmmmmmmmAD/ + /MEEnnnnnnnnnnnnnnnnnnnnnnnnnmmmmmmm)E'. + READnnnnnnn*’ ‘*mmmmmmmm)MEE. +(READ|nnnn’ \\\\../ \\\\.../ ‘mmmmmM)EEE) + READ(nn*’ ‘mmm.MEEE) + ‘READn’ \\\\._./ \\\\__./ \\\\.../ ‘MEE*’ + * /*`; +}; +/* : { + content?: string; + header?: string; + optionList?: Command.args[]; + raw?: boolean; + }[] */ +function commandUsage(cmd) { + const helpContent = [ + { + content: cmd.description, + raw: true, + }, + { + header: 'Usage', + content: `${config.cli} ${cmd.usage}`, + }, + { + header: 'Options', + optionList: [...cmd.args].concat([ + { + name: 'help', + alias: 'h', + type: Boolean, + description: 'Display this usage guide', + }, + ]), + hide: cmd.hiddenArgs || [], + }, + ]; + const similarCommands = getSimilar(cmd.cmdCategory, cmd.command); + if (similarCommands.length) { + helpContent.push({ + header: 'Related commands', + content: formatCommands(similarCommands), + }); + } + return commandLineUsage(helpContent); +} +async function globalUsage(args) { + const helpContent = [ + { + content: owlbert(), + raw: true, + }, + { + header: 'Usage', + content: `${config.cli} [arguments]`, + }, + { + header: 'Options', + optionList: args, + hide: ['command'], + }, + ]; + const categories = listByCategory(); + Object.keys(categories).forEach((key) => { + const category = categories[key]; + helpContent.push({ + header: category.description, + content: formatCommands(category.commands), + }); + }); + helpContent.push({ + content: `Run ${chalk$5.dim(`${config.cli} help `)} for help with a specific command.`, + raw: true, + }, { + content: 'To get more help with ReadMe, check out our docs at https://docs.readme.com.', + raw: true, + }); + return commandLineUsage(helpContent); +} + +const { version } = pkg; +/** + * @param {Array} processArgv - An array of arguments from the current process. Can be used to mock + * fake CLI calls. + * @return {Promise} + */ +function rdme(rawProcessArgv) { + const mainArgs = [ + { name: 'help', alias: 'h', type: Boolean, description: 'Display this usage guide' }, + { + name: 'version', + alias: 'v', + type: Boolean, + description: `Show the current ${config.cli} version (v${version})`, + }, + { name: 'command', type: String, defaultOption: true }, + ]; + let processArgv = rawProcessArgv; + debug(`raw process.argv: ${JSON.stringify(rawProcessArgv)}`); + /** + * We have a weird edge case with our Docker image version of `rdme` where GitHub Actions + * will pass all of the `rdme` arguments as a single string with escaped quotes, + * as opposed to the usual array of strings that we typically expect with `process.argv`. + * + * For example, say the user sends us `rdme openapi "petstore.json"`. + * Instead of `process.argv` being this (i.e., when running the command via CLI): + * ['openapi', 'petstore.json'] + * + * The GitHub Actions runner will send this to the `rdme` Docker image: + * ['openapi "petstore.json"'] + * + * To distinguish these, we have a hidden `docker-gha` argument which we check for to indicate + * when arguments are coming from the GitHub Actions runner. + * This logic checks for that `docker-gha` argument and parses the second string + * into the arguments array that `command-line-args` is expecting. + */ + if (rawProcessArgv.length === 2 && rawProcessArgv[0] === 'docker-gha') { + processArgv = parseArgsStringToArgv(rawProcessArgv[1]); + debug(`parsing arg string into argv: ${JSON.stringify(processArgv)}`); + } + if (process.env.INPUT_RDME) { + processArgv = parseArgsStringToArgv(process.env.INPUT_RDME); + debug(`parsing arg string for GHA into argv: ${JSON.stringify(processArgv)}`); + } + const argv = cliArgs(mainArgs, { partial: true, argv: processArgv }); + const cmd = argv.command || false; + debug(`command-line-args processing: ${JSON.stringify(argv)}`); + // Add support for `-V` as an additional `--version` alias. + if (typeof argv._unknown !== 'undefined') { + if (argv._unknown.indexOf('-V') !== -1) { + argv.version = true; + } + } + if (argv.version && (!cmd || cmd === 'help')) + return Promise.resolve(version); + let command = cmd || ''; + if (!command) { + command = 'help'; + } + if (command === 'help') { + argv.help = true; + } + try { + let cmdArgv; + let bin; + // Handling for `rdme help` and `rdme help ` cases. + if (command === 'help') { + if ((argv._unknown || []).length === 0) { + return Promise.resolve(globalUsage(mainArgs)); + } + if (argv._unknown.indexOf('-H') !== -1) { + return Promise.resolve(globalUsage(mainArgs)); + } + cmdArgv = cliArgs([{ name: 'subcommand', type: String, defaultOption: true }], { + argv: argv._unknown, + }); + if (!cmdArgv.subcommand) { + return Promise.resolve(globalUsage(mainArgs)); + } + bin = load(cmdArgv.subcommand); + return Promise.resolve(commandUsage(bin)); + } + bin = load(command); + // Handling for `rdme --help`. + if (argv.help) { + return Promise.resolve(commandUsage(bin)); + } + try { + cmdArgv = cliArgs(bin.args, { argv: argv._unknown || [] }); + } + catch (e) { + // If we have a command that has its own `--version` argument to accept data, that argument, + // if supplied in the `--version VERSION_STRING` format instead of `--version=VERSION_STRING`, + // will collide with the global version argument because their types differ and the argument + // parser gets confused. + // + // Instead of failing out to the user with an undecipherable "Unknown value: ..." error, let's + // try to parse their request again but a tad less eager. + if ((e.name !== 'UNKNOWN_VALUE' || (e.name === 'UNKNOWN_VALUE' && !argv.version)) && argv.command !== 'oas') { + throw e; + } + cmdArgv = cliArgs(bin.args, { partial: true, argv: processArgv.slice(1) }); + } + const { apiKey: key } = getCurrentConfig(); + cmdArgv = { key, ...cmdArgv }; + return bin.run(cmdArgv).then((msg) => { + if (bin.supportsGHA) { + return createGHA(msg, bin.command, bin.args, cmdArgv); + } + return msg; + }); + } + catch (e) { + if (e.message === 'Command not found.') { + e.message = `${e.message}\n\nType \`${chalk$5.yellow(`${config.cli} help`)}\` ${chalk$5.red('to see all commands')}`; + } + return Promise.reject(e); + } +} + +updateNotifier({ pkg }).notify(); +rdme(process.argv.slice(2)) + .then((msg) => { + if (msg) { + // eslint-disable-next-line no-console + console.log(msg); + if (isGHA()) { + coreExports.setOutput('rdme', msg); + } + } + return process.exit(0); +}) + .catch((err) => { + let message = `Yikes, something went wrong! Please try again and if the problem persists, get in touch with our support team at ${chalk$5.underline('support@readme.io')}.`; + if (err.message) { + message = err.message; + } + /** + * If we're in a GitHub Actions environment, log errors with that formatting instead. + * + * @see {@link https://docs.github.com/en/actions/using-workflows/workflow-commands-for-github-actions#setting-an-error-message} + * @see {@link https://github.com/actions/toolkit/tree/main/packages/core#annotations} + */ + if (isGHA()) { + return coreExports.setFailed(message); + } + // If this is a soft error then we should output the result as a regular log but exit the CLI + // with an error status code. + if (err.name === 'SoftError') { + // eslint-disable-next-line no-console + console.log(err.message); + } + else { + // eslint-disable-next-line no-console + console.error(chalk$5.red(`\n${message}\n`)); + } + return process.exit(1); +}); + +let s = 0; +const 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++, + END: s++ +}; + +let f = 1; +const F = { + 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; + +const lower = c => c | 0x20; + +const noop = () => {}; + +class MultipartParser { + /** + * @param {string} boundary + */ + constructor(boundary) { + this.index = 0; + this.flags = 0; + + this.onHeaderEnd = noop; + this.onHeaderField = noop; + this.onHeadersEnd = noop; + this.onHeaderValue = noop; + this.onPartBegin = noop; + this.onPartData = noop; + this.onPartEnd = noop; + + this.boundaryChars = {}; + + boundary = '\r\n--' + boundary; + const ui8a = new Uint8Array(boundary.length); + for (let i = 0; i < boundary.length; i++) { + ui8a[i] = boundary.charCodeAt(i); + this.boundaryChars[ui8a[i]] = true; + } + + this.boundary = ui8a; + this.lookbehind = new Uint8Array(this.boundary.length + 8); + this.state = S.START_BOUNDARY; + } + + /** + * @param {Uint8Array} data + */ + write(data) { + let i = 0; + const length_ = data.length; + let previousIndex = this.index; + let {lookbehind, boundary, boundaryChars, index, state, flags} = this; + const boundaryLength = this.boundary.length; + const boundaryEnd = boundaryLength - 1; + const bufferLength = data.length; + let c; + let cl; + + const mark = name => { + this[name + 'Mark'] = i; + }; + + const clear = name => { + delete this[name + 'Mark']; + }; + + const callback = (callbackSymbol, start, end, ui8a) => { + if (start === undefined || start !== end) { + this[callbackSymbol](ui8a && ui8a.subarray(start, end)); + } + }; + + const dataCallback = (name, clear) => { + const markSymbol = name + 'Mark'; + if (!(markSymbol in this)) { + return; + } + + if (clear) { + callback(name, this[markSymbol], i, data); + delete this[markSymbol]; + } else { + callback(name, this[markSymbol], data.length, data); + this[markSymbol] = 0; + } + }; + + for (i = 0; i < length_; i++) { + c = data[i]; + + switch (state) { + case S.START_BOUNDARY: + if (index === boundary.length - 2) { + if (c === HYPHEN) { + flags |= F.LAST_BOUNDARY; + } else if (c !== CR) { + return; + } + + index++; + break; + } else if (index - 1 === boundary.length - 2) { + if (flags & F.LAST_BOUNDARY && c === HYPHEN) { + state = S.END; + flags = 0; + } else if (!(flags & F.LAST_BOUNDARY) && c === LF) { + index = 0; + callback('onPartBegin'); + state = S.HEADER_FIELD_START; + } else { + return; + } + + break; + } + + if (c !== boundary[index + 2]) { + index = -2; + } + + if (c === boundary[index + 2]) { + index++; + } + + break; + case S.HEADER_FIELD_START: + state = S.HEADER_FIELD; + mark('onHeaderField'); + index = 0; + // falls through + case S.HEADER_FIELD: + if (c === CR) { + clear('onHeaderField'); + state = S.HEADERS_ALMOST_DONE; + break; + } + + index++; + if (c === HYPHEN) { + break; + } + + if (c === COLON) { + if (index === 1) { + // empty header field + return; + } + + dataCallback('onHeaderField', true); + state = S.HEADER_VALUE_START; + break; + } + + cl = lower(c); + if (cl < A || cl > Z) { + return; + } + + break; + case S.HEADER_VALUE_START: + if (c === SPACE) { + break; + } + + mark('onHeaderValue'); + state = S.HEADER_VALUE; + // falls through + case S.HEADER_VALUE: + if (c === CR) { + dataCallback('onHeaderValue', true); + callback('onHeaderEnd'); + state = S.HEADER_VALUE_ALMOST_DONE; + } + + break; + case S.HEADER_VALUE_ALMOST_DONE: + if (c !== LF) { + return; + } + + state = S.HEADER_FIELD_START; + break; + case S.HEADERS_ALMOST_DONE: + if (c !== LF) { + return; + } + + callback('onHeadersEnd'); + state = S.PART_DATA_START; + break; + case S.PART_DATA_START: + state = S.PART_DATA; + mark('onPartData'); + // falls through + case S.PART_DATA: + previousIndex = index; + + if (index === 0) { + // boyer-moore derrived algorithm to safely skip non-boundary data + i += boundaryEnd; + while (i < bufferLength && !(data[i] in boundaryChars)) { + i += boundaryLength; + } + + i -= boundaryEnd; + c = data[i]; + } + + if (index < boundary.length) { + if (boundary[index] === c) { + if (index === 0) { + dataCallback('onPartData', true); + } + + index++; + } else { + index = 0; + } + } else if (index === boundary.length) { + index++; + if (c === CR) { + // CR = part boundary + flags |= F.PART_BOUNDARY; + } else if (c === HYPHEN) { + // HYPHEN = end boundary + flags |= F.LAST_BOUNDARY; + } else { + index = 0; + } + } else if (index - 1 === boundary.length) { + if (flags & F.PART_BOUNDARY) { + index = 0; + if (c === LF) { + // unset the PART_BOUNDARY flag + flags &= ~F.PART_BOUNDARY; + callback('onPartEnd'); + callback('onPartBegin'); + state = S.HEADER_FIELD_START; + break; + } + } else if (flags & F.LAST_BOUNDARY) { + if (c === HYPHEN) { + callback('onPartEnd'); + state = S.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 (previousIndex > 0) { + // if our boundary turned out to be rubbish, the captured lookbehind + // belongs to partData + const _lookbehind = new Uint8Array(lookbehind.buffer, lookbehind.byteOffset, lookbehind.byteLength); + callback('onPartData', 0, previousIndex, _lookbehind); + previousIndex = 0; + mark('onPartData'); + + // reconsider the current character even so it interrupted the sequence + // it could be the beginning of a new sequence + i--; + } + + break; + case S.END: + break; + default: + throw new Error(`Unexpected state entered: ${state}`); + } + } + + dataCallback('onHeaderField'); + dataCallback('onHeaderValue'); + dataCallback('onPartData'); + + // Update properties for the next call + this.index = index; + this.state = state; + this.flags = flags; + } + + end() { + if ((this.state === S.HEADER_FIELD_START && this.index === 0) || + (this.state === S.PART_DATA && this.index === this.boundary.length)) { + this.onPartEnd(); + } else if (this.state !== S.END) { + throw new Error('MultipartParser.end(): stream ended unexpectedly'); + } + } +} + +function _fileName(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; + } + + const match = m[2] || m[3] || ''; + let filename = match.slice(match.lastIndexOf('\\') + 1); + filename = filename.replace(/%22/g, '"'); + filename = filename.replace(/&#(\d{4});/g, (m, code) => { + return String.fromCharCode(code); + }); + return filename; +} + +async function toFormData(Body, ct) { + if (!/multipart/i.test(ct)) { + throw new TypeError('Failed to fetch'); + } + + const m = ct.match(/boundary=(?:"([^"]+)"|([^;]+))/i); + + if (!m) { + throw new TypeError('no or bad content-type header, no multipart boundary'); + } + + const parser = new MultipartParser(m[1] || m[2]); + + let headerField; + let headerValue; + let entryValue; + let entryName; + let contentType; + let filename; + const entryChunks = []; + const formData = new FormData$1(); + + const onPartData = ui8a => { + entryValue += decoder.decode(ui8a, {stream: true}); + }; + + const appendToFile = ui8a => { + entryChunks.push(ui8a); + }; + + const appendFileToFormData = () => { + const file = new File$1(entryChunks, filename, {type: contentType}); + formData.append(entryName, file); + }; + + const appendEntryToFormData = () => { + formData.append(entryName, entryValue); + }; + + const decoder = new TextDecoder('utf-8'); + decoder.decode(); + + parser.onPartBegin = function () { + parser.onPartData = onPartData; + parser.onPartEnd = appendEntryToFormData; + + headerField = ''; + headerValue = ''; + entryValue = ''; + entryName = ''; + contentType = ''; + filename = null; + entryChunks.length = 0; + }; + + parser.onHeaderField = function (ui8a) { + headerField += decoder.decode(ui8a, {stream: true}); + }; + + parser.onHeaderValue = function (ui8a) { + headerValue += decoder.decode(ui8a, {stream: true}); + }; + + parser.onHeaderEnd = function () { + headerValue += decoder.decode(); + headerField = headerField.toLowerCase(); + + if (headerField === 'content-disposition') { + // matches either a quoted-string or a token (RFC 2616 section 19.5.1) + const m = headerValue.match(/\bname=("([^"]*)"|([^()<>@,;:\\"/[\]?={}\s\t]+))/i); + + if (m) { + entryName = m[2] || m[3] || ''; + } + + filename = _fileName(headerValue); + + if (filename) { + parser.onPartData = appendToFile; + parser.onPartEnd = appendFileToFormData; + } + } else if (headerField === 'content-type') { + contentType = headerValue; + } + + headerValue = ''; + headerField = ''; + }; + + for await (const chunk of Body) { + parser.write(chunk); + } + + parser.end(); + + return formData; +} + +var multipartParser = /*#__PURE__*/Object.freeze({ + __proto__: null, + toFormData: toFormData +}); diff --git a/rollup.config.js b/rollup.config.js index 1d5e82612..950cf002a 100644 --- a/rollup.config.js +++ b/rollup.config.js @@ -6,7 +6,7 @@ import { defineConfig } from 'rollup'; export default defineConfig({ input: 'bin/rdme.js', - output: { file: 'dist/rollup-output.cjs', format: 'cjs', inlineDynamicImports: true }, + output: { file: 'rollup-output.cjs', format: 'cjs', inlineDynamicImports: true }, plugins: [ commonjs(), json(), diff --git a/src/index.ts b/src/index.ts index 7b8e7de27..6d6f61d3b 100644 --- a/src/index.ts +++ b/src/index.ts @@ -60,6 +60,11 @@ export default function rdme(rawProcessArgv: NodeJS.Process['argv']) { debug(`parsing arg string into argv: ${JSON.stringify(processArgv)}`); } + if (process.env.INPUT_RDME) { + processArgv = parseArgsStringToArgv(process.env.INPUT_RDME); + debug(`parsing arg string for GHA into argv: ${JSON.stringify(processArgv)}`); + } + const argv = cliArgs(mainArgs, { partial: true, argv: processArgv }); const cmd = argv.command || false;