/******/ (() => { // webpackBootstrap /******/ var __webpack_modules__ = ({ /***/ 5623: /***/ ((module) => { "use strict"; module.exports = 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; } /***/ }), /***/ 3644: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var concatMap = __webpack_require__(1048); var balanced = __webpack_require__(5623); module.exports = 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 identity(e) { return e; } 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; } /***/ }), /***/ 2779: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var Buffer = (__webpack_require__(4300).Buffer); var CRC_TABLE = [ 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d ]; if (typeof Int32Array !== 'undefined') { CRC_TABLE = new Int32Array(CRC_TABLE); } function ensureBuffer(input) { if (Buffer.isBuffer(input)) { return input; } var hasNewBufferAPI = typeof Buffer.alloc === "function" && typeof Buffer.from === "function"; if (typeof input === "number") { return hasNewBufferAPI ? Buffer.alloc(input) : new Buffer(input); } else if (typeof input === "string") { return hasNewBufferAPI ? Buffer.from(input) : new Buffer(input); } else { throw new Error("input must be buffer, number, or string, received " + typeof input); } } function bufferizeInt(num) { var tmp = ensureBuffer(4); tmp.writeInt32BE(num, 0); return tmp; } function _crc32(buf, previous) { buf = ensureBuffer(buf); if (Buffer.isBuffer(previous)) { previous = previous.readUInt32BE(0); } var crc = ~~previous ^ -1; for (var n = 0; n < buf.length; n++) { crc = CRC_TABLE[(crc ^ buf[n]) & 0xff] ^ (crc >>> 8); } return (crc ^ -1); } function crc32() { return bufferizeInt(_crc32.apply(null, arguments)); } crc32.signed = function () { return _crc32.apply(null, arguments); }; crc32.unsigned = function () { return _crc32.apply(null, arguments) >>> 0; }; module.exports = crc32; /***/ }), /***/ 9019: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const fs = __webpack_require__(7147) const path = __webpack_require__(1017) /* istanbul ignore next */ const LCHOWN = fs.lchown ? 'lchown' : 'chown' /* istanbul ignore next */ const LCHOWNSYNC = fs.lchownSync ? 'lchownSync' : 'chownSync' /* istanbul ignore next */ const needEISDIRHandled = fs.lchown && !process.version.match(/v1[1-9]+\./) && !process.version.match(/v10\.[6-9]/) const lchownSync = (path, uid, gid) => { try { return fs[LCHOWNSYNC](path, uid, gid) } catch (er) { if (er.code !== 'ENOENT') throw er } } /* istanbul ignore next */ const chownSync = (path, uid, gid) => { try { return fs.chownSync(path, uid, gid) } catch (er) { if (er.code !== 'ENOENT') throw er } } /* istanbul ignore next */ const handleEISDIR = needEISDIRHandled ? (path, uid, gid, cb) => er => { // Node prior to v10 had a very questionable implementation of // fs.lchown, which would always try to call fs.open on a directory // Fall back to fs.chown in those cases. if (!er || er.code !== 'EISDIR') cb(er) else fs.chown(path, uid, gid, cb) } : (_, __, ___, cb) => cb /* istanbul ignore next */ const handleEISDirSync = needEISDIRHandled ? (path, uid, gid) => { try { return lchownSync(path, uid, gid) } catch (er) { if (er.code !== 'EISDIR') throw er chownSync(path, uid, gid) } } : (path, uid, gid) => lchownSync(path, uid, gid) // fs.readdir could only accept an options object as of node v6 const nodeVersion = process.version let readdir = (path, options, cb) => fs.readdir(path, options, cb) let readdirSync = (path, options) => fs.readdirSync(path, options) /* istanbul ignore next */ if (/^v4\./.test(nodeVersion)) readdir = (path, options, cb) => fs.readdir(path, cb) const chown = (cpath, uid, gid, cb) => { fs[LCHOWN](cpath, uid, gid, handleEISDIR(cpath, uid, gid, er => { // Skip ENOENT error cb(er && er.code !== 'ENOENT' ? er : null) })) } const chownrKid = (p, child, uid, gid, cb) => { if (typeof child === 'string') return fs.lstat(path.resolve(p, child), (er, stats) => { // Skip ENOENT error if (er) return cb(er.code !== 'ENOENT' ? er : null) stats.name = child chownrKid(p, stats, uid, gid, cb) }) if (child.isDirectory()) { chownr(path.resolve(p, child.name), uid, gid, er => { if (er) return cb(er) const cpath = path.resolve(p, child.name) chown(cpath, uid, gid, cb) }) } else { const cpath = path.resolve(p, child.name) chown(cpath, uid, gid, cb) } } const chownr = (p, uid, gid, cb) => { readdir(p, { withFileTypes: true }, (er, children) => { // any error other than ENOTDIR or ENOTSUP means it's not readable, // or doesn't exist. give up. if (er) { if (er.code === 'ENOENT') return cb() else if (er.code !== 'ENOTDIR' && er.code !== 'ENOTSUP') return cb(er) } if (er || !children.length) return chown(p, uid, gid, cb) let len = children.length let errState = null const then = er => { if (errState) return if (er) return cb(errState = er) if (-- len === 0) return chown(p, uid, gid, cb) } children.forEach(child => chownrKid(p, child, uid, gid, then)) }) } const chownrKidSync = (p, child, uid, gid) => { if (typeof child === 'string') { try { const stats = fs.lstatSync(path.resolve(p, child)) stats.name = child child = stats } catch (er) { if (er.code === 'ENOENT') return else throw er } } if (child.isDirectory()) chownrSync(path.resolve(p, child.name), uid, gid) handleEISDirSync(path.resolve(p, child.name), uid, gid) } const chownrSync = (p, uid, gid) => { let children try { children = readdirSync(p, { withFileTypes: true }) } catch (er) { if (er.code === 'ENOENT') return else if (er.code === 'ENOTDIR' || er.code === 'ENOTSUP') return handleEISDirSync(p, uid, gid) else throw er } if (children && children.length) children.forEach(child => chownrKidSync(p, child, uid, gid)) return handleEISDirSync(p, uid, gid) } module.exports = chownr chownr.sync = chownrSync /***/ }), /***/ 1048: /***/ ((module) => { module.exports = 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]'; }; /***/ }), /***/ 1227: /***/ ((module, exports, __webpack_require__) => { /* eslint-env browser */ /** * 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 = __webpack_require__(2447)(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; } }; /***/ }), /***/ 2447: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { /** * 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 = __webpack_require__(7824); 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.substr(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; } module.exports = setup; /***/ }), /***/ 5158: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { /** * 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) { module.exports = __webpack_require__(1227); } else { module.exports = __webpack_require__(39); } /***/ }), /***/ 39: /***/ ((module, exports, __webpack_require__) => { /** * Module dependencies. */ const tty = __webpack_require__(6224); const util = __webpack_require__(3837); /** * 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 = __webpack_require__(2130); 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 = __webpack_require__(2447)(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); }; /***/ }), /***/ 2840: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var once = __webpack_require__(778); var noop = function() {}; var isRequest = function(stream) { return stream.setHeader && typeof stream.abort === 'function'; }; var isChildProcess = function(stream) { return stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3 }; var eos = function(stream, opts, callback) { if (typeof opts === 'function') return eos(stream, null, opts); if (!opts) opts = {}; callback = once(callback || noop); var ws = stream._writableState; var rs = stream._readableState; var readable = opts.readable || (opts.readable !== false && stream.readable); var writable = opts.writable || (opts.writable !== false && stream.writable); var cancelled = false; var onlegacyfinish = function() { if (!stream.writable) onfinish(); }; var onfinish = function() { writable = false; if (!readable) callback.call(stream); }; var onend = function() { readable = false; if (!writable) callback.call(stream); }; var onexit = function(exitCode) { callback.call(stream, exitCode ? new Error('exited with error code: ' + exitCode) : null); }; var onerror = function(err) { callback.call(stream, err); }; var onclose = function() { process.nextTick(onclosenexttick); }; var onclosenexttick = function() { if (cancelled) return; if (readable && !(rs && (rs.ended && !rs.destroyed))) return callback.call(stream, new Error('premature close')); if (writable && !(ws && (ws.ended && !ws.destroyed))) return callback.call(stream, new Error('premature close')); }; var onrequest = function() { 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 && !ws) { // legacy streams stream.on('end', onlegacyfinish); stream.on('close', onlegacyfinish); } if (isChildProcess(stream)) stream.on('exit', onexit); stream.on('end', onend); stream.on('finish', onfinish); if (opts.error !== false) stream.on('error', onerror); stream.on('close', onclose); return function() { cancelled = true; 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('exit', onexit); stream.removeListener('end', onend); stream.removeListener('error', onerror); stream.removeListener('close', onclose); }; }; module.exports = eos; /***/ }), /***/ 2106: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const debug = __webpack_require__(5158)('extract-zip') // eslint-disable-next-line node/no-unsupported-features/node-builtins const { createWriteStream, promises: fs } = __webpack_require__(7147) const getStream = __webpack_require__(31) const path = __webpack_require__(1017) const { promisify } = __webpack_require__(3837) const stream = __webpack_require__(2781) const yauzl = __webpack_require__(7766) const openZip = promisify(yauzl.open) const pipeline = promisify(stream.pipeline) class Extractor { constructor (zipPath, opts) { this.zipPath = zipPath this.opts = opts } async extract () { debug('opening', this.zipPath, 'with opts', this.opts) this.zipfile = await openZip(this.zipPath, { lazyEntries: true }) this.canceled = false return new Promise((resolve, reject) => { this.zipfile.on('error', err => { this.canceled = true reject(err) }) this.zipfile.readEntry() this.zipfile.on('close', () => { if (!this.canceled) { debug('zip extraction complete') resolve() } }) this.zipfile.on('entry', async entry => { /* istanbul ignore if */ if (this.canceled) { debug('skipping entry', entry.fileName, { cancelled: this.canceled }) return } debug('zipfile entry', entry.fileName) if (entry.fileName.startsWith('__MACOSX/')) { this.zipfile.readEntry() return } const destDir = path.dirname(path.join(this.opts.dir, entry.fileName)) try { await fs.mkdir(destDir, { recursive: true }) const canonicalDestDir = await fs.realpath(destDir) const relativeDestDir = path.relative(this.opts.dir, canonicalDestDir) if (relativeDestDir.split(path.sep).includes('..')) { throw new Error(`Out of bound path "${canonicalDestDir}" found while processing file ${entry.fileName}`) } await this.extractEntry(entry) debug('finished processing', entry.fileName) this.zipfile.readEntry() } catch (err) { this.canceled = true this.zipfile.close() reject(err) } }) }) } async extractEntry (entry) { /* istanbul ignore if */ if (this.canceled) { debug('skipping entry extraction', entry.fileName, { cancelled: this.canceled }) return } if (this.opts.onEntry) { this.opts.onEntry(entry, this.zipfile) } const dest = path.join(this.opts.dir, entry.fileName) // convert external file attr int into a fs stat mode int const mode = (entry.externalFileAttributes >> 16) & 0xFFFF // check if it's a symlink or dir (using stat mode constants) const IFMT = 61440 const IFDIR = 16384 const IFLNK = 40960 const symlink = (mode & IFMT) === IFLNK let isDir = (mode & IFMT) === IFDIR // Failsafe, borrowed from jsZip if (!isDir && entry.fileName.endsWith('/')) { isDir = true } // check for windows weird way of specifying a directory // https://github.com/maxogden/extract-zip/issues/13#issuecomment-154494566 const madeBy = entry.versionMadeBy >> 8 if (!isDir) isDir = (madeBy === 0 && entry.externalFileAttributes === 16) debug('extracting entry', { filename: entry.fileName, isDir: isDir, isSymlink: symlink }) const procMode = this.getExtractedMode(mode, isDir) & 0o777 // always ensure folders are created const destDir = isDir ? dest : path.dirname(dest) const mkdirOptions = { recursive: true } if (isDir) { mkdirOptions.mode = procMode } debug('mkdir', { dir: destDir, ...mkdirOptions }) await fs.mkdir(destDir, mkdirOptions) if (isDir) return debug('opening read stream', dest) const readStream = await promisify(this.zipfile.openReadStream.bind(this.zipfile))(entry) if (symlink) { const link = await getStream(readStream) debug('creating symlink', link, dest) await fs.symlink(link, dest) } else { await pipeline(readStream, createWriteStream(dest, { mode: procMode })) } } getExtractedMode (entryMode, isDir) { let mode = entryMode // Set defaults, if necessary if (mode === 0) { if (isDir) { if (this.opts.defaultDirMode) { mode = parseInt(this.opts.defaultDirMode, 10) } if (!mode) { mode = 0o755 } } else { if (this.opts.defaultFileMode) { mode = parseInt(this.opts.defaultFileMode, 10) } if (!mode) { mode = 0o644 } } } return mode } } module.exports = async function (zipPath, opts) { debug('creating target directory', opts.dir) if (!path.isAbsolute(opts.dir)) { throw new Error('Target directory is expected to be absolute') } await fs.mkdir(opts.dir, { recursive: true }) opts.dir = await fs.realpath(opts.dir) return new Extractor(zipPath, opts).extract() } /***/ }), /***/ 8913: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { var fs = __webpack_require__(7147); var util = __webpack_require__(3837); var stream = __webpack_require__(2781); var Readable = stream.Readable; var Writable = stream.Writable; var PassThrough = stream.PassThrough; var Pend = __webpack_require__(9916); var EventEmitter = (__webpack_require__(2361).EventEmitter); exports.createFromBuffer = createFromBuffer; exports.createFromFd = createFromFd; exports.BufferSlicer = BufferSlicer; exports.FdSlicer = FdSlicer; util.inherits(FdSlicer, EventEmitter); function FdSlicer(fd, options) { options = options || {}; EventEmitter.call(this); this.fd = fd; this.pend = new Pend(); this.pend.max = 1; this.refCount = 0; this.autoClose = !!options.autoClose; } FdSlicer.prototype.read = function(buffer, offset, length, position, callback) { var self = this; self.pend.go(function(cb) { fs.read(self.fd, buffer, offset, length, position, function(err, bytesRead, buffer) { cb(); callback(err, bytesRead, buffer); }); }); }; FdSlicer.prototype.write = function(buffer, offset, length, position, callback) { var self = this; self.pend.go(function(cb) { fs.write(self.fd, buffer, offset, length, position, function(err, written, buffer) { cb(); callback(err, written, buffer); }); }); }; FdSlicer.prototype.createReadStream = function(options) { return new ReadStream(this, options); }; FdSlicer.prototype.createWriteStream = function(options) { return new WriteStream(this, options); }; FdSlicer.prototype.ref = function() { this.refCount += 1; }; FdSlicer.prototype.unref = function() { var self = this; self.refCount -= 1; if (self.refCount > 0) return; if (self.refCount < 0) throw new Error("invalid unref"); if (self.autoClose) { fs.close(self.fd, onCloseDone); } function onCloseDone(err) { if (err) { self.emit('error', err); } else { self.emit('close'); } } }; util.inherits(ReadStream, Readable); function ReadStream(context, options) { options = options || {}; Readable.call(this, options); this.context = context; this.context.ref(); this.start = options.start || 0; this.endOffset = options.end; this.pos = this.start; this.destroyed = false; } ReadStream.prototype._read = function(n) { var self = this; if (self.destroyed) return; var toRead = Math.min(self._readableState.highWaterMark, n); if (self.endOffset != null) { toRead = Math.min(toRead, self.endOffset - self.pos); } if (toRead <= 0) { self.destroyed = true; self.push(null); self.context.unref(); return; } self.context.pend.go(function(cb) { if (self.destroyed) return cb(); var buffer = new Buffer(toRead); fs.read(self.context.fd, buffer, 0, toRead, self.pos, function(err, bytesRead) { if (err) { self.destroy(err); } else if (bytesRead === 0) { self.destroyed = true; self.push(null); self.context.unref(); } else { self.pos += bytesRead; self.push(buffer.slice(0, bytesRead)); } cb(); }); }); }; ReadStream.prototype.destroy = function(err) { if (this.destroyed) return; err = err || new Error("stream destroyed"); this.destroyed = true; this.emit('error', err); this.context.unref(); }; util.inherits(WriteStream, Writable); function WriteStream(context, options) { options = options || {}; Writable.call(this, options); this.context = context; this.context.ref(); this.start = options.start || 0; this.endOffset = (options.end == null) ? Infinity : +options.end; this.bytesWritten = 0; this.pos = this.start; this.destroyed = false; this.on('finish', this.destroy.bind(this)); } WriteStream.prototype._write = function(buffer, encoding, callback) { var self = this; if (self.destroyed) return; if (self.pos + buffer.length > self.endOffset) { var err = new Error("maximum file length exceeded"); err.code = 'ETOOBIG'; self.destroy(); callback(err); return; } self.context.pend.go(function(cb) { if (self.destroyed) return cb(); fs.write(self.context.fd, buffer, 0, buffer.length, self.pos, function(err, bytes) { if (err) { self.destroy(); cb(); callback(err); } else { self.bytesWritten += bytes; self.pos += bytes; self.emit('progress'); cb(); callback(); } }); }); }; WriteStream.prototype.destroy = function() { if (this.destroyed) return; this.destroyed = true; this.context.unref(); }; util.inherits(BufferSlicer, EventEmitter); function BufferSlicer(buffer, options) { EventEmitter.call(this); options = options || {}; this.refCount = 0; this.buffer = buffer; this.maxChunkSize = options.maxChunkSize || Number.MAX_SAFE_INTEGER; } BufferSlicer.prototype.read = function(buffer, offset, length, position, callback) { var end = position + length; var delta = end - this.buffer.length; var written = (delta > 0) ? delta : length; this.buffer.copy(buffer, offset, position, end); setImmediate(function() { callback(null, written); }); }; BufferSlicer.prototype.write = function(buffer, offset, length, position, callback) { buffer.copy(this.buffer, position, offset, offset + length); setImmediate(function() { callback(null, length, buffer); }); }; BufferSlicer.prototype.createReadStream = function(options) { options = options || {}; var readStream = new PassThrough(options); readStream.destroyed = false; readStream.start = options.start || 0; readStream.endOffset = options.end; // by the time this function returns, we'll be done. readStream.pos = readStream.endOffset || this.buffer.length; // respect the maxChunkSize option to slice up the chunk into smaller pieces. var entireSlice = this.buffer.slice(readStream.start, readStream.pos); var offset = 0; while (true) { var nextOffset = offset + this.maxChunkSize; if (nextOffset >= entireSlice.length) { // last chunk if (offset < entireSlice.length) { readStream.write(entireSlice.slice(offset, entireSlice.length)); } break; } readStream.write(entireSlice.slice(offset, nextOffset)); offset = nextOffset; } readStream.end(); readStream.destroy = function() { readStream.destroyed = true; }; return readStream; }; BufferSlicer.prototype.createWriteStream = function(options) { var bufferSlicer = this; options = options || {}; var writeStream = new Writable(options); writeStream.start = options.start || 0; writeStream.endOffset = (options.end == null) ? this.buffer.length : +options.end; writeStream.bytesWritten = 0; writeStream.pos = writeStream.start; writeStream.destroyed = false; writeStream._write = function(buffer, encoding, callback) { if (writeStream.destroyed) return; var end = writeStream.pos + buffer.length; if (end > writeStream.endOffset) { var err = new Error("maximum file length exceeded"); err.code = 'ETOOBIG'; writeStream.destroyed = true; callback(err); return; } buffer.copy(bufferSlicer.buffer, writeStream.pos, 0, buffer.length); writeStream.bytesWritten += buffer.length; writeStream.pos = end; writeStream.emit('progress'); callback(); }; writeStream.destroy = function() { writeStream.destroyed = true; }; return writeStream; }; BufferSlicer.prototype.ref = function() { this.refCount += 1; }; BufferSlicer.prototype.unref = function() { this.refCount -= 1; if (this.refCount < 0) { throw new Error("invalid unref"); } }; function createFromBuffer(buffer, options) { return new BufferSlicer(buffer, options); } function createFromFd(fd, options) { return new FdSlicer(fd, options); } /***/ }), /***/ 292: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; const MiniPass = __webpack_require__(5736) const EE = (__webpack_require__(2361).EventEmitter) const fs = __webpack_require__(7147) let writev = fs.writev /* istanbul ignore next */ if (!writev) { // This entire block can be removed if support for earlier than Node.js // 12.9.0 is not needed. const binding = process.binding('fs') const FSReqWrap = binding.FSReqWrap || binding.FSReqCallback writev = (fd, iovec, pos, cb) => { const done = (er, bw) => cb(er, bw, iovec) const req = new FSReqWrap() req.oncomplete = done binding.writeBuffers(fd, iovec, pos, req) } } const _autoClose = Symbol('_autoClose') const _close = Symbol('_close') const _ended = Symbol('_ended') const _fd = Symbol('_fd') const _finished = Symbol('_finished') const _flags = Symbol('_flags') const _flush = Symbol('_flush') const _handleChunk = Symbol('_handleChunk') const _makeBuf = Symbol('_makeBuf') const _mode = Symbol('_mode') const _needDrain = Symbol('_needDrain') const _onerror = Symbol('_onerror') const _onopen = Symbol('_onopen') const _onread = Symbol('_onread') const _onwrite = Symbol('_onwrite') const _open = Symbol('_open') const _path = Symbol('_path') const _pos = Symbol('_pos') const _queue = Symbol('_queue') const _read = Symbol('_read') const _readSize = Symbol('_readSize') const _reading = Symbol('_reading') const _remain = Symbol('_remain') const _size = Symbol('_size') const _write = Symbol('_write') const _writing = Symbol('_writing') const _defaultFlag = Symbol('_defaultFlag') const _errored = Symbol('_errored') class ReadStream extends MiniPass { constructor (path, opt) { opt = opt || {} super(opt) this.readable = true this.writable = false if (typeof path !== 'string') throw new TypeError('path must be a string') this[_errored] = false this[_fd] = typeof opt.fd === 'number' ? opt.fd : null this[_path] = path this[_readSize] = opt.readSize || 16*1024*1024 this[_reading] = false this[_size] = typeof opt.size === 'number' ? opt.size : Infinity this[_remain] = this[_size] this[_autoClose] = typeof opt.autoClose === 'boolean' ? opt.autoClose : true if (typeof this[_fd] === 'number') this[_read]() else this[_open]() } get fd () { return this[_fd] } get path () { return this[_path] } write () { throw new TypeError('this is a readable stream') } end () { throw new TypeError('this is a readable stream') } [_open] () { fs.open(this[_path], 'r', (er, fd) => this[_onopen](er, fd)) } [_onopen] (er, fd) { if (er) this[_onerror](er) else { this[_fd] = fd this.emit('open', fd) this[_read]() } } [_makeBuf] () { return Buffer.allocUnsafe(Math.min(this[_readSize], this[_remain])) } [_read] () { if (!this[_reading]) { this[_reading] = true const buf = this[_makeBuf]() /* istanbul ignore if */ if (buf.length === 0) return process.nextTick(() => this[_onread](null, 0, buf)) fs.read(this[_fd], buf, 0, buf.length, null, (er, br, buf) => this[_onread](er, br, buf)) } } [_onread] (er, br, buf) { this[_reading] = false if (er) this[_onerror](er) else if (this[_handleChunk](br, buf)) this[_read]() } [_close] () { if (this[_autoClose] && typeof this[_fd] === 'number') { const fd = this[_fd] this[_fd] = null fs.close(fd, er => er ? this.emit('error', er) : this.emit('close')) } } [_onerror] (er) { this[_reading] = true this[_close]() this.emit('error', er) } [_handleChunk] (br, buf) { let ret = false // no effect if infinite this[_remain] -= br if (br > 0) ret = super.write(br < buf.length ? buf.slice(0, br) : buf) if (br === 0 || this[_remain] <= 0) { ret = false this[_close]() super.end() } return ret } emit (ev, data) { switch (ev) { case 'prefinish': case 'finish': break case 'drain': if (typeof this[_fd] === 'number') this[_read]() break case 'error': if (this[_errored]) return this[_errored] = true return super.emit(ev, data) default: return super.emit(ev, data) } } } class ReadStreamSync extends ReadStream { [_open] () { let threw = true try { this[_onopen](null, fs.openSync(this[_path], 'r')) threw = false } finally { if (threw) this[_close]() } } [_read] () { let threw = true try { if (!this[_reading]) { this[_reading] = true do { const buf = this[_makeBuf]() /* istanbul ignore next */ const br = buf.length === 0 ? 0 : fs.readSync(this[_fd], buf, 0, buf.length, null) if (!this[_handleChunk](br, buf)) break } while (true) this[_reading] = false } threw = false } finally { if (threw) this[_close]() } } [_close] () { if (this[_autoClose] && typeof this[_fd] === 'number') { const fd = this[_fd] this[_fd] = null fs.closeSync(fd) this.emit('close') } } } class WriteStream extends EE { constructor (path, opt) { opt = opt || {} super(opt) this.readable = false this.writable = true this[_errored] = false this[_writing] = false this[_ended] = false this[_needDrain] = false this[_queue] = [] this[_path] = path this[_fd] = typeof opt.fd === 'number' ? opt.fd : null this[_mode] = opt.mode === undefined ? 0o666 : opt.mode this[_pos] = typeof opt.start === 'number' ? opt.start : null this[_autoClose] = typeof opt.autoClose === 'boolean' ? opt.autoClose : true // truncating makes no sense when writing into the middle const defaultFlag = this[_pos] !== null ? 'r+' : 'w' this[_defaultFlag] = opt.flags === undefined this[_flags] = this[_defaultFlag] ? defaultFlag : opt.flags if (this[_fd] === null) this[_open]() } emit (ev, data) { if (ev === 'error') { if (this[_errored]) return this[_errored] = true } return super.emit(ev, data) } get fd () { return this[_fd] } get path () { return this[_path] } [_onerror] (er) { this[_close]() this[_writing] = true this.emit('error', er) } [_open] () { fs.open(this[_path], this[_flags], this[_mode], (er, fd) => this[_onopen](er, fd)) } [_onopen] (er, fd) { if (this[_defaultFlag] && this[_flags] === 'r+' && er && er.code === 'ENOENT') { this[_flags] = 'w' this[_open]() } else if (er) this[_onerror](er) else { this[_fd] = fd this.emit('open', fd) this[_flush]() } } end (buf, enc) { if (buf) this.write(buf, enc) this[_ended] = true // synthetic after-write logic, where drain/finish live if (!this[_writing] && !this[_queue].length && typeof this[_fd] === 'number') this[_onwrite](null, 0) return this } write (buf, enc) { if (typeof buf === 'string') buf = Buffer.from(buf, enc) if (this[_ended]) { this.emit('error', new Error('write() after end()')) return false } if (this[_fd] === null || this[_writing] || this[_queue].length) { this[_queue].push(buf) this[_needDrain] = true return false } this[_writing] = true this[_write](buf) return true } [_write] (buf) { fs.write(this[_fd], buf, 0, buf.length, this[_pos], (er, bw) => this[_onwrite](er, bw)) } [_onwrite] (er, bw) { if (er) this[_onerror](er) else { if (this[_pos] !== null) this[_pos] += bw if (this[_queue].length) this[_flush]() else { this[_writing] = false if (this[_ended] && !this[_finished]) { this[_finished] = true this[_close]() this.emit('finish') } else if (this[_needDrain]) { this[_needDrain] = false this.emit('drain') } } } } [_flush] () { if (this[_queue].length === 0) { if (this[_ended]) this[_onwrite](null, 0) } else if (this[_queue].length === 1) this[_write](this[_queue].pop()) else { const iovec = this[_queue] this[_queue] = [] writev(this[_fd], iovec, this[_pos], (er, bw) => this[_onwrite](er, bw)) } } [_close] () { if (this[_autoClose] && typeof this[_fd] === 'number') { const fd = this[_fd] this[_fd] = null fs.close(fd, er => er ? this.emit('error', er) : this.emit('close')) } } } class WriteStreamSync extends WriteStream { [_open] () { let fd // only wrap in a try{} block if we know we'll retry, to avoid // the rethrow obscuring the error's source frame in most cases. if (this[_defaultFlag] && this[_flags] === 'r+') { try { fd = fs.openSync(this[_path], this[_flags], this[_mode]) } catch (er) { if (er.code === 'ENOENT') { this[_flags] = 'w' return this[_open]() } else throw er } } else fd = fs.openSync(this[_path], this[_flags], this[_mode]) this[_onopen](null, fd) } [_close] () { if (this[_autoClose] && typeof this[_fd] === 'number') { const fd = this[_fd] this[_fd] = null fs.closeSync(fd) this.emit('close') } } [_write] (buf) { // throw the original, but try to close if it fails let threw = true try { this[_onwrite](null, fs.writeSync(this[_fd], buf, 0, buf.length, this[_pos])) threw = false } finally { if (threw) try { this[_close]() } catch (_) {} } } } exports.ReadStream = ReadStream exports.ReadStreamSync = ReadStreamSync exports.WriteStream = WriteStream exports.WriteStreamSync = WriteStreamSync /***/ }), /***/ 5105: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const {PassThrough: PassThroughStream} = __webpack_require__(2781); module.exports = 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; }; /***/ }), /***/ 31: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const {constants: BufferConstants} = __webpack_require__(4300); const pump = __webpack_require__(4286); const bufferStream = __webpack_require__(5105); class MaxBufferError extends Error { constructor() { super('maxBuffer exceeded'); this.name = 'MaxBufferError'; } } async function getStream(inputStream, options) { if (!inputStream) { return Promise.reject(new Error('Expected a stream')); } options = { maxBuffer: Infinity, ...options }; const {maxBuffer} = options; let stream; 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); }; stream = pump(inputStream, bufferStream(options), error => { if (error) { rejectPromise(error); return; } resolve(); }); stream.on('data', () => { if (stream.getBufferedLength() > maxBuffer) { rejectPromise(new MaxBufferError()); } }); }); return stream.getBufferedValue(); } module.exports = getStream; // TODO: Remove this for the next major release module.exports["default"] = getStream; module.exports.buffer = (stream, options) => getStream(stream, {...options, encoding: 'buffer'}); module.exports.array = (stream, options) => getStream(stream, {...options, array: true}); module.exports.MaxBufferError = MaxBufferError; /***/ }), /***/ 8512: /***/ ((module) => { "use strict"; module.exports = (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); }; /***/ }), /***/ 9593: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; // A linked list to keep track of recently-used-ness const Yallist = __webpack_require__(4411) 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. const max = 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) } module.exports = LRUCache /***/ }), /***/ 1171: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { module.exports = minimatch minimatch.Minimatch = Minimatch var path = { sep: '/' } try { path = __webpack_require__(1017) } catch (er) {} var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {} var expand = __webpack_require__(3644) 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) { a = a || {} b = b || {} var t = {} Object.keys(b).forEach(function (k) { t[k] = b[k] }) Object.keys(a).forEach(function (k) { t[k] = a[k] }) return t } minimatch.defaults = function (def) { if (!def || !Object.keys(def).length) return minimatch var orig = minimatch var m = function minimatch (p, pattern, options) { return orig.minimatch(p, pattern, ext(def, options)) } m.Minimatch = function Minimatch (pattern, options) { return new orig.Minimatch(pattern, ext(def, options)) } return m } Minimatch.defaults = function (def) { if (!def || !Object.keys(def).length) return Minimatch return minimatch.defaults(def).Minimatch } function minimatch (p, pattern, options) { if (typeof pattern !== 'string') { throw new TypeError('glob pattern string required') } if (!options) options = {} // shortcut: comments match nothing. if (!options.nocomment && pattern.charAt(0) === '#') { return false } // "" only matches "" if (pattern.trim() === '') return p === '' return new Minimatch(pattern, options).match(p) } function Minimatch (pattern, options) { if (!(this instanceof Minimatch)) { return new Minimatch(pattern, options) } if (typeof pattern !== 'string') { throw new TypeError('glob pattern string required') } if (!options) options = {} pattern = pattern.trim() // windows support: need to use /, not \ if (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 // make the set of regexps etc. this.make() } Minimatch.prototype.debug = function () {} Minimatch.prototype.make = make function make () { // don't do it more than once. if (this._made) return 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 = console.error 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 if (typeof pattern === 'undefined') { throw new TypeError('undefined pattern') } if (options.nobrace || !pattern.match(/\{.*\}/)) { // shortcut. no need to expand. return [pattern] } return expand(pattern) } // 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) { if (pattern.length > 1024 * 64) { throw new TypeError('pattern is too long') } var options = this.options // shortcuts if (!options.noglobstar && pattern === '**') return GLOBSTAR 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) { 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 (?:) 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\]" if (inClass) { // 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) { // 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) { 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 = match function match (f, 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. 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 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') { if (options.nocase) { hit = f.toLowerCase() === p.toLowerCase() } else { 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 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/ var emptyFileEnd = (fi === fl - 1) && (file[fi] === '') return emptyFileEnd } // should be unreachable. throw new Error('wtf?') } // replace stuff like \* with * function globUnescape (s) { return s.replace(/\\(.)/g, '$1') } function regExpEscape (s) { return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') } /***/ }), /***/ 5736: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const proc = typeof process === 'object' && process ? process : { stdout: null, stderr: null, } const EE = __webpack_require__(2361) const Stream = __webpack_require__(2781) const Yallist = __webpack_require__(4411) const SD = (__webpack_require__(1576).StringDecoder) const EOF = Symbol('EOF') const MAYBE_EMIT_END = Symbol('maybeEmitEnd') const EMITTED_END = Symbol('emittedEnd') const EMITTING_END = Symbol('emittingEnd') const EMITTED_ERROR = Symbol('emittedError') const CLOSED = Symbol('closed') const READ = Symbol('read') const FLUSH = Symbol('flush') const FLUSHCHUNK = Symbol('flushChunk') const ENCODING = Symbol('encoding') const DECODER = Symbol('decoder') const FLOWING = Symbol('flowing') const PAUSED = Symbol('paused') const RESUME = Symbol('resume') const BUFFERLENGTH = Symbol('bufferLength') const BUFFERPUSH = Symbol('bufferPush') const BUFFERSHIFT = Symbol('bufferShift') const OBJECTMODE = Symbol('objectMode') const DESTROYED = Symbol('destroyed') // TODO remove when Node v8 support drops const doIter = global._MP_NO_ITERATOR_SYMBOLS_ !== '1' const ASYNCITERATOR = doIter && Symbol.asyncIterator || Symbol('asyncIterator not implemented') const ITERATOR = doIter && Symbol.iterator || Symbol('iterator not implemented') // events that mean 'the stream is over' // these are treated specially, and re-emitted // if they are listened for after emitting. const isEndish = ev => ev === 'end' || ev === 'finish' || ev === 'prefinish' const isArrayBuffer = b => b instanceof ArrayBuffer || typeof b === 'object' && b.constructor && b.constructor.name === 'ArrayBuffer' && b.byteLength >= 0 const isArrayBufferView = b => !Buffer.isBuffer(b) && ArrayBuffer.isView(b) module.exports = class Minipass extends Stream { constructor (options) { super() this[FLOWING] = false // whether we're explicitly paused this[PAUSED] = false this.pipes = new Yallist() this.buffer = new Yallist() this[OBJECTMODE] = options && options.objectMode || false if (this[OBJECTMODE]) this[ENCODING] = null else this[ENCODING] = options && options.encoding || null if (this[ENCODING] === 'buffer') this[ENCODING] = null this[DECODER] = this[ENCODING] ? new SD(this[ENCODING]) : null this[EOF] = false this[EMITTED_END] = false this[EMITTING_END] = false this[CLOSED] = false this[EMITTED_ERROR] = null this.writable = true this.readable = true this[BUFFERLENGTH] = 0 this[DESTROYED] = false } get bufferLength () { return this[BUFFERLENGTH] } get encoding () { return this[ENCODING] } set encoding (enc) { if (this[OBJECTMODE]) throw new Error('cannot set encoding in objectMode') if (this[ENCODING] && enc !== this[ENCODING] && (this[DECODER] && this[DECODER].lastNeed || this[BUFFERLENGTH])) throw new Error('cannot change encoding') if (this[ENCODING] !== enc) { this[DECODER] = enc ? new SD(enc) : null if (this.buffer.length) this.buffer = this.buffer.map(chunk => this[DECODER].write(chunk)) } this[ENCODING] = enc } setEncoding (enc) { this.encoding = enc } get objectMode () { return this[OBJECTMODE] } set objectMode (om) { this[OBJECTMODE] = this[OBJECTMODE] || !!om } write (chunk, encoding, cb) { if (this[EOF]) throw new Error('write after end') if (this[DESTROYED]) { this.emit('error', Object.assign( new Error('Cannot call write after a stream was destroyed'), { code: 'ERR_STREAM_DESTROYED' } )) return true } if (typeof encoding === 'function') cb = encoding, encoding = 'utf8' if (!encoding) encoding = 'utf8' // convert array buffers and typed array views into buffers // at some point in the future, we may want to do the opposite! // leave strings and buffers as-is // anything else switches us into object mode if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) { if (isArrayBufferView(chunk)) chunk = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength) else if (isArrayBuffer(chunk)) chunk = Buffer.from(chunk) else if (typeof chunk !== 'string') // use the setter so we throw if we have encoding set this.objectMode = true } // this ensures at this point that the chunk is a buffer or string // don't buffer it up or send it to the decoder if (!this.objectMode && !chunk.length) { if (this[BUFFERLENGTH] !== 0) this.emit('readable') if (cb) cb() return this.flowing } // fast-path writing strings of same encoding to a stream with // an empty buffer, skipping the buffer/decoder dance if (typeof chunk === 'string' && !this[OBJECTMODE] && // unless it is a string already ready for us to use !(encoding === this[ENCODING] && !this[DECODER].lastNeed)) { chunk = Buffer.from(chunk, encoding) } if (Buffer.isBuffer(chunk) && this[ENCODING]) chunk = this[DECODER].write(chunk) if (this.flowing) { // if we somehow have something in the buffer, but we think we're // flowing, then we need to flush all that out first, or we get // chunks coming in out of order. Can't emit 'drain' here though, // because we're mid-write, so that'd be bad. if (this[BUFFERLENGTH] !== 0) this[FLUSH](true) this.emit('data', chunk) } else this[BUFFERPUSH](chunk) if (this[BUFFERLENGTH] !== 0) this.emit('readable') if (cb) cb() return this.flowing } read (n) { if (this[DESTROYED]) return null try { if (this[BUFFERLENGTH] === 0 || n === 0 || n > this[BUFFERLENGTH]) return null if (this[OBJECTMODE]) n = null if (this.buffer.length > 1 && !this[OBJECTMODE]) { if (this.encoding) this.buffer = new Yallist([ Array.from(this.buffer).join('') ]) else this.buffer = new Yallist([ Buffer.concat(Array.from(this.buffer), this[BUFFERLENGTH]) ]) } return this[READ](n || null, this.buffer.head.value) } finally { this[MAYBE_EMIT_END]() } } [READ] (n, chunk) { if (n === chunk.length || n === null) this[BUFFERSHIFT]() else { this.buffer.head.value = chunk.slice(n) chunk = chunk.slice(0, n) this[BUFFERLENGTH] -= n } this.emit('data', chunk) if (!this.buffer.length && !this[EOF]) this.emit('drain') return chunk } end (chunk, encoding, cb) { if (typeof chunk === 'function') cb = chunk, chunk = null if (typeof encoding === 'function') cb = encoding, encoding = 'utf8' if (chunk) this.write(chunk, encoding) if (cb) this.once('end', cb) this[EOF] = true this.writable = false // if we haven't written anything, then go ahead and emit, // even if we're not reading. // we'll re-emit if a new 'end' listener is added anyway. // This makes MP more suitable to write-only use cases. if (this.flowing || !this[PAUSED]) this[MAYBE_EMIT_END]() return this } // don't let the internal resume be overwritten [RESUME] () { if (this[DESTROYED]) return this[PAUSED] = false this[FLOWING] = true this.emit('resume') if (this.buffer.length) this[FLUSH]() else if (this[EOF]) this[MAYBE_EMIT_END]() else this.emit('drain') } resume () { return this[RESUME]() } pause () { this[FLOWING] = false this[PAUSED] = true } get destroyed () { return this[DESTROYED] } get flowing () { return this[FLOWING] } get paused () { return this[PAUSED] } [BUFFERPUSH] (chunk) { if (this[OBJECTMODE]) this[BUFFERLENGTH] += 1 else this[BUFFERLENGTH] += chunk.length return this.buffer.push(chunk) } [BUFFERSHIFT] () { if (this.buffer.length) { if (this[OBJECTMODE]) this[BUFFERLENGTH] -= 1 else this[BUFFERLENGTH] -= this.buffer.head.value.length } return this.buffer.shift() } [FLUSH] (noDrain) { do {} while (this[FLUSHCHUNK](this[BUFFERSHIFT]())) if (!noDrain && !this.buffer.length && !this[EOF]) this.emit('drain') } [FLUSHCHUNK] (chunk) { return chunk ? (this.emit('data', chunk), this.flowing) : false } pipe (dest, opts) { if (this[DESTROYED]) return const ended = this[EMITTED_END] opts = opts || {} if (dest === proc.stdout || dest === proc.stderr) opts.end = false else opts.end = opts.end !== false const p = { dest: dest, opts: opts, ondrain: _ => this[RESUME]() } this.pipes.push(p) dest.on('drain', p.ondrain) this[RESUME]() // piping an ended stream ends immediately if (ended && p.opts.end) p.dest.end() return dest } addListener (ev, fn) { return this.on(ev, fn) } on (ev, fn) { try { return super.on(ev, fn) } finally { if (ev === 'data' && !this.pipes.length && !this.flowing) this[RESUME]() else if (isEndish(ev) && this[EMITTED_END]) { super.emit(ev) this.removeAllListeners(ev) } else if (ev === 'error' && this[EMITTED_ERROR]) { fn.call(this, this[EMITTED_ERROR]) } } } get emittedEnd () { return this[EMITTED_END] } [MAYBE_EMIT_END] () { if (!this[EMITTING_END] && !this[EMITTED_END] && !this[DESTROYED] && this.buffer.length === 0 && this[EOF]) { this[EMITTING_END] = true this.emit('end') this.emit('prefinish') this.emit('finish') if (this[CLOSED]) this.emit('close') this[EMITTING_END] = false } } emit (ev, data) { // error and close are only events allowed after calling destroy() if (ev !== 'error' && ev !== 'close' && ev !== DESTROYED && this[DESTROYED]) return else if (ev === 'data') { if (!data) return if (this.pipes.length) this.pipes.forEach(p => p.dest.write(data) === false && this.pause()) } else if (ev === 'end') { // only actual end gets this treatment if (this[EMITTED_END] === true) return this[EMITTED_END] = true this.readable = false if (this[DECODER]) { data = this[DECODER].end() if (data) { this.pipes.forEach(p => p.dest.write(data)) super.emit('data', data) } } this.pipes.forEach(p => { p.dest.removeListener('drain', p.ondrain) if (p.opts.end) p.dest.end() }) } else if (ev === 'close') { this[CLOSED] = true // don't emit close before 'end' and 'finish' if (!this[EMITTED_END] && !this[DESTROYED]) return } else if (ev === 'error') { this[EMITTED_ERROR] = data } // TODO: replace with a spread operator when Node v4 support drops const args = new Array(arguments.length) args[0] = ev args[1] = data if (arguments.length > 2) { for (let i = 2; i < arguments.length; i++) { args[i] = arguments[i] } } try { return super.emit.apply(this, args) } finally { if (!isEndish(ev)) this[MAYBE_EMIT_END]() else this.removeAllListeners(ev) } } // const all = await stream.collect() collect () { const buf = [] if (!this[OBJECTMODE]) buf.dataLength = 0 // set the promise first, in case an error is raised // by triggering the flow here. const p = this.promise() this.on('data', c => { buf.push(c) if (!this[OBJECTMODE]) buf.dataLength += c.length }) return p.then(() => buf) } // const data = await stream.concat() concat () { return this[OBJECTMODE] ? Promise.reject(new Error('cannot concat in objectMode')) : this.collect().then(buf => this[OBJECTMODE] ? Promise.reject(new Error('cannot concat in objectMode')) : this[ENCODING] ? buf.join('') : Buffer.concat(buf, buf.dataLength)) } // stream.promise().then(() => done, er => emitted error) promise () { return new Promise((resolve, reject) => { this.on(DESTROYED, () => reject(new Error('stream destroyed'))) this.on('error', er => reject(er)) this.on('end', () => resolve()) }) } // for await (let chunk of stream) [ASYNCITERATOR] () { const next = () => { const res = this.read() if (res !== null) return Promise.resolve({ done: false, value: res }) if (this[EOF]) return Promise.resolve({ done: true }) let resolve = null let reject = null const onerr = er => { this.removeListener('data', ondata) this.removeListener('end', onend) reject(er) } const ondata = value => { this.removeListener('error', onerr) this.removeListener('end', onend) this.pause() resolve({ value: value, done: !!this[EOF] }) } const onend = () => { this.removeListener('error', onerr) this.removeListener('data', ondata) resolve({ done: true }) } const ondestroy = () => onerr(new Error('stream destroyed')) return new Promise((res, rej) => { reject = rej resolve = res this.once(DESTROYED, ondestroy) this.once('error', onerr) this.once('end', onend) this.once('data', ondata) }) } return { next } } // for (let chunk of stream) [ITERATOR] () { const next = () => { const value = this.read() const done = value === null return { value, done } } return { next } } destroy (er) { if (this[DESTROYED]) { if (er) this.emit('error', er) else this.emit(DESTROYED) return this } this[DESTROYED] = true // throw away all buffered data, it's never coming out this.buffer = new Yallist() this[BUFFERLENGTH] = 0 if (typeof this.close === 'function' && !this[CLOSED]) this.close() if (er) this.emit('error', er) else // if no error to emit, still reject pending promises this.emit(DESTROYED) return this } static isStream (s) { return !!s && (s instanceof Minipass || s instanceof Stream || s instanceof EE && ( typeof s.pipe === 'function' || // readable (typeof s.write === 'function' && typeof s.end === 'function') // writable )) } } /***/ }), /***/ 883: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // Update with any zlib constants that are added or changed in the future. // Node v6 didn't export this, so we just hard code the version and rely // on all the other hard-coded values from zlib v4736. When node v6 // support drops, we can just export the realZlibConstants object. const realZlibConstants = (__webpack_require__(9796).constants) || /* istanbul ignore next */ { ZLIB_VERNUM: 4736 } module.exports = Object.freeze(Object.assign(Object.create(null), { Z_NO_FLUSH: 0, Z_PARTIAL_FLUSH: 1, Z_SYNC_FLUSH: 2, Z_FULL_FLUSH: 3, Z_FINISH: 4, Z_BLOCK: 5, Z_OK: 0, Z_STREAM_END: 1, Z_NEED_DICT: 2, Z_ERRNO: -1, Z_STREAM_ERROR: -2, Z_DATA_ERROR: -3, Z_MEM_ERROR: -4, Z_BUF_ERROR: -5, Z_VERSION_ERROR: -6, Z_NO_COMPRESSION: 0, Z_BEST_SPEED: 1, Z_BEST_COMPRESSION: 9, Z_DEFAULT_COMPRESSION: -1, Z_FILTERED: 1, Z_HUFFMAN_ONLY: 2, Z_RLE: 3, Z_FIXED: 4, Z_DEFAULT_STRATEGY: 0, DEFLATE: 1, INFLATE: 2, GZIP: 3, GUNZIP: 4, DEFLATERAW: 5, INFLATERAW: 6, UNZIP: 7, BROTLI_DECODE: 8, BROTLI_ENCODE: 9, Z_MIN_WINDOWBITS: 8, Z_MAX_WINDOWBITS: 15, Z_DEFAULT_WINDOWBITS: 15, Z_MIN_CHUNK: 64, Z_MAX_CHUNK: Infinity, Z_DEFAULT_CHUNK: 16384, Z_MIN_MEMLEVEL: 1, Z_MAX_MEMLEVEL: 9, Z_DEFAULT_MEMLEVEL: 8, Z_MIN_LEVEL: -1, Z_MAX_LEVEL: 9, Z_DEFAULT_LEVEL: -1, BROTLI_OPERATION_PROCESS: 0, BROTLI_OPERATION_FLUSH: 1, BROTLI_OPERATION_FINISH: 2, BROTLI_OPERATION_EMIT_METADATA: 3, BROTLI_MODE_GENERIC: 0, BROTLI_MODE_TEXT: 1, BROTLI_MODE_FONT: 2, BROTLI_DEFAULT_MODE: 0, BROTLI_MIN_QUALITY: 0, BROTLI_MAX_QUALITY: 11, BROTLI_DEFAULT_QUALITY: 11, BROTLI_MIN_WINDOW_BITS: 10, BROTLI_MAX_WINDOW_BITS: 24, BROTLI_LARGE_MAX_WINDOW_BITS: 30, BROTLI_DEFAULT_WINDOW: 22, BROTLI_MIN_INPUT_BLOCK_BITS: 16, BROTLI_MAX_INPUT_BLOCK_BITS: 24, BROTLI_PARAM_MODE: 0, BROTLI_PARAM_QUALITY: 1, BROTLI_PARAM_LGWIN: 2, BROTLI_PARAM_LGBLOCK: 3, BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING: 4, BROTLI_PARAM_SIZE_HINT: 5, BROTLI_PARAM_LARGE_WINDOW: 6, BROTLI_PARAM_NPOSTFIX: 7, BROTLI_PARAM_NDIRECT: 8, BROTLI_DECODER_RESULT_ERROR: 0, BROTLI_DECODER_RESULT_SUCCESS: 1, BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT: 2, BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT: 3, BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION: 0, BROTLI_DECODER_PARAM_LARGE_WINDOW: 1, BROTLI_DECODER_NO_ERROR: 0, BROTLI_DECODER_SUCCESS: 1, BROTLI_DECODER_NEEDS_MORE_INPUT: 2, BROTLI_DECODER_NEEDS_MORE_OUTPUT: 3, BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE: -1, BROTLI_DECODER_ERROR_FORMAT_RESERVED: -2, BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE: -3, BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET: -4, BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME: -5, BROTLI_DECODER_ERROR_FORMAT_CL_SPACE: -6, BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE: -7, BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT: -8, BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1: -9, BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2: -10, BROTLI_DECODER_ERROR_FORMAT_TRANSFORM: -11, BROTLI_DECODER_ERROR_FORMAT_DICTIONARY: -12, BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS: -13, BROTLI_DECODER_ERROR_FORMAT_PADDING_1: -14, BROTLI_DECODER_ERROR_FORMAT_PADDING_2: -15, BROTLI_DECODER_ERROR_FORMAT_DISTANCE: -16, BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET: -19, BROTLI_DECODER_ERROR_INVALID_ARGUMENTS: -20, BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES: -21, BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS: -22, BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP: -25, BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1: -26, BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2: -27, BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES: -30, BROTLI_DECODER_ERROR_UNREACHABLE: -31, }, realZlibConstants)) /***/ }), /***/ 1650: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; const assert = __webpack_require__(9491) const Buffer = (__webpack_require__(4300).Buffer) const realZlib = __webpack_require__(9796) const constants = exports.constants = __webpack_require__(883) const Minipass = __webpack_require__(5736) const OriginalBufferConcat = Buffer.concat const _superWrite = Symbol('_superWrite') class ZlibError extends Error { constructor (err) { super('zlib: ' + err.message) this.code = err.code this.errno = err.errno /* istanbul ignore if */ if (!this.code) this.code = 'ZLIB_ERROR' this.message = 'zlib: ' + err.message Error.captureStackTrace(this, this.constructor) } get name () { return 'ZlibError' } } // the Zlib class they all inherit from // This thing manages the queue of requests, and returns // true or false if there is anything in the queue when // you call the .write() method. const _opts = Symbol('opts') const _flushFlag = Symbol('flushFlag') const _finishFlushFlag = Symbol('finishFlushFlag') const _fullFlushFlag = Symbol('fullFlushFlag') const _handle = Symbol('handle') const _onError = Symbol('onError') const _sawError = Symbol('sawError') const _level = Symbol('level') const _strategy = Symbol('strategy') const _ended = Symbol('ended') const _defaultFullFlush = Symbol('_defaultFullFlush') class ZlibBase extends Minipass { constructor (opts, mode) { if (!opts || typeof opts !== 'object') throw new TypeError('invalid options for ZlibBase constructor') super(opts) this[_sawError] = false this[_ended] = false this[_opts] = opts this[_flushFlag] = opts.flush this[_finishFlushFlag] = opts.finishFlush // this will throw if any options are invalid for the class selected try { this[_handle] = new realZlib[mode](opts) } catch (er) { // make sure that all errors get decorated properly throw new ZlibError(er) } this[_onError] = (err) => { // no sense raising multiple errors, since we abort on the first one. if (this[_sawError]) return this[_sawError] = true // there is no way to cleanly recover. // continuing only obscures problems. this.close() this.emit('error', err) } this[_handle].on('error', er => this[_onError](new ZlibError(er))) this.once('end', () => this.close) } close () { if (this[_handle]) { this[_handle].close() this[_handle] = null this.emit('close') } } reset () { if (!this[_sawError]) { assert(this[_handle], 'zlib binding closed') return this[_handle].reset() } } flush (flushFlag) { if (this.ended) return if (typeof flushFlag !== 'number') flushFlag = this[_fullFlushFlag] this.write(Object.assign(Buffer.alloc(0), { [_flushFlag]: flushFlag })) } end (chunk, encoding, cb) { if (chunk) this.write(chunk, encoding) this.flush(this[_finishFlushFlag]) this[_ended] = true return super.end(null, null, cb) } get ended () { return this[_ended] } write (chunk, encoding, cb) { // process the chunk using the sync process // then super.write() all the outputted chunks if (typeof encoding === 'function') cb = encoding, encoding = 'utf8' if (typeof chunk === 'string') chunk = Buffer.from(chunk, encoding) if (this[_sawError]) return assert(this[_handle], 'zlib binding closed') // _processChunk tries to .close() the native handle after it's done, so we // intercept that by temporarily making it a no-op. const nativeHandle = this[_handle]._handle const originalNativeClose = nativeHandle.close nativeHandle.close = () => {} const originalClose = this[_handle].close this[_handle].close = () => {} // It also calls `Buffer.concat()` at the end, which may be convenient // for some, but which we are not interested in as it slows us down. Buffer.concat = (args) => args let result try { const flushFlag = typeof chunk[_flushFlag] === 'number' ? chunk[_flushFlag] : this[_flushFlag] result = this[_handle]._processChunk(chunk, flushFlag) // if we don't throw, reset it back how it was Buffer.concat = OriginalBufferConcat } catch (err) { // or if we do, put Buffer.concat() back before we emit error // Error events call into user code, which may call Buffer.concat() Buffer.concat = OriginalBufferConcat this[_onError](new ZlibError(err)) } finally { if (this[_handle]) { // Core zlib resets `_handle` to null after attempting to close the // native handle. Our no-op handler prevented actual closure, but we // need to restore the `._handle` property. this[_handle]._handle = nativeHandle nativeHandle.close = originalNativeClose this[_handle].close = originalClose // `_processChunk()` adds an 'error' listener. If we don't remove it // after each call, these handlers start piling up. this[_handle].removeAllListeners('error') // make sure OUR error listener is still attached tho } } if (this[_handle]) this[_handle].on('error', er => this[_onError](new ZlibError(er))) let writeReturn if (result) { if (Array.isArray(result) && result.length > 0) { // The first buffer is always `handle._outBuffer`, which would be // re-used for later invocations; so, we always have to copy that one. writeReturn = this[_superWrite](Buffer.from(result[0])) for (let i = 1; i < result.length; i++) { writeReturn = this[_superWrite](result[i]) } } else { writeReturn = this[_superWrite](Buffer.from(result)) } } if (cb) cb() return writeReturn } [_superWrite] (data) { return super.write(data) } } class Zlib extends ZlibBase { constructor (opts, mode) { opts = opts || {} opts.flush = opts.flush || constants.Z_NO_FLUSH opts.finishFlush = opts.finishFlush || constants.Z_FINISH super(opts, mode) this[_fullFlushFlag] = constants.Z_FULL_FLUSH this[_level] = opts.level this[_strategy] = opts.strategy } params (level, strategy) { if (this[_sawError]) return if (!this[_handle]) throw new Error('cannot switch params when binding is closed') // no way to test this without also not supporting params at all /* istanbul ignore if */ if (!this[_handle].params) throw new Error('not supported in this implementation') if (this[_level] !== level || this[_strategy] !== strategy) { this.flush(constants.Z_SYNC_FLUSH) assert(this[_handle], 'zlib binding closed') // .params() calls .flush(), but the latter is always async in the // core zlib. We override .flush() temporarily to intercept that and // flush synchronously. const origFlush = this[_handle].flush this[_handle].flush = (flushFlag, cb) => { this.flush(flushFlag) cb() } try { this[_handle].params(level, strategy) } finally { this[_handle].flush = origFlush } /* istanbul ignore else */ if (this[_handle]) { this[_level] = level this[_strategy] = strategy } } } } // minimal 2-byte header class Deflate extends Zlib { constructor (opts) { super(opts, 'Deflate') } } class Inflate extends Zlib { constructor (opts) { super(opts, 'Inflate') } } // gzip - bigger header, same deflate compression const _portable = Symbol('_portable') class Gzip extends Zlib { constructor (opts) { super(opts, 'Gzip') this[_portable] = opts && !!opts.portable } [_superWrite] (data) { if (!this[_portable]) return super[_superWrite](data) // we'll always get the header emitted in one first chunk // overwrite the OS indicator byte with 0xFF this[_portable] = false data[9] = 255 return super[_superWrite](data) } } class Gunzip extends Zlib { constructor (opts) { super(opts, 'Gunzip') } } // raw - no header class DeflateRaw extends Zlib { constructor (opts) { super(opts, 'DeflateRaw') } } class InflateRaw extends Zlib { constructor (opts) { super(opts, 'InflateRaw') } } // auto-detect header. class Unzip extends Zlib { constructor (opts) { super(opts, 'Unzip') } } class Brotli extends ZlibBase { constructor (opts, mode) { opts = opts || {} opts.flush = opts.flush || constants.BROTLI_OPERATION_PROCESS opts.finishFlush = opts.finishFlush || constants.BROTLI_OPERATION_FINISH super(opts, mode) this[_fullFlushFlag] = constants.BROTLI_OPERATION_FLUSH } } class BrotliCompress extends Brotli { constructor (opts) { super(opts, 'BrotliCompress') } } class BrotliDecompress extends Brotli { constructor (opts) { super(opts, 'BrotliDecompress') } } exports.Deflate = Deflate exports.Inflate = Inflate exports.Gzip = Gzip exports.Gunzip = Gunzip exports.DeflateRaw = DeflateRaw exports.InflateRaw = InflateRaw exports.Unzip = Unzip /* istanbul ignore else */ if (typeof realZlib.BrotliCompress === 'function') { exports.BrotliCompress = BrotliCompress exports.BrotliDecompress = BrotliDecompress } else { exports.BrotliCompress = exports.BrotliDecompress = class { constructor () { throw new Error('Brotli is not supported in this version of Node.js') } } } /***/ }), /***/ 1890: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const optsArg = __webpack_require__(4231) const pathArg = __webpack_require__(3610) const {mkdirpNative, mkdirpNativeSync} = __webpack_require__(9378) const {mkdirpManual, mkdirpManualSync} = __webpack_require__(8600) const {useNative, useNativeSync} = __webpack_require__(6167) const mkdirp = (path, opts) => { path = pathArg(path) opts = optsArg(opts) return useNative(opts) ? mkdirpNative(path, opts) : mkdirpManual(path, opts) } const mkdirpSync = (path, opts) => { path = pathArg(path) opts = optsArg(opts) return useNativeSync(opts) ? mkdirpNativeSync(path, opts) : mkdirpManualSync(path, opts) } mkdirp.sync = mkdirpSync mkdirp.native = (path, opts) => mkdirpNative(pathArg(path), optsArg(opts)) mkdirp.manual = (path, opts) => mkdirpManual(pathArg(path), optsArg(opts)) mkdirp.nativeSync = (path, opts) => mkdirpNativeSync(pathArg(path), optsArg(opts)) mkdirp.manualSync = (path, opts) => mkdirpManualSync(pathArg(path), optsArg(opts)) module.exports = mkdirp /***/ }), /***/ 8812: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const {dirname} = __webpack_require__(1017) const findMade = (opts, parent, path = undefined) => { // we never want the 'made' return value to be a root directory if (path === parent) return Promise.resolve() return opts.statAsync(parent).then( st => st.isDirectory() ? path : undefined, // will fail later er => er.code === 'ENOENT' ? findMade(opts, dirname(parent), parent) : undefined ) } const findMadeSync = (opts, parent, path = undefined) => { if (path === parent) return undefined try { return opts.statSync(parent).isDirectory() ? path : undefined } catch (er) { return er.code === 'ENOENT' ? findMadeSync(opts, dirname(parent), parent) : undefined } } module.exports = {findMade, findMadeSync} /***/ }), /***/ 8600: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const {dirname} = __webpack_require__(1017) const mkdirpManual = (path, opts, made) => { opts.recursive = false const parent = dirname(path) if (parent === path) { return opts.mkdirAsync(path, opts).catch(er => { // swallowed by recursive implementation on posix systems // any other error is a failure if (er.code !== 'EISDIR') throw er }) } return opts.mkdirAsync(path, opts).then(() => made || path, er => { if (er.code === 'ENOENT') return mkdirpManual(parent, opts) .then(made => mkdirpManual(path, opts, made)) if (er.code !== 'EEXIST' && er.code !== 'EROFS') throw er return opts.statAsync(path).then(st => { if (st.isDirectory()) return made else throw er }, () => { throw er }) }) } const mkdirpManualSync = (path, opts, made) => { const parent = dirname(path) opts.recursive = false if (parent === path) { try { return opts.mkdirSync(path, opts) } catch (er) { // swallowed by recursive implementation on posix systems // any other error is a failure if (er.code !== 'EISDIR') throw er else return } } try { opts.mkdirSync(path, opts) return made || path } catch (er) { if (er.code === 'ENOENT') return mkdirpManualSync(path, opts, mkdirpManualSync(parent, opts, made)) if (er.code !== 'EEXIST' && er.code !== 'EROFS') throw er try { if (!opts.statSync(path).isDirectory()) throw er } catch (_) { throw er } } } module.exports = {mkdirpManual, mkdirpManualSync} /***/ }), /***/ 9378: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const {dirname} = __webpack_require__(1017) const {findMade, findMadeSync} = __webpack_require__(8812) const {mkdirpManual, mkdirpManualSync} = __webpack_require__(8600) const mkdirpNative = (path, opts) => { opts.recursive = true const parent = dirname(path) if (parent === path) return opts.mkdirAsync(path, opts) return findMade(opts, path).then(made => opts.mkdirAsync(path, opts).then(() => made) .catch(er => { if (er.code === 'ENOENT') return mkdirpManual(path, opts) else throw er })) } const mkdirpNativeSync = (path, opts) => { opts.recursive = true const parent = dirname(path) if (parent === path) return opts.mkdirSync(path, opts) const made = findMadeSync(opts, path) try { opts.mkdirSync(path, opts) return made } catch (er) { if (er.code === 'ENOENT') return mkdirpManualSync(path, opts) else throw er } } module.exports = {mkdirpNative, mkdirpNativeSync} /***/ }), /***/ 4231: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const { promisify } = __webpack_require__(3837) const fs = __webpack_require__(7147) const optsArg = opts => { if (!opts) opts = { mode: 0o777, fs } else if (typeof opts === 'object') opts = { mode: 0o777, fs, ...opts } else if (typeof opts === 'number') opts = { mode: opts, fs } else if (typeof opts === 'string') opts = { mode: parseInt(opts, 8), fs } else throw new TypeError('invalid options argument') opts.mkdir = opts.mkdir || opts.fs.mkdir || fs.mkdir opts.mkdirAsync = promisify(opts.mkdir) opts.stat = opts.stat || opts.fs.stat || fs.stat opts.statAsync = promisify(opts.stat) opts.statSync = opts.statSync || opts.fs.statSync || fs.statSync opts.mkdirSync = opts.mkdirSync || opts.fs.mkdirSync || fs.mkdirSync return opts } module.exports = optsArg /***/ }), /***/ 3610: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const platform = process.env.__TESTING_MKDIRP_PLATFORM__ || process.platform const { resolve, parse } = __webpack_require__(1017) const pathArg = path => { if (/\0/.test(path)) { // simulate same failure that node raises throw Object.assign( new TypeError('path must be a string without null bytes'), { path, code: 'ERR_INVALID_ARG_VALUE', } ) } path = resolve(path) if (platform === 'win32') { const badWinChars = /[*|"<>?:]/ const {root} = parse(path) if (badWinChars.test(path.substr(root.length))) { throw Object.assign(new Error('Illegal characters in path.'), { path, code: 'EINVAL', }) } } return path } module.exports = pathArg /***/ }), /***/ 6167: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const fs = __webpack_require__(7147) const version = process.env.__TESTING_MKDIRP_NODE_VERSION__ || process.version const versArr = version.replace(/^v/, '').split('.') const hasNative = +versArr[0] > 10 || +versArr[0] === 10 && +versArr[1] >= 12 const useNative = !hasNative ? () => false : opts => opts.mkdir === fs.mkdir const useNativeSync = !hasNative ? () => false : opts => opts.mkdirSync === fs.mkdirSync module.exports = {useNative, useNativeSync} /***/ }), /***/ 7824: /***/ ((module) => { /** * Helpers. */ 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 */ module.exports = 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' : ''); } /***/ }), /***/ 778: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var wrappy = __webpack_require__(2479) module.exports = wrappy(once) module.exports.strict = wrappy(onceStrict) once.proto = once(function () { Object.defineProperty(Function.prototype, 'once', { value: function () { return once(this) }, configurable: true }) Object.defineProperty(Function.prototype, 'onceStrict', { value: function () { return onceStrict(this) }, configurable: true }) }) function once (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 } /***/ }), /***/ 9916: /***/ ((module) => { module.exports = Pend; function Pend() { this.pending = 0; this.max = Infinity; this.listeners = []; this.waiting = []; this.error = null; } Pend.prototype.go = function(fn) { if (this.pending < this.max) { pendGo(this, fn); } else { this.waiting.push(fn); } }; Pend.prototype.wait = function(cb) { if (this.pending === 0) { cb(this.error); } else { this.listeners.push(cb); } }; Pend.prototype.hold = function() { return pendHold(this); }; function pendHold(self) { self.pending += 1; var called = false; return onCb; function onCb(err) { if (called) throw new Error("callback called twice"); called = true; self.error = self.error || err; self.pending -= 1; if (self.waiting.length > 0 && self.pending < self.max) { pendGo(self, self.waiting.shift()); } else if (self.pending === 0) { var listeners = self.listeners; self.listeners = []; listeners.forEach(cbListener); } } function cbListener(listener) { listener(self.error); } } function pendGo(self, fn) { fn(pendHold(self)); } /***/ }), /***/ 4286: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var once = __webpack_require__(778) var eos = __webpack_require__(2840) var fs = __webpack_require__(7147) // we only need fs to get the ReadStream and WriteStream prototypes var noop = function () {} var ancient = /^v?\.0/.test(process.version) var isFn = function (fn) { return typeof fn === 'function' } var isFS = function (stream) { if (!ancient) return false // newer node version do not need to care about fs is a special way if (!fs) return false // browser return (stream instanceof (fs.ReadStream || noop) || stream instanceof (fs.WriteStream || noop)) && isFn(stream.close) } var isRequest = function (stream) { return stream.setHeader && isFn(stream.abort) } var destroyer = function (stream, reading, writing, callback) { callback = once(callback) var closed = false stream.on('close', function () { closed = true }) 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 if (isFS(stream)) return stream.close(noop) // use close for fs streams to avoid fd leaks if (isRequest(stream)) return stream.abort() // request.destroy just do .end - .abort is what we want if (isFn(stream.destroy)) return stream.destroy() callback(err || new Error('stream was destroyed')) } } var call = function (fn) { fn() } var pipe = function (from, to) { return from.pipe(to) } var pump = function () { var streams = Array.prototype.slice.call(arguments) var callback = isFn(streams[streams.length - 1] || noop) && streams.pop() || noop if (Array.isArray(streams[0])) streams = streams[0] if (streams.length < 2) throw new Error('pump requires two streams per minimum') var error var destroys = streams.map(function (stream, i) { var reading = i < streams.length - 1 var writing = i > 0 return destroyer(stream, reading, writing, function (err) { if (!error) error = err if (err) destroys.forEach(call) if (reading) return destroys.forEach(call) callback(error) }) }) return streams.reduce(pipe) } module.exports = pump /***/ }), /***/ 2257: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const ANY = Symbol('SemVer ANY') // hoisted class for cyclic dependency class Comparator { static get ANY () { return ANY } constructor (comp, options) { options = parseOptions(options) if (comp instanceof Comparator) { if (comp.loose === !!options.loose) { return comp } else { comp = comp.value } } debug('comparator', comp, options) this.options = options this.loose = !!options.loose this.parse(comp) if (this.semver === ANY) { this.value = '' } else { this.value = this.operator + this.semver.version } debug('comp', this) } parse (comp) { const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] const m = comp.match(r) if (!m) { throw new TypeError(`Invalid comparator: ${comp}`) } this.operator = m[1] !== undefined ? m[1] : '' if (this.operator === '=') { this.operator = '' } // if it literally is just '>' or '' then allow anything. if (!m[2]) { this.semver = ANY } else { this.semver = new SemVer(m[2], this.options.loose) } } toString () { return this.value } test (version) { debug('Comparator.test', version, this.options.loose) if (this.semver === ANY || version === ANY) { return true } if (typeof version === 'string') { try { version = new SemVer(version, this.options) } catch (er) { return false } } return cmp(version, this.operator, this.semver, this.options) } intersects (comp, options) { if (!(comp instanceof Comparator)) { throw new TypeError('a Comparator is required') } if (!options || typeof options !== 'object') { options = { loose: !!options, includePrerelease: false } } if (this.operator === '') { if (this.value === '') { return true } return new Range(comp.value, options).test(this.value) } else if (comp.operator === '') { if (comp.value === '') { return true } return new Range(this.value, options).test(comp.semver) } const sameDirectionIncreasing = (this.operator === '>=' || this.operator === '>') && (comp.operator === '>=' || comp.operator === '>') const sameDirectionDecreasing = (this.operator === '<=' || this.operator === '<') && (comp.operator === '<=' || comp.operator === '<') const sameSemVer = this.semver.version === comp.semver.version const differentDirectionsInclusive = (this.operator === '>=' || this.operator === '<=') && (comp.operator === '>=' || comp.operator === '<=') const oppositeDirectionsLessThan = cmp(this.semver, '<', comp.semver, options) && (this.operator === '>=' || this.operator === '>') && (comp.operator === '<=' || comp.operator === '<') const oppositeDirectionsGreaterThan = cmp(this.semver, '>', comp.semver, options) && (this.operator === '<=' || this.operator === '<') && (comp.operator === '>=' || comp.operator === '>') return ( sameDirectionIncreasing || sameDirectionDecreasing || (sameSemVer && differentDirectionsInclusive) || oppositeDirectionsLessThan || oppositeDirectionsGreaterThan ) } } module.exports = Comparator const parseOptions = __webpack_require__(2893) const {re, t} = __webpack_require__(5765) const cmp = __webpack_require__(7539) const debug = __webpack_require__(4225) const SemVer = __webpack_require__(6376) const Range = __webpack_require__(6902) /***/ }), /***/ 6902: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // hoisted class for cyclic dependency class Range { constructor (range, options) { options = parseOptions(options) if (range instanceof Range) { if ( range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease ) { return range } else { return new Range(range.raw, options) } } if (range instanceof Comparator) { // just put it in the set and return this.raw = range.value this.set = [[range]] this.format() return this } this.options = options this.loose = !!options.loose this.includePrerelease = !!options.includePrerelease // First, split based on boolean or || this.raw = range this.set = range .split(/\s*\|\|\s*/) // map the range to a 2d array of comparators .map(range => this.parseRange(range.trim())) // throw out any comparator lists that are empty // this generally means that it was not a valid range, which is allowed // in loose mode, but will still throw if the WHOLE range is invalid. .filter(c => c.length) if (!this.set.length) { throw new TypeError(`Invalid SemVer Range: ${range}`) } // if we have any that are not the null set, throw out null sets. if (this.set.length > 1) { // keep the first one, in case they're all null sets const first = this.set[0] this.set = this.set.filter(c => !isNullSet(c[0])) if (this.set.length === 0) this.set = [first] else if (this.set.length > 1) { // if we have any that are *, then the range is just * for (const c of this.set) { if (c.length === 1 && isAny(c[0])) { this.set = [c] break } } } } this.format() } format () { this.range = this.set .map((comps) => { return comps.join(' ').trim() }) .join('||') .trim() return this.range } toString () { return this.range } parseRange (range) { range = range.trim() // memoize range parsing for performance. // this is a very hot path, and fully deterministic. const memoOpts = Object.keys(this.options).join(',') const memoKey = `parseRange:${memoOpts}:${range}` const cached = cache.get(memoKey) if (cached) return cached const loose = this.options.loose // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE] range = range.replace(hr, hyphenReplace(this.options.includePrerelease)) debug('hyphen replace', range) // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace) debug('comparator trim', range, re[t.COMPARATORTRIM]) // `~ 1.2.3` => `~1.2.3` range = range.replace(re[t.TILDETRIM], tildeTrimReplace) // `^ 1.2.3` => `^1.2.3` range = range.replace(re[t.CARETTRIM], caretTrimReplace) // normalize spaces range = range.split(/\s+/).join(' ') // At this point, the range is completely trimmed and // ready to be split into comparators. const compRe = loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] const rangeList = range .split(' ') .map(comp => parseComparator(comp, this.options)) .join(' ') .split(/\s+/) // >=0.0.0 is equivalent to * .map(comp => replaceGTE0(comp, this.options)) // in loose mode, throw out any that are not valid comparators .filter(this.options.loose ? comp => !!comp.match(compRe) : () => true) .map(comp => new Comparator(comp, this.options)) // 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 l = rangeList.length const rangeMap = new Map() for (const comp of rangeList) { 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 } } module.exports = Range const LRU = __webpack_require__(9593) const cache = new LRU({ max: 1000 }) const parseOptions = __webpack_require__(2893) const Comparator = __webpack_require__(2257) const debug = __webpack_require__(4225) const SemVer = __webpack_require__(6376) const { re, t, comparatorTrimReplace, tildeTrimReplace, caretTrimReplace } = __webpack_require__(5765) 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 const replaceTildes = (comp, options) => comp.trim().split(/\s+/).map((comp) => { return replaceTilde(comp, 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 const replaceCarets = (comp, options) => comp.trim().split(/\s+/).map((comp) => { return replaceCaret(comp, 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((comp) => { return replaceXRange(comp, 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 } /***/ }), /***/ 6376: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const debug = __webpack_require__(4225) const { MAX_LENGTH, MAX_SAFE_INTEGER } = __webpack_require__(3295) const { re, t } = __webpack_require__(5765) const parseOptions = __webpack_require__(2893) const { compareIdentifiers } = __webpack_require__(6742) class SemVer { constructor (version, options) { options = parseOptions(options) if (version instanceof SemVer) { if (version.loose === !!options.loose && version.includePrerelease === !!options.includePrerelease) { return version } else { version = version.version } } else if (typeof version !== 'string') { throw new TypeError(`Invalid Version: ${version}`) } if (version.length > MAX_LENGTH) { throw new TypeError( `version is longer than ${MAX_LENGTH} characters` ) } debug('SemVer', version, options) this.options = options this.loose = !!options.loose // this isn't actually relevant for versions, but keep it so that we // don't run into trouble passing this.options around. this.includePrerelease = !!options.includePrerelease const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]) if (!m) { throw new TypeError(`Invalid Version: ${version}`) } this.raw = version // these are actually numbers this.major = +m[1] this.minor = +m[2] this.patch = +m[3] if (this.major > MAX_SAFE_INTEGER || this.major < 0) { throw new TypeError('Invalid major version') } if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { throw new TypeError('Invalid minor version') } if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { throw new TypeError('Invalid patch version') } // numberify any prerelease numeric ids if (!m[4]) { this.prerelease = [] } else { this.prerelease = m[4].split('.').map((id) => { if (/^[0-9]+$/.test(id)) { const num = +id if (num >= 0 && num < MAX_SAFE_INTEGER) { return num } } return id }) } this.build = m[5] ? m[5].split('.') : [] this.format() } format () { this.version = `${this.major}.${this.minor}.${this.patch}` if (this.prerelease.length) { this.version += `-${this.prerelease.join('.')}` } return this.version } toString () { return this.version } compare (other) { debug('SemVer.compare', this.version, this.options, other) if (!(other instanceof SemVer)) { if (typeof other === 'string' && other === this.version) { return 0 } other = new SemVer(other, this.options) } if (other.version === this.version) { return 0 } return this.compareMain(other) || this.comparePre(other) } compareMain (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } return ( compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch) ) } comparePre (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } // NOT having a prerelease is > having one if (this.prerelease.length && !other.prerelease.length) { return -1 } else if (!this.prerelease.length && other.prerelease.length) { return 1 } else if (!this.prerelease.length && !other.prerelease.length) { return 0 } let i = 0 do { const a = this.prerelease[i] const b = other.prerelease[i] debug('prerelease compare', i, a, b) if (a === undefined && b === undefined) { return 0 } else if (b === undefined) { return 1 } else if (a === undefined) { return -1 } else if (a === b) { continue } else { return compareIdentifiers(a, b) } } while (++i) } compareBuild (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } let i = 0 do { const a = this.build[i] const b = other.build[i] debug('prerelease compare', i, a, b) if (a === undefined && b === undefined) { return 0 } else if (b === undefined) { return 1 } else if (a === undefined) { return -1 } else if (a === b) { continue } else { return compareIdentifiers(a, b) } } while (++i) } // preminor will bump the version up to the next minor release, and immediately // down to pre-release. premajor and prepatch work the same way. inc (release, identifier) { switch (release) { case 'premajor': this.prerelease.length = 0 this.patch = 0 this.minor = 0 this.major++ this.inc('pre', identifier) break case 'preminor': this.prerelease.length = 0 this.patch = 0 this.minor++ this.inc('pre', identifier) break case 'prepatch': // If this is already a prerelease, it will bump to the next version // drop any prereleases that might already exist, since they are not // relevant at this point. this.prerelease.length = 0 this.inc('patch', identifier) this.inc('pre', identifier) break // If the input is a non-prerelease version, this acts the same as // prepatch. case 'prerelease': if (this.prerelease.length === 0) { this.inc('patch', identifier) } this.inc('pre', identifier) break case 'major': // If this is a pre-major version, bump up to the same major version. // Otherwise increment major. // 1.0.0-5 bumps to 1.0.0 // 1.1.0 bumps to 2.0.0 if ( this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0 ) { this.major++ } this.minor = 0 this.patch = 0 this.prerelease = [] break case 'minor': // If this is a pre-minor version, bump up to the same minor version. // Otherwise increment minor. // 1.2.0-5 bumps to 1.2.0 // 1.2.1 bumps to 1.3.0 if (this.patch !== 0 || this.prerelease.length === 0) { this.minor++ } this.patch = 0 this.prerelease = [] break case 'patch': // If this is not a pre-release version, it will increment the patch. // If it is a pre-release it will bump up to the same patch version. // 1.2.0-5 patches to 1.2.0 // 1.2.0 patches to 1.2.1 if (this.prerelease.length === 0) { this.patch++ } this.prerelease = [] break // This probably shouldn't be used publicly. // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. case 'pre': if (this.prerelease.length === 0) { this.prerelease = [0] } else { let i = this.prerelease.length while (--i >= 0) { if (typeof this.prerelease[i] === 'number') { this.prerelease[i]++ i = -2 } } if (i === -1) { // didn't increment anything this.prerelease.push(0) } } if (identifier) { // 1.2.0-beta.1 bumps to 1.2.0-beta.2, // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 if (this.prerelease[0] === identifier) { if (isNaN(this.prerelease[1])) { this.prerelease = [identifier, 0] } } else { this.prerelease = [identifier, 0] } } break default: throw new Error(`invalid increment argument: ${release}`) } this.format() this.raw = this.version return this } } module.exports = SemVer /***/ }), /***/ 3507: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const parse = __webpack_require__(3959) const clean = (version, options) => { const s = parse(version.trim().replace(/^[=v]+/, ''), options) return s ? s.version : null } module.exports = clean /***/ }), /***/ 7539: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const eq = __webpack_require__(8718) const neq = __webpack_require__(1194) const gt = __webpack_require__(1312) const gte = __webpack_require__(5903) const lt = __webpack_require__(1544) const lte = __webpack_require__(2056) const cmp = (a, op, b, loose) => { switch (op) { case '===': if (typeof a === 'object') a = a.version if (typeof b === 'object') b = b.version return a === b case '!==': if (typeof a === 'object') a = a.version if (typeof b === 'object') b = b.version return a !== b case '': case '=': case '==': return eq(a, b, loose) case '!=': return neq(a, b, loose) case '>': return gt(a, b, loose) case '>=': return gte(a, b, loose) case '<': return lt(a, b, loose) case '<=': return lte(a, b, loose) default: throw new TypeError(`Invalid operator: ${op}`) } } module.exports = cmp /***/ }), /***/ 9038: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(6376) const parse = __webpack_require__(3959) const {re, t} = __webpack_require__(5765) const coerce = (version, options) => { if (version instanceof SemVer) { return version } if (typeof version === 'number') { version = String(version) } if (typeof version !== 'string') { return null } options = options || {} let match = null if (!options.rtl) { match = version.match(re[t.COERCE]) } else { // Find the right-most coercible string that does not share // a terminus with a more left-ward coercible string. // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' // // Walk through the string checking with a /g regexp // Manually set the index so as to pick up overlapping matches. // Stop when we get a match that ends at the string end, since no // coercible string can be more right-ward without the same terminus. let next while ((next = re[t.COERCERTL].exec(version)) && (!match || match.index + match[0].length !== version.length) ) { if (!match || next.index + next[0].length !== match.index + match[0].length) { match = next } re[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length } // leave it in a clean state re[t.COERCERTL].lastIndex = -1 } if (match === null) return null return parse(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options) } module.exports = coerce /***/ }), /***/ 8880: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(6376) const compareBuild = (a, b, loose) => { const versionA = new SemVer(a, loose) const versionB = new SemVer(b, loose) return versionA.compare(versionB) || versionA.compareBuild(versionB) } module.exports = compareBuild /***/ }), /***/ 7880: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(6269) const compareLoose = (a, b) => compare(a, b, true) module.exports = compareLoose /***/ }), /***/ 6269: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(6376) const compare = (a, b, loose) => new SemVer(a, loose).compare(new SemVer(b, loose)) module.exports = compare /***/ }), /***/ 2378: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const parse = __webpack_require__(3959) const eq = __webpack_require__(8718) const diff = (version1, version2) => { if (eq(version1, version2)) { return null } else { const v1 = parse(version1) const v2 = parse(version2) const hasPre = v1.prerelease.length || v2.prerelease.length const prefix = hasPre ? 'pre' : '' const defaultResult = hasPre ? 'prerelease' : '' for (const key in v1) { if (key === 'major' || key === 'minor' || key === 'patch') { if (v1[key] !== v2[key]) { return prefix + key } } } return defaultResult // may be undefined } } module.exports = diff /***/ }), /***/ 8718: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(6269) const eq = (a, b, loose) => compare(a, b, loose) === 0 module.exports = eq /***/ }), /***/ 1312: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(6269) const gt = (a, b, loose) => compare(a, b, loose) > 0 module.exports = gt /***/ }), /***/ 5903: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(6269) const gte = (a, b, loose) => compare(a, b, loose) >= 0 module.exports = gte /***/ }), /***/ 253: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(6376) const inc = (version, release, options, identifier) => { if (typeof (options) === 'string') { identifier = options options = undefined } try { return new SemVer(version, options).inc(release, identifier).version } catch (er) { return null } } module.exports = inc /***/ }), /***/ 1544: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(6269) const lt = (a, b, loose) => compare(a, b, loose) < 0 module.exports = lt /***/ }), /***/ 2056: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(6269) const lte = (a, b, loose) => compare(a, b, loose) <= 0 module.exports = lte /***/ }), /***/ 8679: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(6376) const major = (a, loose) => new SemVer(a, loose).major module.exports = major /***/ }), /***/ 7789: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(6376) const minor = (a, loose) => new SemVer(a, loose).minor module.exports = minor /***/ }), /***/ 1194: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(6269) const neq = (a, b, loose) => compare(a, b, loose) !== 0 module.exports = neq /***/ }), /***/ 3959: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const {MAX_LENGTH} = __webpack_require__(3295) const { re, t } = __webpack_require__(5765) const SemVer = __webpack_require__(6376) const parseOptions = __webpack_require__(2893) const parse = (version, options) => { options = parseOptions(options) if (version instanceof SemVer) { return version } if (typeof version !== 'string') { return null } if (version.length > MAX_LENGTH) { return null } const r = options.loose ? re[t.LOOSE] : re[t.FULL] if (!r.test(version)) { return null } try { return new SemVer(version, options) } catch (er) { return null } } module.exports = parse /***/ }), /***/ 2358: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(6376) const patch = (a, loose) => new SemVer(a, loose).patch module.exports = patch /***/ }), /***/ 7559: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const parse = __webpack_require__(3959) const prerelease = (version, options) => { const parsed = parse(version, options) return (parsed && parsed.prerelease.length) ? parsed.prerelease : null } module.exports = prerelease /***/ }), /***/ 9795: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compare = __webpack_require__(6269) const rcompare = (a, b, loose) => compare(b, a, loose) module.exports = rcompare /***/ }), /***/ 3657: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compareBuild = __webpack_require__(8880) const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)) module.exports = rsort /***/ }), /***/ 5712: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(6902) const satisfies = (version, range, options) => { try { range = new Range(range, options) } catch (er) { return false } return range.test(version) } module.exports = satisfies /***/ }), /***/ 1100: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const compareBuild = __webpack_require__(8880) const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose)) module.exports = sort /***/ }), /***/ 6397: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const parse = __webpack_require__(3959) const valid = (version, options) => { const v = parse(version, options) return v ? v.version : null } module.exports = valid /***/ }), /***/ 1249: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // just pre-load all the stuff that index.js lazily exports const internalRe = __webpack_require__(5765) module.exports = { re: internalRe.re, src: internalRe.src, tokens: internalRe.t, SEMVER_SPEC_VERSION: (__webpack_require__(3295).SEMVER_SPEC_VERSION), SemVer: __webpack_require__(6376), compareIdentifiers: (__webpack_require__(6742).compareIdentifiers), rcompareIdentifiers: (__webpack_require__(6742).rcompareIdentifiers), parse: __webpack_require__(3959), valid: __webpack_require__(6397), clean: __webpack_require__(3507), inc: __webpack_require__(253), diff: __webpack_require__(2378), major: __webpack_require__(8679), minor: __webpack_require__(7789), patch: __webpack_require__(2358), prerelease: __webpack_require__(7559), compare: __webpack_require__(6269), rcompare: __webpack_require__(9795), compareLoose: __webpack_require__(7880), compareBuild: __webpack_require__(8880), sort: __webpack_require__(1100), rsort: __webpack_require__(3657), gt: __webpack_require__(1312), lt: __webpack_require__(1544), eq: __webpack_require__(8718), neq: __webpack_require__(1194), gte: __webpack_require__(5903), lte: __webpack_require__(2056), cmp: __webpack_require__(7539), coerce: __webpack_require__(9038), Comparator: __webpack_require__(2257), Range: __webpack_require__(6902), satisfies: __webpack_require__(5712), toComparators: __webpack_require__(1042), maxSatisfying: __webpack_require__(5775), minSatisfying: __webpack_require__(1657), minVersion: __webpack_require__(5316), validRange: __webpack_require__(9042), outside: __webpack_require__(6826), gtr: __webpack_require__(7606), ltr: __webpack_require__(32), intersects: __webpack_require__(2937), simplifyRange: __webpack_require__(7908), subset: __webpack_require__(799), } /***/ }), /***/ 3295: /***/ ((module) => { // Note: this is the semver.org version of the spec that it implements // Not necessarily the package version of this code. const SEMVER_SPEC_VERSION = '2.0.0' const MAX_LENGTH = 256 const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || /* istanbul ignore next */ 9007199254740991 // Max safe segment length for coercion. const MAX_SAFE_COMPONENT_LENGTH = 16 module.exports = { SEMVER_SPEC_VERSION, MAX_LENGTH, MAX_SAFE_INTEGER, MAX_SAFE_COMPONENT_LENGTH } /***/ }), /***/ 4225: /***/ ((module) => { const debug = ( typeof process === 'object' && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ) ? (...args) => console.error('SEMVER', ...args) : () => {} module.exports = debug /***/ }), /***/ 6742: /***/ ((module) => { const numeric = /^[0-9]+$/ const compareIdentifiers = (a, b) => { const anum = numeric.test(a) const bnum = numeric.test(b) if (anum && bnum) { a = +a b = +b } return a === b ? 0 : (anum && !bnum) ? -1 : (bnum && !anum) ? 1 : a < b ? -1 : 1 } const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a) module.exports = { compareIdentifiers, rcompareIdentifiers } /***/ }), /***/ 2893: /***/ ((module) => { // parse out just the options we care about so we always get a consistent // obj with keys in a consistent order. const opts = ['includePrerelease', 'loose', 'rtl'] const parseOptions = options => !options ? {} : typeof options !== 'object' ? { loose: true } : opts.filter(k => options[k]).reduce((options, k) => { options[k] = true return options }, {}) module.exports = parseOptions /***/ }), /***/ 5765: /***/ ((module, exports, __webpack_require__) => { const { MAX_SAFE_COMPONENT_LENGTH } = __webpack_require__(3295) const debug = __webpack_require__(4225) exports = module.exports = {} // The actual regexps go on exports.re const re = exports.re = [] const src = exports.src = [] const t = exports.t = {} let R = 0 const createToken = (name, value, isGlobal) => { const index = R++ debug(index, value) t[name] = index src[index] = value re[index] = new RegExp(value, isGlobal ? 'g' : undefined) } // The following Regular Expressions can be used for tokenizing, // validating, and parsing SemVer version strings. // ## Numeric Identifier // A single `0`, or a non-zero digit followed by zero or more digits. createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*') createToken('NUMERICIDENTIFIERLOOSE', '[0-9]+') // ## Non-numeric Identifier // Zero or more digits, followed by a letter or hyphen, and then zero or // more letters, digits, or hyphens. createToken('NONNUMERICIDENTIFIER', '\\d*[a-zA-Z-][a-zA-Z0-9-]*') // ## Main Version // Three dot-separated numeric identifiers. createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + `(${src[t.NUMERICIDENTIFIER]})\\.` + `(${src[t.NUMERICIDENTIFIER]})`) createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + `(${src[t.NUMERICIDENTIFIERLOOSE]})`) // ## Pre-release Version Identifier // A numeric identifier, or a non-numeric identifier. createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER] }|${src[t.NONNUMERICIDENTIFIER]})`) createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE] }|${src[t.NONNUMERICIDENTIFIER]})`) // ## Pre-release Version // Hyphen, followed by one or more dot-separated pre-release version // identifiers. createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER] }(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`) createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE] }(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`) // ## Build Metadata Identifier // Any combination of digits, letters, or hyphens. createToken('BUILDIDENTIFIER', '[0-9A-Za-z-]+') // ## Build Metadata // Plus sign, followed by one or more period-separated build metadata // identifiers. createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER] }(?:\\.${src[t.BUILDIDENTIFIER]})*))`) // ## Full Version String // A main version, followed optionally by a pre-release version and // build metadata. // Note that the only major, minor, patch, and pre-release sections of // the version string are capturing groups. The build metadata is not a // capturing group, because it should not ever be used in version // comparison. createToken('FULLPLAIN', `v?${src[t.MAINVERSION] }${src[t.PRERELEASE]}?${ src[t.BUILD]}?`) createToken('FULL', `^${src[t.FULLPLAIN]}$`) // like full, but allows v1.2.3 and =1.2.3, which people do sometimes. // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty // common in the npm registry. createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE] }${src[t.PRERELEASELOOSE]}?${ src[t.BUILD]}?`) createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`) createToken('GTLT', '((?:<|>)?=?)') // Something like "2.*" or "1.2.x". // Note that "x.x" is a valid xRange identifer, meaning "any version" // Only the first item is strictly required. createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`) createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`) createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + `(?:${src[t.PRERELEASE]})?${ src[t.BUILD]}?` + `)?)?`) createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:${src[t.PRERELEASELOOSE]})?${ src[t.BUILD]}?` + `)?)?`) createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`) createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`) // Coercion. // Extract anything that could conceivably be a part of a valid semver createToken('COERCE', `${'(^|[^\\d])' + '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + `(?:$|[^\\d])`) createToken('COERCERTL', src[t.COERCE], true) // Tilde ranges. // Meaning is "reasonably at or greater than" createToken('LONETILDE', '(?:~>?)') createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true) exports.tildeTrimReplace = '$1~' createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`) createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`) // Caret ranges. // Meaning is "at least and backwards compatible with" createToken('LONECARET', '(?:\\^)') createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true) exports.caretTrimReplace = '$1^' createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`) createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`) // A simple gt/lt/eq thing, or just "" to indicate "any version" createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`) createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`) // An expression to strip any whitespace between the gtlt and the thing // it modifies, so that `> 1.2.3` ==> `>1.2.3` createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT] }\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true) exports.comparatorTrimReplace = '$1$2$3' // Something like `1.2.3 - 1.2.4` // Note that these all use the loose form, because they'll be // checked against either the strict or loose comparator form // later. createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + `\\s+-\\s+` + `(${src[t.XRANGEPLAIN]})` + `\\s*$`) createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + `\\s+-\\s+` + `(${src[t.XRANGEPLAINLOOSE]})` + `\\s*$`) // Star ranges basically just allow anything at all. createToken('STAR', '(<|>)?=?\\s*\\*') // >=0.0.0 is like a star createToken('GTE0', '^\\s*>=\\s*0\.0\.0\\s*$') createToken('GTE0PRE', '^\\s*>=\\s*0\.0\.0-0\\s*$') /***/ }), /***/ 7606: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // Determine if version is greater than all the versions possible in the range. const outside = __webpack_require__(6826) const gtr = (version, range, options) => outside(version, range, '>', options) module.exports = gtr /***/ }), /***/ 2937: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(6902) const intersects = (r1, r2, options) => { r1 = new Range(r1, options) r2 = new Range(r2, options) return r1.intersects(r2) } module.exports = intersects /***/ }), /***/ 32: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const outside = __webpack_require__(6826) // Determine if version is less than all the versions possible in the range const ltr = (version, range, options) => outside(version, range, '<', options) module.exports = ltr /***/ }), /***/ 5775: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(6376) const Range = __webpack_require__(6902) const maxSatisfying = (versions, range, options) => { let max = null let maxSV = null let rangeObj = null try { rangeObj = new Range(range, options) } catch (er) { return null } versions.forEach((v) => { if (rangeObj.test(v)) { // satisfies(v, range, options) if (!max || maxSV.compare(v) === -1) { // compare(max, v, true) max = v maxSV = new SemVer(max, options) } } }) return max } module.exports = maxSatisfying /***/ }), /***/ 1657: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(6376) const Range = __webpack_require__(6902) const minSatisfying = (versions, range, options) => { let min = null let minSV = null let rangeObj = null try { rangeObj = new Range(range, options) } catch (er) { return null } versions.forEach((v) => { if (rangeObj.test(v)) { // satisfies(v, range, options) if (!min || minSV.compare(v) === 1) { // compare(min, v, true) min = v minSV = new SemVer(min, options) } } }) return min } module.exports = minSatisfying /***/ }), /***/ 5316: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(6376) const Range = __webpack_require__(6902) const gt = __webpack_require__(1312) const minVersion = (range, loose) => { range = new Range(range, loose) let minver = new SemVer('0.0.0') if (range.test(minver)) { return minver } minver = new SemVer('0.0.0-0') if (range.test(minver)) { return minver } minver = null for (let i = 0; i < range.set.length; ++i) { const comparators = range.set[i] let setMin = null comparators.forEach((comparator) => { // Clone to avoid manipulating the comparator's semver object. const compver = new SemVer(comparator.semver.version) switch (comparator.operator) { case '>': if (compver.prerelease.length === 0) { compver.patch++ } else { compver.prerelease.push(0) } compver.raw = compver.format() /* fallthrough */ case '': case '>=': if (!setMin || gt(compver, setMin)) { setMin = compver } break case '<': case '<=': /* Ignore maximum versions */ break /* istanbul ignore next */ default: throw new Error(`Unexpected operation: ${comparator.operator}`) } }) if (setMin && (!minver || gt(minver, setMin))) minver = setMin } if (minver && range.test(minver)) { return minver } return null } module.exports = minVersion /***/ }), /***/ 6826: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const SemVer = __webpack_require__(6376) const Comparator = __webpack_require__(2257) const {ANY} = Comparator const Range = __webpack_require__(6902) const satisfies = __webpack_require__(5712) const gt = __webpack_require__(1312) const lt = __webpack_require__(1544) const lte = __webpack_require__(2056) const gte = __webpack_require__(5903) const outside = (version, range, hilo, options) => { version = new SemVer(version, options) range = new Range(range, options) let gtfn, ltefn, ltfn, comp, ecomp switch (hilo) { case '>': gtfn = gt ltefn = lte ltfn = lt comp = '>' ecomp = '>=' break case '<': gtfn = lt ltefn = gte ltfn = gt comp = '<' ecomp = '<=' break default: throw new TypeError('Must provide a hilo val of "<" or ">"') } // If it satisfies the range it is not outside if (satisfies(version, range, options)) { return false } // From now on, variable terms are as if we're in "gtr" mode. // but note that everything is flipped for the "ltr" function. for (let i = 0; i < range.set.length; ++i) { const comparators = range.set[i] let high = null let low = null comparators.forEach((comparator) => { if (comparator.semver === ANY) { comparator = new Comparator('>=0.0.0') } high = high || comparator low = low || comparator if (gtfn(comparator.semver, high.semver, options)) { high = comparator } else if (ltfn(comparator.semver, low.semver, options)) { low = comparator } }) // If the edge version comparator has a operator then our version // isn't outside it if (high.operator === comp || high.operator === ecomp) { return false } // If the lowest version comparator has an operator and our version // is less than it then it isn't higher than the range if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) { return false } else if (low.operator === ecomp && ltfn(version, low.semver)) { return false } } return true } module.exports = outside /***/ }), /***/ 7908: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // 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 = __webpack_require__(5712) const compare = __webpack_require__(6269) module.exports = (versions, range, options) => { const set = [] let min = null let prev = null const v = versions.sort((a, b) => compare(a, b, options)) for (const version of v) { const included = satisfies(version, range, options) if (included) { prev = version if (!min) min = version } else { if (prev) { set.push([min, prev]) } prev = null min = null } } if (min) set.push([min, 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 } /***/ }), /***/ 799: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(6902) const Comparator = __webpack_require__(2257) const { ANY } = Comparator const satisfies = __webpack_require__(5712) const compare = __webpack_require__(6269) // Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff: // - Every simple range `r1, r2, ...` is a null set, OR // - Every simple range `r1, r2, ...` which is not a null set is a subset of // some `R1, R2, ...` // // Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff: // - If c is only the ANY comparator // - If C is only the ANY comparator, return true // - Else if in prerelease mode, return false // - else replace c with `[>=0.0.0]` // - If C is only the ANY comparator // - if in prerelease mode, return true // - else replace C with `[>=0.0.0]` // - Let EQ be the set of = comparators in c // - If EQ is more than one, return true (null set) // - Let GT be the highest > or >= comparator in c // - Let LT be the lowest < or <= comparator in c // - If GT and LT, and GT.semver > LT.semver, return true (null set) // - If any C is a = range, and GT or LT are set, return false // - If EQ // - If GT, and EQ does not satisfy GT, return true (null set) // - If LT, and EQ does not satisfy LT, return true (null set) // - If EQ satisfies every C, return true // - Else return false // - If GT // - If GT.semver is lower than any > or >= comp in C, return false // - If GT is >=, and GT.semver does not satisfy every C, return false // - If GT.semver has a prerelease, and not in prerelease mode // - If no C has a prerelease and the GT.semver tuple, return false // - If LT // - If LT.semver is greater than any < or <= comp in C, return false // - If LT is <=, and LT.semver does not satisfy every C, return false // - If GT.semver has a prerelease, and not in prerelease mode // - If no C has a prerelease and the LT.semver tuple, return false // - Else return true const subset = (sub, dom, options = {}) => { if (sub === dom) return true sub = new Range(sub, options) dom = new Range(dom, options) let sawNonNull = false OUTER: for (const simpleSub of sub.set) { for (const simpleDom of dom.set) { const isSub = simpleSubset(simpleSub, simpleDom, options) sawNonNull = sawNonNull || isSub !== null if (isSub) continue OUTER } // the null set is a subset of everything, but null simple ranges in // a complex range should be ignored. so if we saw a non-null range, // then we know this isn't a subset, but if EVERY simple range was null, // then it is a subset. if (sawNonNull) return false } return true } const simpleSubset = (sub, dom, options) => { if (sub === dom) return true if (sub.length === 1 && sub[0].semver === ANY) { if (dom.length === 1 && dom[0].semver === ANY) return true else if (options.includePrerelease) sub = [ new Comparator('>=0.0.0-0') ] else sub = [ new Comparator('>=0.0.0') ] } if (dom.length === 1 && dom[0].semver === ANY) { if (options.includePrerelease) return true else dom = [ new Comparator('>=0.0.0') ] } const eqSet = new Set() let gt, lt for (const c of sub) { if (c.operator === '>' || c.operator === '>=') gt = higherGT(gt, c, options) else if (c.operator === '<' || c.operator === '<=') lt = lowerLT(lt, c, options) else eqSet.add(c.semver) } if (eqSet.size > 1) return null let gtltComp if (gt && lt) { gtltComp = compare(gt.semver, lt.semver, options) if (gtltComp > 0) return null else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) return null } // will iterate one or zero times for (const eq of eqSet) { if (gt && !satisfies(eq, String(gt), options)) return null if (lt && !satisfies(eq, String(lt), options)) return null for (const c of dom) { if (!satisfies(eq, String(c), options)) return false } return true } let higher, lower let hasDomLT, hasDomGT // if the subset has a prerelease, we need a comparator in the superset // with the same tuple and a prerelease, or it's not a subset let needDomLTPre = lt && !options.includePrerelease && lt.semver.prerelease.length ? lt.semver : false let needDomGTPre = gt && !options.includePrerelease && gt.semver.prerelease.length ? gt.semver : false // exception: <1.2.3-0 is the same as <1.2.3 if (needDomLTPre && needDomLTPre.prerelease.length === 1 && lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { needDomLTPre = false } for (const c of dom) { hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>=' hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<=' if (gt) { if (needDomGTPre) { if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomGTPre.major && c.semver.minor === needDomGTPre.minor && c.semver.patch === needDomGTPre.patch) { needDomGTPre = false } } if (c.operator === '>' || c.operator === '>=') { higher = higherGT(gt, c, options) if (higher === c && higher !== gt) return false } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) return false } if (lt) { if (needDomLTPre) { if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomLTPre.major && c.semver.minor === needDomLTPre.minor && c.semver.patch === needDomLTPre.patch) { needDomLTPre = false } } if (c.operator === '<' || c.operator === '<=') { lower = lowerLT(lt, c, options) if (lower === c && lower !== lt) return false } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) return false } if (!c.operator && (lt || gt) && gtltComp !== 0) return false } // if there was a < or >, and nothing in the dom, then must be false // UNLESS it was limited by another range in the other direction. // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 if (gt && hasDomLT && !lt && gtltComp !== 0) return false if (lt && hasDomGT && !gt && gtltComp !== 0) return false // we needed a prerelease range in a specific tuple, but didn't get one // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0, // because it includes prereleases in the 1.2.3 tuple if (needDomGTPre || needDomLTPre) return false return true } // >=1.2.3 is lower than >1.2.3 const higherGT = (a, b, options) => { if (!a) return b const comp = compare(a.semver, b.semver, options) return comp > 0 ? a : comp < 0 ? b : b.operator === '>' && a.operator === '>=' ? b : a } // <=1.2.3 is higher than <1.2.3 const lowerLT = (a, b, options) => { if (!a) return b const comp = compare(a.semver, b.semver, options) return comp < 0 ? a : comp > 0 ? b : b.operator === '<' && a.operator === '<=' ? b : a } module.exports = subset /***/ }), /***/ 1042: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(6902) // Mostly just for testing and legacy API reasons const toComparators = (range, options) => new Range(range, options).set .map(comp => comp.map(c => c.value).join(' ').trim().split(' ')) module.exports = toComparators /***/ }), /***/ 9042: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const Range = __webpack_require__(6902) const validRange = (range, options) => { try { // Return '*' instead of '' so that truthiness works. // This will throw if it's invalid anyway return new Range(range, options).range || '*' } catch (er) { return null } } module.exports = validRange /***/ }), /***/ 2130: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const os = __webpack_require__(2037); const tty = __webpack_require__(6224); const hasFlag = __webpack_require__(8512); 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); } module.exports = { supportsColor: getSupportLevel, stdout: translateLevel(supportsColor(true, tty.isatty(1))), stderr: translateLevel(supportsColor(true, tty.isatty(2))) }; /***/ }), /***/ 7998: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // high-level commands exports.c = exports.create = __webpack_require__(4629) exports.r = exports.replace = __webpack_require__(1746) exports.t = exports.list = __webpack_require__(6473) exports.u = exports.update = __webpack_require__(5997) exports.x = exports.extract = __webpack_require__(769) // classes exports.Pack = __webpack_require__(8042) exports.Unpack = __webpack_require__(2699) exports.Parse = __webpack_require__(6824) exports.ReadEntry = __webpack_require__(6277) exports.WriteEntry = __webpack_require__(7620) exports.Header = __webpack_require__(7134) exports.Pax = __webpack_require__(4747) exports.types = __webpack_require__(4402) /***/ }), /***/ 4629: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; // tar -c const hlo = __webpack_require__(2093) const Pack = __webpack_require__(8042) const fsm = __webpack_require__(292) const t = __webpack_require__(6473) const path = __webpack_require__(1017) module.exports = (opt_, files, cb) => { if (typeof files === 'function') cb = files if (Array.isArray(opt_)) files = opt_, opt_ = {} if (!files || !Array.isArray(files) || !files.length) throw new TypeError('no files or directories specified') files = Array.from(files) const opt = hlo(opt_) if (opt.sync && typeof cb === 'function') throw new TypeError('callback not supported for sync tar functions') if (!opt.file && typeof cb === 'function') throw new TypeError('callback only supported with file option') return opt.file && opt.sync ? createFileSync(opt, files) : opt.file ? createFile(opt, files, cb) : opt.sync ? createSync(opt, files) : create(opt, files) } const createFileSync = (opt, files) => { const p = new Pack.Sync(opt) const stream = new fsm.WriteStreamSync(opt.file, { mode: opt.mode || 0o666, }) p.pipe(stream) addFilesSync(p, files) } const createFile = (opt, files, cb) => { const p = new Pack(opt) const stream = new fsm.WriteStream(opt.file, { mode: opt.mode || 0o666, }) p.pipe(stream) const promise = new Promise((res, rej) => { stream.on('error', rej) stream.on('close', res) p.on('error', rej) }) addFilesAsync(p, files) return cb ? promise.then(cb, cb) : promise } const addFilesSync = (p, files) => { files.forEach(file => { if (file.charAt(0) === '@') { t({ file: path.resolve(p.cwd, file.substr(1)), sync: true, noResume: true, onentry: entry => p.add(entry), }) } else p.add(file) }) p.end() } const addFilesAsync = (p, files) => { while (files.length) { const file = files.shift() if (file.charAt(0) === '@') { return t({ file: path.resolve(p.cwd, file.substr(1)), noResume: true, onentry: entry => p.add(entry), }).then(_ => addFilesAsync(p, files)) } else p.add(file) } p.end() } const createSync = (opt, files) => { const p = new Pack.Sync(opt) addFilesSync(p, files) return p } const create = (opt, files) => { const p = new Pack(opt) addFilesAsync(p, files) return p } /***/ }), /***/ 769: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; // tar -x const hlo = __webpack_require__(2093) const Unpack = __webpack_require__(2699) const fs = __webpack_require__(7147) const fsm = __webpack_require__(292) const path = __webpack_require__(1017) const stripSlash = __webpack_require__(4922) module.exports = (opt_, files, cb) => { if (typeof opt_ === 'function') cb = opt_, files = null, opt_ = {} else if (Array.isArray(opt_)) files = opt_, opt_ = {} if (typeof files === 'function') cb = files, files = null if (!files) files = [] else files = Array.from(files) const opt = hlo(opt_) if (opt.sync && typeof cb === 'function') throw new TypeError('callback not supported for sync tar functions') if (!opt.file && typeof cb === 'function') throw new TypeError('callback only supported with file option') if (files.length) filesFilter(opt, files) return opt.file && opt.sync ? extractFileSync(opt) : opt.file ? extractFile(opt, cb) : opt.sync ? extractSync(opt) : extract(opt) } // construct a filter that limits the file entries listed // include child entries if a dir is included const filesFilter = (opt, files) => { const map = new Map(files.map(f => [stripSlash(f), true])) const filter = opt.filter const mapHas = (file, r) => { const root = r || path.parse(file).root || '.' const ret = file === root ? false : map.has(file) ? map.get(file) : mapHas(path.dirname(file), root) map.set(file, ret) return ret } opt.filter = filter ? (file, entry) => filter(file, entry) && mapHas(stripSlash(file)) : file => mapHas(stripSlash(file)) } const extractFileSync = opt => { const u = new Unpack.Sync(opt) const file = opt.file const stat = fs.statSync(file) // This trades a zero-byte read() syscall for a stat // However, it will usually result in less memory allocation const readSize = opt.maxReadSize || 16 * 1024 * 1024 const stream = new fsm.ReadStreamSync(file, { readSize: readSize, size: stat.size, }) stream.pipe(u) } const extractFile = (opt, cb) => { const u = new Unpack(opt) const readSize = opt.maxReadSize || 16 * 1024 * 1024 const file = opt.file const p = new Promise((resolve, reject) => { u.on('error', reject) u.on('close', resolve) // This trades a zero-byte read() syscall for a stat // However, it will usually result in less memory allocation fs.stat(file, (er, stat) => { if (er) reject(er) else { const stream = new fsm.ReadStream(file, { readSize: readSize, size: stat.size, }) stream.on('error', reject) stream.pipe(u) } }) }) return cb ? p.then(cb, cb) : p } const extractSync = opt => new Unpack.Sync(opt) const extract = opt => new Unpack(opt) /***/ }), /***/ 5879: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // Get the appropriate flag to use for creating files // We use fmap on Windows platforms for files less than // 512kb. This is a fairly low limit, but avoids making // things slower in some cases. Since most of what this // library is used for is extracting tarballs of many // relatively small files in npm packages and the like, // it can be a big boost on Windows platforms. // Only supported in Node v12.9.0 and above. const platform = process.env.__FAKE_PLATFORM__ || process.platform const isWindows = platform === 'win32' const fs = global.__FAKE_TESTING_FS__ || __webpack_require__(7147) /* istanbul ignore next */ const { O_CREAT, O_TRUNC, O_WRONLY, UV_FS_O_FILEMAP = 0 } = fs.constants const fMapEnabled = isWindows && !!UV_FS_O_FILEMAP const fMapLimit = 512 * 1024 const fMapFlag = UV_FS_O_FILEMAP | O_TRUNC | O_CREAT | O_WRONLY module.exports = !fMapEnabled ? () => 'w' : size => size < fMapLimit ? fMapFlag : 'w' /***/ }), /***/ 7134: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; // parse a 512-byte header block to a data object, or vice-versa // encode returns `true` if a pax extended header is needed, because // the data could not be faithfully encoded in a simple header. // (Also, check header.needPax to see if it needs a pax header.) const types = __webpack_require__(4402) const pathModule = (__webpack_require__(1017).posix) const large = __webpack_require__(9678) const SLURP = Symbol('slurp') const TYPE = Symbol('type') class Header { constructor (data, off, ex, gex) { this.cksumValid = false this.needPax = false this.nullBlock = false this.block = null this.path = null this.mode = null this.uid = null this.gid = null this.size = null this.mtime = null this.cksum = null this[TYPE] = '0' this.linkpath = null this.uname = null this.gname = null this.devmaj = 0 this.devmin = 0 this.atime = null this.ctime = null if (Buffer.isBuffer(data)) this.decode(data, off || 0, ex, gex) else if (data) this.set(data) } decode (buf, off, ex, gex) { if (!off) off = 0 if (!buf || !(buf.length >= off + 512)) throw new Error('need 512 bytes for header') this.path = decString(buf, off, 100) this.mode = decNumber(buf, off + 100, 8) this.uid = decNumber(buf, off + 108, 8) this.gid = decNumber(buf, off + 116, 8) this.size = decNumber(buf, off + 124, 12) this.mtime = decDate(buf, off + 136, 12) this.cksum = decNumber(buf, off + 148, 12) // if we have extended or global extended headers, apply them now // See https://github.com/npm/node-tar/pull/187 this[SLURP](ex) this[SLURP](gex, true) // old tar versions marked dirs as a file with a trailing / this[TYPE] = decString(buf, off + 156, 1) if (this[TYPE] === '') this[TYPE] = '0' if (this[TYPE] === '0' && this.path.substr(-1) === '/') this[TYPE] = '5' // tar implementations sometimes incorrectly put the stat(dir).size // as the size in the tarball, even though Directory entries are // not able to have any body at all. In the very rare chance that // it actually DOES have a body, we weren't going to do anything with // it anyway, and it'll just be a warning about an invalid header. if (this[TYPE] === '5') this.size = 0 this.linkpath = decString(buf, off + 157, 100) if (buf.slice(off + 257, off + 265).toString() === 'ustar\u000000') { this.uname = decString(buf, off + 265, 32) this.gname = decString(buf, off + 297, 32) this.devmaj = decNumber(buf, off + 329, 8) this.devmin = decNumber(buf, off + 337, 8) if (buf[off + 475] !== 0) { // definitely a prefix, definitely >130 chars. const prefix = decString(buf, off + 345, 155) this.path = prefix + '/' + this.path } else { const prefix = decString(buf, off + 345, 130) if (prefix) this.path = prefix + '/' + this.path this.atime = decDate(buf, off + 476, 12) this.ctime = decDate(buf, off + 488, 12) } } let sum = 8 * 0x20 for (let i = off; i < off + 148; i++) sum += buf[i] for (let i = off + 156; i < off + 512; i++) sum += buf[i] this.cksumValid = sum === this.cksum if (this.cksum === null && sum === 8 * 0x20) this.nullBlock = true } [SLURP] (ex, global) { for (const k in ex) { // we slurp in everything except for the path attribute in // a global extended header, because that's weird. if (ex[k] !== null && ex[k] !== undefined && !(global && k === 'path')) this[k] = ex[k] } } encode (buf, off) { if (!buf) { buf = this.block = Buffer.alloc(512) off = 0 } if (!off) off = 0 if (!(buf.length >= off + 512)) throw new Error('need 512 bytes for header') const prefixSize = this.ctime || this.atime ? 130 : 155 const split = splitPrefix(this.path || '', prefixSize) const path = split[0] const prefix = split[1] this.needPax = split[2] this.needPax = encString(buf, off, 100, path) || this.needPax this.needPax = encNumber(buf, off + 100, 8, this.mode) || this.needPax this.needPax = encNumber(buf, off + 108, 8, this.uid) || this.needPax this.needPax = encNumber(buf, off + 116, 8, this.gid) || this.needPax this.needPax = encNumber(buf, off + 124, 12, this.size) || this.needPax this.needPax = encDate(buf, off + 136, 12, this.mtime) || this.needPax buf[off + 156] = this[TYPE].charCodeAt(0) this.needPax = encString(buf, off + 157, 100, this.linkpath) || this.needPax buf.write('ustar\u000000', off + 257, 8) this.needPax = encString(buf, off + 265, 32, this.uname) || this.needPax this.needPax = encString(buf, off + 297, 32, this.gname) || this.needPax this.needPax = encNumber(buf, off + 329, 8, this.devmaj) || this.needPax this.needPax = encNumber(buf, off + 337, 8, this.devmin) || this.needPax this.needPax = encString(buf, off + 345, prefixSize, prefix) || this.needPax if (buf[off + 475] !== 0) this.needPax = encString(buf, off + 345, 155, prefix) || this.needPax else { this.needPax = encString(buf, off + 345, 130, prefix) || this.needPax this.needPax = encDate(buf, off + 476, 12, this.atime) || this.needPax this.needPax = encDate(buf, off + 488, 12, this.ctime) || this.needPax } let sum = 8 * 0x20 for (let i = off; i < off + 148; i++) sum += buf[i] for (let i = off + 156; i < off + 512; i++) sum += buf[i] this.cksum = sum encNumber(buf, off + 148, 8, this.cksum) this.cksumValid = true return this.needPax } set (data) { for (const i in data) { if (data[i] !== null && data[i] !== undefined) this[i] = data[i] } } get type () { return types.name.get(this[TYPE]) || this[TYPE] } get typeKey () { return this[TYPE] } set type (type) { if (types.code.has(type)) this[TYPE] = types.code.get(type) else this[TYPE] = type } } const splitPrefix = (p, prefixSize) => { const pathSize = 100 let pp = p let prefix = '' let ret const root = pathModule.parse(p).root || '.' if (Buffer.byteLength(pp) < pathSize) ret = [pp, prefix, false] else { // first set prefix to the dir, and path to the base prefix = pathModule.dirname(pp) pp = pathModule.basename(pp) do { // both fit! if (Buffer.byteLength(pp) <= pathSize && Buffer.byteLength(prefix) <= prefixSize) ret = [pp, prefix, false] // prefix fits in prefix, but path doesn't fit in path else if (Buffer.byteLength(pp) > pathSize && Buffer.byteLength(prefix) <= prefixSize) ret = [pp.substr(0, pathSize - 1), prefix, true] else { // make path take a bit from prefix pp = pathModule.join(pathModule.basename(prefix), pp) prefix = pathModule.dirname(prefix) } } while (prefix !== root && !ret) // at this point, found no resolution, just truncate if (!ret) ret = [p.substr(0, pathSize - 1), '', true] } return ret } const decString = (buf, off, size) => buf.slice(off, off + size).toString('utf8').replace(/\0.*/, '') const decDate = (buf, off, size) => numToDate(decNumber(buf, off, size)) const numToDate = num => num === null ? null : new Date(num * 1000) const decNumber = (buf, off, size) => buf[off] & 0x80 ? large.parse(buf.slice(off, off + size)) : decSmallNumber(buf, off, size) const nanNull = value => isNaN(value) ? null : value const decSmallNumber = (buf, off, size) => nanNull(parseInt( buf.slice(off, off + size) .toString('utf8').replace(/\0.*$/, '').trim(), 8)) // the maximum encodable as a null-terminated octal, by field size const MAXNUM = { 12: 0o77777777777, 8: 0o7777777, } const encNumber = (buf, off, size, number) => number === null ? false : number > MAXNUM[size] || number < 0 ? (large.encode(number, buf.slice(off, off + size)), true) : (encSmallNumber(buf, off, size, number), false) const encSmallNumber = (buf, off, size, number) => buf.write(octalString(number, size), off, size, 'ascii') const octalString = (number, size) => padOctal(Math.floor(number).toString(8), size) const padOctal = (string, size) => (string.length === size - 1 ? string : new Array(size - string.length - 1).join('0') + string + ' ') + '\0' const encDate = (buf, off, size, date) => date === null ? false : encNumber(buf, off, size, date.getTime() / 1000) // enough to fill the longest string we've got const NULLS = new Array(156).join('\0') // pad with nulls, return true if it's longer or non-ascii const encString = (buf, off, size, string) => string === null ? false : (buf.write(string + NULLS, off, size, 'utf8'), string.length !== Buffer.byteLength(string) || string.length > size) module.exports = Header /***/ }), /***/ 2093: /***/ ((module) => { "use strict"; // turn tar(1) style args like `C` into the more verbose things like `cwd` const argmap = new Map([ ['C', 'cwd'], ['f', 'file'], ['z', 'gzip'], ['P', 'preservePaths'], ['U', 'unlink'], ['strip-components', 'strip'], ['stripComponents', 'strip'], ['keep-newer', 'newer'], ['keepNewer', 'newer'], ['keep-newer-files', 'newer'], ['keepNewerFiles', 'newer'], ['k', 'keep'], ['keep-existing', 'keep'], ['keepExisting', 'keep'], ['m', 'noMtime'], ['no-mtime', 'noMtime'], ['p', 'preserveOwner'], ['L', 'follow'], ['h', 'follow'], ]) module.exports = opt => opt ? Object.keys(opt).map(k => [ argmap.has(k) ? argmap.get(k) : k, opt[k], ]).reduce((set, kv) => (set[kv[0]] = kv[1], set), Object.create(null)) : {} /***/ }), /***/ 9678: /***/ ((module) => { "use strict"; // Tar can encode large and negative numbers using a leading byte of // 0xff for negative, and 0x80 for positive. const encode = (num, buf) => { if (!Number.isSafeInteger(num)) // The number is so large that javascript cannot represent it with integer // precision. throw Error('cannot encode number outside of javascript safe integer range') else if (num < 0) encodeNegative(num, buf) else encodePositive(num, buf) return buf } const encodePositive = (num, buf) => { buf[0] = 0x80 for (var i = buf.length; i > 1; i--) { buf[i - 1] = num & 0xff num = Math.floor(num / 0x100) } } const encodeNegative = (num, buf) => { buf[0] = 0xff var flipped = false num = num * -1 for (var i = buf.length; i > 1; i--) { var byte = num & 0xff num = Math.floor(num / 0x100) if (flipped) buf[i - 1] = onesComp(byte) else if (byte === 0) buf[i - 1] = 0 else { flipped = true buf[i - 1] = twosComp(byte) } } } const parse = (buf) => { const pre = buf[0] const value = pre === 0x80 ? pos(buf.slice(1, buf.length)) : pre === 0xff ? twos(buf) : null if (value === null) throw Error('invalid base256 encoding') if (!Number.isSafeInteger(value)) // The number is so large that javascript cannot represent it with integer // precision. throw Error('parsed number outside of javascript safe integer range') return value } const twos = (buf) => { var len = buf.length var sum = 0 var flipped = false for (var i = len - 1; i > -1; i--) { var byte = buf[i] var f if (flipped) f = onesComp(byte) else if (byte === 0) f = byte else { flipped = true f = twosComp(byte) } if (f !== 0) sum -= f * Math.pow(256, len - i - 1) } return sum } const pos = (buf) => { var len = buf.length var sum = 0 for (var i = len - 1; i > -1; i--) { var byte = buf[i] if (byte !== 0) sum += byte * Math.pow(256, len - i - 1) } return sum } const onesComp = byte => (0xff ^ byte) & 0xff const twosComp = byte => ((0xff ^ byte) + 1) & 0xff module.exports = { encode, parse, } /***/ }), /***/ 6473: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; // XXX: This shares a lot in common with extract.js // maybe some DRY opportunity here? // tar -t const hlo = __webpack_require__(2093) const Parser = __webpack_require__(6824) const fs = __webpack_require__(7147) const fsm = __webpack_require__(292) const path = __webpack_require__(1017) const stripSlash = __webpack_require__(4922) module.exports = (opt_, files, cb) => { if (typeof opt_ === 'function') cb = opt_, files = null, opt_ = {} else if (Array.isArray(opt_)) files = opt_, opt_ = {} if (typeof files === 'function') cb = files, files = null if (!files) files = [] else files = Array.from(files) const opt = hlo(opt_) if (opt.sync && typeof cb === 'function') throw new TypeError('callback not supported for sync tar functions') if (!opt.file && typeof cb === 'function') throw new TypeError('callback only supported with file option') if (files.length) filesFilter(opt, files) if (!opt.noResume) onentryFunction(opt) return opt.file && opt.sync ? listFileSync(opt) : opt.file ? listFile(opt, cb) : list(opt) } const onentryFunction = opt => { const onentry = opt.onentry opt.onentry = onentry ? e => { onentry(e) e.resume() } : e => e.resume() } // construct a filter that limits the file entries listed // include child entries if a dir is included const filesFilter = (opt, files) => { const map = new Map(files.map(f => [stripSlash(f), true])) const filter = opt.filter const mapHas = (file, r) => { const root = r || path.parse(file).root || '.' const ret = file === root ? false : map.has(file) ? map.get(file) : mapHas(path.dirname(file), root) map.set(file, ret) return ret } opt.filter = filter ? (file, entry) => filter(file, entry) && mapHas(stripSlash(file)) : file => mapHas(stripSlash(file)) } const listFileSync = opt => { const p = list(opt) const file = opt.file let threw = true let fd try { const stat = fs.statSync(file) const readSize = opt.maxReadSize || 16 * 1024 * 1024 if (stat.size < readSize) p.end(fs.readFileSync(file)) else { let pos = 0 const buf = Buffer.allocUnsafe(readSize) fd = fs.openSync(file, 'r') while (pos < stat.size) { const bytesRead = fs.readSync(fd, buf, 0, readSize, pos) pos += bytesRead p.write(buf.slice(0, bytesRead)) } p.end() } threw = false } finally { if (threw && fd) { try { fs.closeSync(fd) } catch (er) {} } } } const listFile = (opt, cb) => { const parse = new Parser(opt) const readSize = opt.maxReadSize || 16 * 1024 * 1024 const file = opt.file const p = new Promise((resolve, reject) => { parse.on('error', reject) parse.on('end', resolve) fs.stat(file, (er, stat) => { if (er) reject(er) else { const stream = new fsm.ReadStream(file, { readSize: readSize, size: stat.size, }) stream.on('error', reject) stream.pipe(parse) } }) }) return cb ? p.then(cb, cb) : p } const list = opt => new Parser(opt) /***/ }), /***/ 3248: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; // wrapper around mkdirp for tar's needs. // TODO: This should probably be a class, not functionally // passing around state in a gazillion args. const mkdirp = __webpack_require__(1890) const fs = __webpack_require__(7147) const path = __webpack_require__(1017) const chownr = __webpack_require__(9019) const normPath = __webpack_require__(2905) class SymlinkError extends Error { constructor (symlink, path) { super('Cannot extract through symbolic link') this.path = path this.symlink = symlink } get name () { return 'SylinkError' } } class CwdError extends Error { constructor (path, code) { super(code + ': Cannot cd into \'' + path + '\'') this.path = path this.code = code } get name () { return 'CwdError' } } const cGet = (cache, key) => cache.get(normPath(key)) const cSet = (cache, key, val) => cache.set(normPath(key), val) const checkCwd = (dir, cb) => { fs.stat(dir, (er, st) => { if (er || !st.isDirectory()) er = new CwdError(dir, er && er.code || 'ENOTDIR') cb(er) }) } module.exports = (dir, opt, cb) => { dir = normPath(dir) // if there's any overlap between mask and mode, // then we'll need an explicit chmod const umask = opt.umask const mode = opt.mode | 0o0700 const needChmod = (mode & umask) !== 0 const uid = opt.uid const gid = opt.gid const doChown = typeof uid === 'number' && typeof gid === 'number' && (uid !== opt.processUid || gid !== opt.processGid) const preserve = opt.preserve const unlink = opt.unlink const cache = opt.cache const cwd = normPath(opt.cwd) const done = (er, created) => { if (er) cb(er) else { cSet(cache, dir, true) if (created && doChown) chownr(created, uid, gid, er => done(er)) else if (needChmod) fs.chmod(dir, mode, cb) else cb() } } if (cache && cGet(cache, dir) === true) return done() if (dir === cwd) return checkCwd(dir, done) if (preserve) return mkdirp(dir, {mode}).then(made => done(null, made), done) const sub = normPath(path.relative(cwd, dir)) const parts = sub.split('/') mkdir_(cwd, parts, mode, cache, unlink, cwd, null, done) } const mkdir_ = (base, parts, mode, cache, unlink, cwd, created, cb) => { if (!parts.length) return cb(null, created) const p = parts.shift() const part = normPath(path.resolve(base + '/' + p)) if (cGet(cache, part)) return mkdir_(part, parts, mode, cache, unlink, cwd, created, cb) fs.mkdir(part, mode, onmkdir(part, parts, mode, cache, unlink, cwd, created, cb)) } const onmkdir = (part, parts, mode, cache, unlink, cwd, created, cb) => er => { if (er) { fs.lstat(part, (statEr, st) => { if (statEr) { statEr.path = statEr.path && normPath(statEr.path) cb(statEr) } else if (st.isDirectory()) mkdir_(part, parts, mode, cache, unlink, cwd, created, cb) else if (unlink) { fs.unlink(part, er => { if (er) return cb(er) fs.mkdir(part, mode, onmkdir(part, parts, mode, cache, unlink, cwd, created, cb)) }) } else if (st.isSymbolicLink()) return cb(new SymlinkError(part, part + '/' + parts.join('/'))) else cb(er) }) } else { created = created || part mkdir_(part, parts, mode, cache, unlink, cwd, created, cb) } } const checkCwdSync = dir => { let ok = false let code = 'ENOTDIR' try { ok = fs.statSync(dir).isDirectory() } catch (er) { code = er.code } finally { if (!ok) throw new CwdError(dir, code) } } module.exports.sync = (dir, opt) => { dir = normPath(dir) // if there's any overlap between mask and mode, // then we'll need an explicit chmod const umask = opt.umask const mode = opt.mode | 0o0700 const needChmod = (mode & umask) !== 0 const uid = opt.uid const gid = opt.gid const doChown = typeof uid === 'number' && typeof gid === 'number' && (uid !== opt.processUid || gid !== opt.processGid) const preserve = opt.preserve const unlink = opt.unlink const cache = opt.cache const cwd = normPath(opt.cwd) const done = (created) => { cSet(cache, dir, true) if (created && doChown) chownr.sync(created, uid, gid) if (needChmod) fs.chmodSync(dir, mode) } if (cache && cGet(cache, dir) === true) return done() if (dir === cwd) { checkCwdSync(cwd) return done() } if (preserve) return done(mkdirp.sync(dir, mode)) const sub = normPath(path.relative(cwd, dir)) const parts = sub.split('/') let created = null for (let p = parts.shift(), part = cwd; p && (part += '/' + p); p = parts.shift()) { part = normPath(path.resolve(part)) if (cGet(cache, part)) continue try { fs.mkdirSync(part, mode) created = created || part cSet(cache, part, true) } catch (er) { const st = fs.lstatSync(part) if (st.isDirectory()) { cSet(cache, part, true) continue } else if (unlink) { fs.unlinkSync(part) fs.mkdirSync(part, mode) created = created || part cSet(cache, part, true) continue } else if (st.isSymbolicLink()) return new SymlinkError(part, part + '/' + parts.join('/')) } } return done(created) } /***/ }), /***/ 7716: /***/ ((module) => { "use strict"; module.exports = (mode, isDir, portable) => { mode &= 0o7777 // in portable mode, use the minimum reasonable umask // if this system creates files with 0o664 by default // (as some linux distros do), then we'll write the // archive with 0o644 instead. Also, don't ever create // a file that is not readable/writable by the owner. if (portable) mode = (mode | 0o600) & ~0o22 // if dirs are readable, then they should be listable if (isDir) { if (mode & 0o400) mode |= 0o100 if (mode & 0o40) mode |= 0o10 if (mode & 0o4) mode |= 0o1 } return mode } /***/ }), /***/ 1946: /***/ ((module) => { // warning: extremely hot code path. // This has been meticulously optimized for use // within npm install on large package trees. // Do not edit without careful benchmarking. const normalizeCache = Object.create(null) const {hasOwnProperty} = Object.prototype module.exports = s => { if (!hasOwnProperty.call(normalizeCache, s)) normalizeCache[s] = s.normalize('NFKD') return normalizeCache[s] } /***/ }), /***/ 2905: /***/ ((module) => { // on windows, either \ or / are valid directory separators. // on unix, \ is a valid character in filenames. // so, on windows, and only on windows, we replace all \ chars with /, // so that we can use / as our one and only directory separator char. const platform = process.env.TESTING_TAR_FAKE_PLATFORM || process.platform module.exports = platform !== 'win32' ? p => p : p => p && p.replace(/\\/g, '/') /***/ }), /***/ 8042: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; // A readable tar stream creator // Technically, this is a transform stream that you write paths into, // and tar format comes out of. // The `add()` method is like `write()` but returns this, // and end() return `this` as well, so you can // do `new Pack(opt).add('files').add('dir').end().pipe(output) // You could also do something like: // streamOfPaths().pipe(new Pack()).pipe(new fs.WriteStream('out.tar')) class PackJob { constructor (path, absolute) { this.path = path || './' this.absolute = absolute this.entry = null this.stat = null this.readdir = null this.pending = false this.ignore = false this.piped = false } } const MiniPass = __webpack_require__(5736) const zlib = __webpack_require__(1650) const ReadEntry = __webpack_require__(6277) const WriteEntry = __webpack_require__(7620) const WriteEntrySync = WriteEntry.Sync const WriteEntryTar = WriteEntry.Tar const Yallist = __webpack_require__(4411) const EOF = Buffer.alloc(1024) const ONSTAT = Symbol('onStat') const ENDED = Symbol('ended') const QUEUE = Symbol('queue') const CURRENT = Symbol('current') const PROCESS = Symbol('process') const PROCESSING = Symbol('processing') const PROCESSJOB = Symbol('processJob') const JOBS = Symbol('jobs') const JOBDONE = Symbol('jobDone') const ADDFSENTRY = Symbol('addFSEntry') const ADDTARENTRY = Symbol('addTarEntry') const STAT = Symbol('stat') const READDIR = Symbol('readdir') const ONREADDIR = Symbol('onreaddir') const PIPE = Symbol('pipe') const ENTRY = Symbol('entry') const ENTRYOPT = Symbol('entryOpt') const WRITEENTRYCLASS = Symbol('writeEntryClass') const WRITE = Symbol('write') const ONDRAIN = Symbol('ondrain') const fs = __webpack_require__(7147) const path = __webpack_require__(1017) const warner = __webpack_require__(7902) const normPath = __webpack_require__(2905) const Pack = warner(class Pack extends MiniPass { constructor (opt) { super(opt) opt = opt || Object.create(null) this.opt = opt this.file = opt.file || '' this.cwd = opt.cwd || process.cwd() this.maxReadSize = opt.maxReadSize this.preservePaths = !!opt.preservePaths this.strict = !!opt.strict this.noPax = !!opt.noPax this.prefix = normPath(opt.prefix || '') this.linkCache = opt.linkCache || new Map() this.statCache = opt.statCache || new Map() this.readdirCache = opt.readdirCache || new Map() this[WRITEENTRYCLASS] = WriteEntry if (typeof opt.onwarn === 'function') this.on('warn', opt.onwarn) this.portable = !!opt.portable this.zip = null if (opt.gzip) { if (typeof opt.gzip !== 'object') opt.gzip = {} if (this.portable) opt.gzip.portable = true this.zip = new zlib.Gzip(opt.gzip) this.zip.on('data', chunk => super.write(chunk)) this.zip.on('end', _ => super.end()) this.zip.on('drain', _ => this[ONDRAIN]()) this.on('resume', _ => this.zip.resume()) } else this.on('drain', this[ONDRAIN]) this.noDirRecurse = !!opt.noDirRecurse this.follow = !!opt.follow this.noMtime = !!opt.noMtime this.mtime = opt.mtime || null this.filter = typeof opt.filter === 'function' ? opt.filter : _ => true this[QUEUE] = new Yallist() this[JOBS] = 0 this.jobs = +opt.jobs || 4 this[PROCESSING] = false this[ENDED] = false } [WRITE] (chunk) { return super.write(chunk) } add (path) { this.write(path) return this } end (path) { if (path) this.write(path) this[ENDED] = true this[PROCESS]() return this } write (path) { if (this[ENDED]) throw new Error('write after end') if (path instanceof ReadEntry) this[ADDTARENTRY](path) else this[ADDFSENTRY](path) return this.flowing } [ADDTARENTRY] (p) { const absolute = normPath(path.resolve(this.cwd, p.path)) // in this case, we don't have to wait for the stat if (!this.filter(p.path, p)) p.resume() else { const job = new PackJob(p.path, absolute, false) job.entry = new WriteEntryTar(p, this[ENTRYOPT](job)) job.entry.on('end', _ => this[JOBDONE](job)) this[JOBS] += 1 this[QUEUE].push(job) } this[PROCESS]() } [ADDFSENTRY] (p) { const absolute = normPath(path.resolve(this.cwd, p)) this[QUEUE].push(new PackJob(p, absolute)) this[PROCESS]() } [STAT] (job) { job.pending = true this[JOBS] += 1 const stat = this.follow ? 'stat' : 'lstat' fs[stat](job.absolute, (er, stat) => { job.pending = false this[JOBS] -= 1 if (er) this.emit('error', er) else this[ONSTAT](job, stat) }) } [ONSTAT] (job, stat) { this.statCache.set(job.absolute, stat) job.stat = stat // now we have the stat, we can filter it. if (!this.filter(job.path, stat)) job.ignore = true this[PROCESS]() } [READDIR] (job) { job.pending = true this[JOBS] += 1 fs.readdir(job.absolute, (er, entries) => { job.pending = false this[JOBS] -= 1 if (er) return this.emit('error', er) this[ONREADDIR](job, entries) }) } [ONREADDIR] (job, entries) { this.readdirCache.set(job.absolute, entries) job.readdir = entries this[PROCESS]() } [PROCESS] () { if (this[PROCESSING]) return this[PROCESSING] = true for (let w = this[QUEUE].head; w !== null && this[JOBS] < this.jobs; w = w.next) { this[PROCESSJOB](w.value) if (w.value.ignore) { const p = w.next this[QUEUE].removeNode(w) w.next = p } } this[PROCESSING] = false if (this[ENDED] && !this[QUEUE].length && this[JOBS] === 0) { if (this.zip) this.zip.end(EOF) else { super.write(EOF) super.end() } } } get [CURRENT] () { return this[QUEUE] && this[QUEUE].head && this[QUEUE].head.value } [JOBDONE] (job) { this[QUEUE].shift() this[JOBS] -= 1 this[PROCESS]() } [PROCESSJOB] (job) { if (job.pending) return if (job.entry) { if (job === this[CURRENT] && !job.piped) this[PIPE](job) return } if (!job.stat) { if (this.statCache.has(job.absolute)) this[ONSTAT](job, this.statCache.get(job.absolute)) else this[STAT](job) } if (!job.stat) return // filtered out! if (job.ignore) return if (!this.noDirRecurse && job.stat.isDirectory() && !job.readdir) { if (this.readdirCache.has(job.absolute)) this[ONREADDIR](job, this.readdirCache.get(job.absolute)) else this[READDIR](job) if (!job.readdir) return } // we know it doesn't have an entry, because that got checked above job.entry = this[ENTRY](job) if (!job.entry) { job.ignore = true return } if (job === this[CURRENT] && !job.piped) this[PIPE](job) } [ENTRYOPT] (job) { return { onwarn: (code, msg, data) => this.warn(code, msg, data), noPax: this.noPax, cwd: this.cwd, absolute: job.absolute, preservePaths: this.preservePaths, maxReadSize: this.maxReadSize, strict: this.strict, portable: this.portable, linkCache: this.linkCache, statCache: this.statCache, noMtime: this.noMtime, mtime: this.mtime, prefix: this.prefix, } } [ENTRY] (job) { this[JOBS] += 1 try { return new this[WRITEENTRYCLASS](job.path, this[ENTRYOPT](job)) .on('end', () => this[JOBDONE](job)) .on('error', er => this.emit('error', er)) } catch (er) { this.emit('error', er) } } [ONDRAIN] () { if (this[CURRENT] && this[CURRENT].entry) this[CURRENT].entry.resume() } // like .pipe() but using super, because our write() is special [PIPE] (job) { job.piped = true if (job.readdir) { job.readdir.forEach(entry => { const p = job.path const base = p === './' ? '' : p.replace(/\/*$/, '/') this[ADDFSENTRY](base + entry) }) } const source = job.entry const zip = this.zip if (zip) { source.on('data', chunk => { if (!zip.write(chunk)) source.pause() }) } else { source.on('data', chunk => { if (!super.write(chunk)) source.pause() }) } } pause () { if (this.zip) this.zip.pause() return super.pause() } }) class PackSync extends Pack { constructor (opt) { super(opt) this[WRITEENTRYCLASS] = WriteEntrySync } // pause/resume are no-ops in sync streams. pause () {} resume () {} [STAT] (job) { const stat = this.follow ? 'statSync' : 'lstatSync' this[ONSTAT](job, fs[stat](job.absolute)) } [READDIR] (job, stat) { this[ONREADDIR](job, fs.readdirSync(job.absolute)) } // gotta get it all in this tick [PIPE] (job) { const source = job.entry const zip = this.zip if (job.readdir) { job.readdir.forEach(entry => { const p = job.path const base = p === './' ? '' : p.replace(/\/*$/, '/') this[ADDFSENTRY](base + entry) }) } if (zip) { source.on('data', chunk => { zip.write(chunk) }) } else { source.on('data', chunk => { super[WRITE](chunk) }) } } } Pack.Sync = PackSync module.exports = Pack /***/ }), /***/ 6824: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; // this[BUFFER] is the remainder of a chunk if we're waiting for // the full 512 bytes of a header to come in. We will Buffer.concat() // it to the next write(), which is a mem copy, but a small one. // // this[QUEUE] is a Yallist of entries that haven't been emitted // yet this can only get filled up if the user keeps write()ing after // a write() returns false, or does a write() with more than one entry // // We don't buffer chunks, we always parse them and either create an // entry, or push it into the active entry. The ReadEntry class knows // to throw data away if .ignore=true // // Shift entry off the buffer when it emits 'end', and emit 'entry' for // the next one in the list. // // At any time, we're pushing body chunks into the entry at WRITEENTRY, // and waiting for 'end' on the entry at READENTRY // // ignored entries get .resume() called on them straight away const warner = __webpack_require__(7902) const Header = __webpack_require__(7134) const EE = __webpack_require__(2361) const Yallist = __webpack_require__(4411) const maxMetaEntrySize = 1024 * 1024 const Entry = __webpack_require__(6277) const Pax = __webpack_require__(4747) const zlib = __webpack_require__(1650) const gzipHeader = Buffer.from([0x1f, 0x8b]) const STATE = Symbol('state') const WRITEENTRY = Symbol('writeEntry') const READENTRY = Symbol('readEntry') const NEXTENTRY = Symbol('nextEntry') const PROCESSENTRY = Symbol('processEntry') const EX = Symbol('extendedHeader') const GEX = Symbol('globalExtendedHeader') const META = Symbol('meta') const EMITMETA = Symbol('emitMeta') const BUFFER = Symbol('buffer') const QUEUE = Symbol('queue') const ENDED = Symbol('ended') const EMITTEDEND = Symbol('emittedEnd') const EMIT = Symbol('emit') const UNZIP = Symbol('unzip') const CONSUMECHUNK = Symbol('consumeChunk') const CONSUMECHUNKSUB = Symbol('consumeChunkSub') const CONSUMEBODY = Symbol('consumeBody') const CONSUMEMETA = Symbol('consumeMeta') const CONSUMEHEADER = Symbol('consumeHeader') const CONSUMING = Symbol('consuming') const BUFFERCONCAT = Symbol('bufferConcat') const MAYBEEND = Symbol('maybeEnd') const WRITING = Symbol('writing') const ABORTED = Symbol('aborted') const DONE = Symbol('onDone') const SAW_VALID_ENTRY = Symbol('sawValidEntry') const SAW_NULL_BLOCK = Symbol('sawNullBlock') const SAW_EOF = Symbol('sawEOF') const noop = _ => true module.exports = warner(class Parser extends EE { constructor (opt) { opt = opt || {} super(opt) this.file = opt.file || '' // set to boolean false when an entry starts. 1024 bytes of \0 // is technically a valid tarball, albeit a boring one. this[SAW_VALID_ENTRY] = null // these BADARCHIVE errors can't be detected early. listen on DONE. this.on(DONE, _ => { if (this[STATE] === 'begin' || this[SAW_VALID_ENTRY] === false) { // either less than 1 block of data, or all entries were invalid. // Either way, probably not even a tarball. this.warn('TAR_BAD_ARCHIVE', 'Unrecognized archive format') } }) if (opt.ondone) this.on(DONE, opt.ondone) else { this.on(DONE, _ => { this.emit('prefinish') this.emit('finish') this.emit('end') this.emit('close') }) } this.strict = !!opt.strict this.maxMetaEntrySize = opt.maxMetaEntrySize || maxMetaEntrySize this.filter = typeof opt.filter === 'function' ? opt.filter : noop // have to set this so that streams are ok piping into it this.writable = true this.readable = false this[QUEUE] = new Yallist() this[BUFFER] = null this[READENTRY] = null this[WRITEENTRY] = null this[STATE] = 'begin' this[META] = '' this[EX] = null this[GEX] = null this[ENDED] = false this[UNZIP] = null this[ABORTED] = false this[SAW_NULL_BLOCK] = false this[SAW_EOF] = false if (typeof opt.onwarn === 'function') this.on('warn', opt.onwarn) if (typeof opt.onentry === 'function') this.on('entry', opt.onentry) } [CONSUMEHEADER] (chunk, position) { if (this[SAW_VALID_ENTRY] === null) this[SAW_VALID_ENTRY] = false let header try { header = new Header(chunk, position, this[EX], this[GEX]) } catch (er) { return this.warn('TAR_ENTRY_INVALID', er) } if (header.nullBlock) { if (this[SAW_NULL_BLOCK]) { this[SAW_EOF] = true // ending an archive with no entries. pointless, but legal. if (this[STATE] === 'begin') this[STATE] = 'header' this[EMIT]('eof') } else { this[SAW_NULL_BLOCK] = true this[EMIT]('nullBlock') } } else { this[SAW_NULL_BLOCK] = false if (!header.cksumValid) this.warn('TAR_ENTRY_INVALID', 'checksum failure', {header}) else if (!header.path) this.warn('TAR_ENTRY_INVALID', 'path is required', {header}) else { const type = header.type if (/^(Symbolic)?Link$/.test(type) && !header.linkpath) this.warn('TAR_ENTRY_INVALID', 'linkpath required', {header}) else if (!/^(Symbolic)?Link$/.test(type) && header.linkpath) this.warn('TAR_ENTRY_INVALID', 'linkpath forbidden', {header}) else { const entry = this[WRITEENTRY] = new Entry(header, this[EX], this[GEX]) // we do this for meta & ignored entries as well, because they // are still valid tar, or else we wouldn't know to ignore them if (!this[SAW_VALID_ENTRY]) { if (entry.remain) { // this might be the one! const onend = () => { if (!entry.invalid) this[SAW_VALID_ENTRY] = true } entry.on('end', onend) } else this[SAW_VALID_ENTRY] = true } if (entry.meta) { if (entry.size > this.maxMetaEntrySize) { entry.ignore = true this[EMIT]('ignoredEntry', entry) this[STATE] = 'ignore' entry.resume() } else if (entry.size > 0) { this[META] = '' entry.on('data', c => this[META] += c) this[STATE] = 'meta' } } else { this[EX] = null entry.ignore = entry.ignore || !this.filter(entry.path, entry) if (entry.ignore) { // probably valid, just not something we care about this[EMIT]('ignoredEntry', entry) this[STATE] = entry.remain ? 'ignore' : 'header' entry.resume() } else { if (entry.remain) this[STATE] = 'body' else { this[STATE] = 'header' entry.end() } if (!this[READENTRY]) { this[QUEUE].push(entry) this[NEXTENTRY]() } else this[QUEUE].push(entry) } } } } } } [PROCESSENTRY] (entry) { let go = true if (!entry) { this[READENTRY] = null go = false } else if (Array.isArray(entry)) this.emit.apply(this, entry) else { this[READENTRY] = entry this.emit('entry', entry) if (!entry.emittedEnd) { entry.on('end', _ => this[NEXTENTRY]()) go = false } } return go } [NEXTENTRY] () { do {} while (this[PROCESSENTRY](this[QUEUE].shift())) if (!this[QUEUE].length) { // At this point, there's nothing in the queue, but we may have an // entry which is being consumed (readEntry). // If we don't, then we definitely can handle more data. // If we do, and either it's flowing, or it has never had any data // written to it, then it needs more. // The only other possibility is that it has returned false from a // write() call, so we wait for the next drain to continue. const re = this[READENTRY] const drainNow = !re || re.flowing || re.size === re.remain if (drainNow) { if (!this[WRITING]) this.emit('drain') } else re.once('drain', _ => this.emit('drain')) } } [CONSUMEBODY] (chunk, position) { // write up to but no more than writeEntry.blockRemain const entry = this[WRITEENTRY] const br = entry.blockRemain const c = (br >= chunk.length && position === 0) ? chunk : chunk.slice(position, position + br) entry.write(c) if (!entry.blockRemain) { this[STATE] = 'header' this[WRITEENTRY] = null entry.end() } return c.length } [CONSUMEMETA] (chunk, position) { const entry = this[WRITEENTRY] const ret = this[CONSUMEBODY](chunk, position) // if we finished, then the entry is reset if (!this[WRITEENTRY]) this[EMITMETA](entry) return ret } [EMIT] (ev, data, extra) { if (!this[QUEUE].length && !this[READENTRY]) this.emit(ev, data, extra) else this[QUEUE].push([ev, data, extra]) } [EMITMETA] (entry) { this[EMIT]('meta', this[META]) switch (entry.type) { case 'ExtendedHeader': case 'OldExtendedHeader': this[EX] = Pax.parse(this[META], this[EX], false) break case 'GlobalExtendedHeader': this[GEX] = Pax.parse(this[META], this[GEX], true) break case 'NextFileHasLongPath': case 'OldGnuLongPath': this[EX] = this[EX] || Object.create(null) this[EX].path = this[META].replace(/\0.*/, '') break case 'NextFileHasLongLinkpath': this[EX] = this[EX] || Object.create(null) this[EX].linkpath = this[META].replace(/\0.*/, '') break /* istanbul ignore next */ default: throw new Error('unknown meta: ' + entry.type) } } abort (error) { this[ABORTED] = true this.emit('abort', error) // always throws, even in non-strict mode this.warn('TAR_ABORT', error, { recoverable: false }) } write (chunk) { if (this[ABORTED]) return // first write, might be gzipped if (this[UNZIP] === null && chunk) { if (this[BUFFER]) { chunk = Buffer.concat([this[BUFFER], chunk]) this[BUFFER] = null } if (chunk.length < gzipHeader.length) { this[BUFFER] = chunk return true } for (let i = 0; this[UNZIP] === null && i < gzipHeader.length; i++) { if (chunk[i] !== gzipHeader[i]) this[UNZIP] = false } if (this[UNZIP] === null) { const ended = this[ENDED] this[ENDED] = false this[UNZIP] = new zlib.Unzip() this[UNZIP].on('data', chunk => this[CONSUMECHUNK](chunk)) this[UNZIP].on('error', er => this.abort(er)) this[UNZIP].on('end', _ => { this[ENDED] = true this[CONSUMECHUNK]() }) this[WRITING] = true const ret = this[UNZIP][ended ? 'end' : 'write'](chunk) this[WRITING] = false return ret } } this[WRITING] = true if (this[UNZIP]) this[UNZIP].write(chunk) else this[CONSUMECHUNK](chunk) this[WRITING] = false // return false if there's a queue, or if the current entry isn't flowing const ret = this[QUEUE].length ? false : this[READENTRY] ? this[READENTRY].flowing : true // if we have no queue, then that means a clogged READENTRY if (!ret && !this[QUEUE].length) this[READENTRY].once('drain', _ => this.emit('drain')) return ret } [BUFFERCONCAT] (c) { if (c && !this[ABORTED]) this[BUFFER] = this[BUFFER] ? Buffer.concat([this[BUFFER], c]) : c } [MAYBEEND] () { if (this[ENDED] && !this[EMITTEDEND] && !this[ABORTED] && !this[CONSUMING]) { this[EMITTEDEND] = true const entry = this[WRITEENTRY] if (entry && entry.blockRemain) { // truncated, likely a damaged file const have = this[BUFFER] ? this[BUFFER].length : 0 this.warn('TAR_BAD_ARCHIVE', `Truncated input (needed ${ entry.blockRemain} more bytes, only ${have} available)`, {entry}) if (this[BUFFER]) entry.write(this[BUFFER]) entry.end() } this[EMIT](DONE) } } [CONSUMECHUNK] (chunk) { if (this[CONSUMING]) this[BUFFERCONCAT](chunk) else if (!chunk && !this[BUFFER]) this[MAYBEEND]() else { this[CONSUMING] = true if (this[BUFFER]) { this[BUFFERCONCAT](chunk) const c = this[BUFFER] this[BUFFER] = null this[CONSUMECHUNKSUB](c) } else this[CONSUMECHUNKSUB](chunk) while (this[BUFFER] && this[BUFFER].length >= 512 && !this[ABORTED] && !this[SAW_EOF]) { const c = this[BUFFER] this[BUFFER] = null this[CONSUMECHUNKSUB](c) } this[CONSUMING] = false } if (!this[BUFFER] || this[ENDED]) this[MAYBEEND]() } [CONSUMECHUNKSUB] (chunk) { // we know that we are in CONSUMING mode, so anything written goes into // the buffer. Advance the position and put any remainder in the buffer. let position = 0 const length = chunk.length while (position + 512 <= length && !this[ABORTED] && !this[SAW_EOF]) { switch (this[STATE]) { case 'begin': case 'header': this[CONSUMEHEADER](chunk, position) position += 512 break case 'ignore': case 'body': position += this[CONSUMEBODY](chunk, position) break case 'meta': position += this[CONSUMEMETA](chunk, position) break /* istanbul ignore next */ default: throw new Error('invalid state: ' + this[STATE]) } } if (position < length) { if (this[BUFFER]) this[BUFFER] = Buffer.concat([chunk.slice(position), this[BUFFER]]) else this[BUFFER] = chunk.slice(position) } } end (chunk) { if (!this[ABORTED]) { if (this[UNZIP]) this[UNZIP].end(chunk) else { this[ENDED] = true this.write(chunk) } } } }) /***/ }), /***/ 10: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // A path exclusive reservation system // reserve([list, of, paths], fn) // When the fn is first in line for all its paths, it // is called with a cb that clears the reservation. // // Used by async unpack to avoid clobbering paths in use, // while still allowing maximal safe parallelization. const assert = __webpack_require__(9491) const normalize = __webpack_require__(1946) const stripSlashes = __webpack_require__(4922) const { join } = __webpack_require__(1017) const platform = process.env.TESTING_TAR_FAKE_PLATFORM || process.platform const isWindows = platform === 'win32' module.exports = () => { // path => [function or Set] // A Set object means a directory reservation // A fn is a direct reservation on that path const queues = new Map() // fn => {paths:[path,...], dirs:[path, ...]} const reservations = new Map() // return a set of parent dirs for a given path // '/a/b/c/d' -> ['/', '/a', '/a/b', '/a/b/c', '/a/b/c/d'] const getDirs = path => { const dirs = path.split('/').slice(0, -1).reduce((set, path) => { if (set.length) path = join(set[set.length - 1], path) set.push(path || '/') return set }, []) return dirs } // functions currently running const running = new Set() // return the queues for each path the function cares about // fn => {paths, dirs} const getQueues = fn => { const res = reservations.get(fn) /* istanbul ignore if - unpossible */ if (!res) throw new Error('function does not have any path reservations') return { paths: res.paths.map(path => queues.get(path)), dirs: [...res.dirs].map(path => queues.get(path)), } } // check if fn is first in line for all its paths, and is // included in the first set for all its dir queues const check = fn => { const {paths, dirs} = getQueues(fn) return paths.every(q => q[0] === fn) && dirs.every(q => q[0] instanceof Set && q[0].has(fn)) } // run the function if it's first in line and not already running const run = fn => { if (running.has(fn) || !check(fn)) return false running.add(fn) fn(() => clear(fn)) return true } const clear = fn => { if (!running.has(fn)) return false const { paths, dirs } = reservations.get(fn) const next = new Set() paths.forEach(path => { const q = queues.get(path) assert.equal(q[0], fn) if (q.length === 1) queues.delete(path) else { q.shift() if (typeof q[0] === 'function') next.add(q[0]) else q[0].forEach(fn => next.add(fn)) } }) dirs.forEach(dir => { const q = queues.get(dir) assert(q[0] instanceof Set) if (q[0].size === 1 && q.length === 1) queues.delete(dir) else if (q[0].size === 1) { q.shift() // must be a function or else the Set would've been reused next.add(q[0]) } else q[0].delete(fn) }) running.delete(fn) next.forEach(fn => run(fn)) return true } const reserve = (paths, fn) => { // collide on matches across case and unicode normalization // On windows, thanks to the magic of 8.3 shortnames, it is fundamentally // impossible to determine whether two paths refer to the same thing on // disk, without asking the kernel for a shortname. // So, we just pretend that every path matches every other path here, // effectively removing all parallelization on windows. paths = isWindows ? ['win32 parallelization disabled'] : paths.map(p => { // don't need normPath, because we skip this entirely for windows return normalize(stripSlashes(join(p))).toLowerCase() }) const dirs = new Set( paths.map(path => getDirs(path)).reduce((a, b) => a.concat(b)) ) reservations.set(fn, {dirs, paths}) paths.forEach(path => { const q = queues.get(path) if (!q) queues.set(path, [fn]) else q.push(fn) }) dirs.forEach(dir => { const q = queues.get(dir) if (!q) queues.set(dir, [new Set([fn])]) else if (q[q.length - 1] instanceof Set) q[q.length - 1].add(fn) else q.push(new Set([fn])) }) return run(fn) } return { check, reserve } } /***/ }), /***/ 4747: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const Header = __webpack_require__(7134) const path = __webpack_require__(1017) class Pax { constructor (obj, global) { this.atime = obj.atime || null this.charset = obj.charset || null this.comment = obj.comment || null this.ctime = obj.ctime || null this.gid = obj.gid || null this.gname = obj.gname || null this.linkpath = obj.linkpath || null this.mtime = obj.mtime || null this.path = obj.path || null this.size = obj.size || null this.uid = obj.uid || null this.uname = obj.uname || null this.dev = obj.dev || null this.ino = obj.ino || null this.nlink = obj.nlink || null this.global = global || false } encode () { const body = this.encodeBody() if (body === '') return null const bodyLen = Buffer.byteLength(body) // round up to 512 bytes // add 512 for header const bufLen = 512 * Math.ceil(1 + bodyLen / 512) const buf = Buffer.allocUnsafe(bufLen) // 0-fill the header section, it might not hit every field for (let i = 0; i < 512; i++) buf[i] = 0 new Header({ // XXX split the path // then the path should be PaxHeader + basename, but less than 99, // prepend with the dirname path: ('PaxHeader/' + path.basename(this.path)).slice(0, 99), mode: this.mode || 0o644, uid: this.uid || null, gid: this.gid || null, size: bodyLen, mtime: this.mtime || null, type: this.global ? 'GlobalExtendedHeader' : 'ExtendedHeader', linkpath: '', uname: this.uname || '', gname: this.gname || '', devmaj: 0, devmin: 0, atime: this.atime || null, ctime: this.ctime || null, }).encode(buf) buf.write(body, 512, bodyLen, 'utf8') // null pad after the body for (let i = bodyLen + 512; i < buf.length; i++) buf[i] = 0 return buf } encodeBody () { return ( this.encodeField('path') + this.encodeField('ctime') + this.encodeField('atime') + this.encodeField('dev') + this.encodeField('ino') + this.encodeField('nlink') + this.encodeField('charset') + this.encodeField('comment') + this.encodeField('gid') + this.encodeField('gname') + this.encodeField('linkpath') + this.encodeField('mtime') + this.encodeField('size') + this.encodeField('uid') + this.encodeField('uname') ) } encodeField (field) { if (this[field] === null || this[field] === undefined) return '' const v = this[field] instanceof Date ? this[field].getTime() / 1000 : this[field] const s = ' ' + (field === 'dev' || field === 'ino' || field === 'nlink' ? 'SCHILY.' : '') + field + '=' + v + '\n' const byteLen = Buffer.byteLength(s) // the digits includes the length of the digits in ascii base-10 // so if it's 9 characters, then adding 1 for the 9 makes it 10 // which makes it 11 chars. let digits = Math.floor(Math.log(byteLen) / Math.log(10)) + 1 if (byteLen + digits >= Math.pow(10, digits)) digits += 1 const len = digits + byteLen return len + s } } Pax.parse = (string, ex, g) => new Pax(merge(parseKV(string), ex), g) const merge = (a, b) => b ? Object.keys(a).reduce((s, k) => (s[k] = a[k], s), b) : a const parseKV = string => string .replace(/\n$/, '') .split('\n') .reduce(parseKVLine, Object.create(null)) const parseKVLine = (set, line) => { const n = parseInt(line, 10) // XXX Values with \n in them will fail this. // Refactor to not be a naive line-by-line parse. if (n !== Buffer.byteLength(line) + 1) return set line = line.substr((n + ' ').length) const kv = line.split('=') const k = kv.shift().replace(/^SCHILY\.(dev|ino|nlink)/, '$1') if (!k) return set const v = kv.join('=') set[k] = /^([A-Z]+\.)?([mac]|birth|creation)time$/.test(k) ? new Date(v * 1000) : /^[0-9]+$/.test(v) ? +v : v return set } module.exports = Pax /***/ }), /***/ 6277: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const MiniPass = __webpack_require__(5736) const normPath = __webpack_require__(2905) const SLURP = Symbol('slurp') module.exports = class ReadEntry extends MiniPass { constructor (header, ex, gex) { super() // read entries always start life paused. this is to avoid the // situation where Minipass's auto-ending empty streams results // in an entry ending before we're ready for it. this.pause() this.extended = ex this.globalExtended = gex this.header = header this.startBlockSize = 512 * Math.ceil(header.size / 512) this.blockRemain = this.startBlockSize this.remain = header.size this.type = header.type this.meta = false this.ignore = false switch (this.type) { case 'File': case 'OldFile': case 'Link': case 'SymbolicLink': case 'CharacterDevice': case 'BlockDevice': case 'Directory': case 'FIFO': case 'ContiguousFile': case 'GNUDumpDir': break case 'NextFileHasLongLinkpath': case 'NextFileHasLongPath': case 'OldGnuLongPath': case 'GlobalExtendedHeader': case 'ExtendedHeader': case 'OldExtendedHeader': this.meta = true break // NOTE: gnutar and bsdtar treat unrecognized types as 'File' // it may be worth doing the same, but with a warning. default: this.ignore = true } this.path = normPath(header.path) this.mode = header.mode if (this.mode) this.mode = this.mode & 0o7777 this.uid = header.uid this.gid = header.gid this.uname = header.uname this.gname = header.gname this.size = header.size this.mtime = header.mtime this.atime = header.atime this.ctime = header.ctime this.linkpath = normPath(header.linkpath) this.uname = header.uname this.gname = header.gname if (ex) this[SLURP](ex) if (gex) this[SLURP](gex, true) } write (data) { const writeLen = data.length if (writeLen > this.blockRemain) throw new Error('writing more to entry than is appropriate') const r = this.remain const br = this.blockRemain this.remain = Math.max(0, r - writeLen) this.blockRemain = Math.max(0, br - writeLen) if (this.ignore) return true if (r >= writeLen) return super.write(data) // r < writeLen return super.write(data.slice(0, r)) } [SLURP] (ex, global) { for (const k in ex) { // we slurp in everything except for the path attribute in // a global extended header, because that's weird. if (ex[k] !== null && ex[k] !== undefined && !(global && k === 'path')) this[k] = k === 'path' || k === 'linkpath' ? normPath(ex[k]) : ex[k] } } } /***/ }), /***/ 1746: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; // tar -r const hlo = __webpack_require__(2093) const Pack = __webpack_require__(8042) const fs = __webpack_require__(7147) const fsm = __webpack_require__(292) const t = __webpack_require__(6473) const path = __webpack_require__(1017) // starting at the head of the file, read a Header // If the checksum is invalid, that's our position to start writing // If it is, jump forward by the specified size (round up to 512) // and try again. // Write the new Pack stream starting there. const Header = __webpack_require__(7134) module.exports = (opt_, files, cb) => { const opt = hlo(opt_) if (!opt.file) throw new TypeError('file is required') if (opt.gzip) throw new TypeError('cannot append to compressed archives') if (!files || !Array.isArray(files) || !files.length) throw new TypeError('no files or directories specified') files = Array.from(files) return opt.sync ? replaceSync(opt, files) : replace(opt, files, cb) } const replaceSync = (opt, files) => { const p = new Pack.Sync(opt) let threw = true let fd let position try { try { fd = fs.openSync(opt.file, 'r+') } catch (er) { if (er.code === 'ENOENT') fd = fs.openSync(opt.file, 'w+') else throw er } const st = fs.fstatSync(fd) const headBuf = Buffer.alloc(512) POSITION: for (position = 0; position < st.size; position += 512) { for (let bufPos = 0, bytes = 0; bufPos < 512; bufPos += bytes) { bytes = fs.readSync( fd, headBuf, bufPos, headBuf.length - bufPos, position + bufPos ) if (position === 0 && headBuf[0] === 0x1f && headBuf[1] === 0x8b) throw new Error('cannot append to compressed archives') if (!bytes) break POSITION } const h = new Header(headBuf) if (!h.cksumValid) break const entryBlockSize = 512 * Math.ceil(h.size / 512) if (position + entryBlockSize + 512 > st.size) break // the 512 for the header we just parsed will be added as well // also jump ahead all the blocks for the body position += entryBlockSize if (opt.mtimeCache) opt.mtimeCache.set(h.path, h.mtime) } threw = false streamSync(opt, p, position, fd, files) } finally { if (threw) { try { fs.closeSync(fd) } catch (er) {} } } } const streamSync = (opt, p, position, fd, files) => { const stream = new fsm.WriteStreamSync(opt.file, { fd: fd, start: position, }) p.pipe(stream) addFilesSync(p, files) } const replace = (opt, files, cb) => { files = Array.from(files) const p = new Pack(opt) const getPos = (fd, size, cb_) => { const cb = (er, pos) => { if (er) fs.close(fd, _ => cb_(er)) else cb_(null, pos) } let position = 0 if (size === 0) return cb(null, 0) let bufPos = 0 const headBuf = Buffer.alloc(512) const onread = (er, bytes) => { if (er) return cb(er) bufPos += bytes if (bufPos < 512 && bytes) { return fs.read( fd, headBuf, bufPos, headBuf.length - bufPos, position + bufPos, onread ) } if (position === 0 && headBuf[0] === 0x1f && headBuf[1] === 0x8b) return cb(new Error('cannot append to compressed archives')) // truncated header if (bufPos < 512) return cb(null, position) const h = new Header(headBuf) if (!h.cksumValid) return cb(null, position) const entryBlockSize = 512 * Math.ceil(h.size / 512) if (position + entryBlockSize + 512 > size) return cb(null, position) position += entryBlockSize + 512 if (position >= size) return cb(null, position) if (opt.mtimeCache) opt.mtimeCache.set(h.path, h.mtime) bufPos = 0 fs.read(fd, headBuf, 0, 512, position, onread) } fs.read(fd, headBuf, 0, 512, position, onread) } const promise = new Promise((resolve, reject) => { p.on('error', reject) let flag = 'r+' const onopen = (er, fd) => { if (er && er.code === 'ENOENT' && flag === 'r+') { flag = 'w+' return fs.open(opt.file, flag, onopen) } if (er) return reject(er) fs.fstat(fd, (er, st) => { if (er) return fs.close(fd, () => reject(er)) getPos(fd, st.size, (er, position) => { if (er) return reject(er) const stream = new fsm.WriteStream(opt.file, { fd: fd, start: position, }) p.pipe(stream) stream.on('error', reject) stream.on('close', resolve) addFilesAsync(p, files) }) }) } fs.open(opt.file, flag, onopen) }) return cb ? promise.then(cb, cb) : promise } const addFilesSync = (p, files) => { files.forEach(file => { if (file.charAt(0) === '@') { t({ file: path.resolve(p.cwd, file.substr(1)), sync: true, noResume: true, onentry: entry => p.add(entry), }) } else p.add(file) }) p.end() } const addFilesAsync = (p, files) => { while (files.length) { const file = files.shift() if (file.charAt(0) === '@') { return t({ file: path.resolve(p.cwd, file.substr(1)), noResume: true, onentry: entry => p.add(entry), }).then(_ => addFilesAsync(p, files)) } else p.add(file) } p.end() } /***/ }), /***/ 2214: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // unix absolute paths are also absolute on win32, so we use this for both const { isAbsolute, parse } = (__webpack_require__(1017).win32) // returns [root, stripped] // Note that windows will think that //x/y/z/a has a "root" of //x/y, and in // those cases, we want to sanitize it to x/y/z/a, not z/a, so we strip / // explicitly if it's the first character. // drive-specific relative paths on Windows get their root stripped off even // though they are not absolute, so `c:../foo` becomes ['c:', '../foo'] module.exports = path => { let r = '' let parsed = parse(path) while (isAbsolute(path) || parsed.root) { // windows will think that //x/y/z has a "root" of //x/y/ // but strip the //?/C:/ off of //?/C:/path const root = path.charAt(0) === '/' && path.slice(0, 4) !== '//?/' ? '/' : parsed.root path = path.substr(root.length) r += root parsed = parse(path) } return [r, path] } /***/ }), /***/ 4922: /***/ ((module) => { // warning: extremely hot code path. // This has been meticulously optimized for use // within npm install on large package trees. // Do not edit without careful benchmarking. module.exports = str => { let i = str.length - 1 let slashesStart = -1 while (i > -1 && str.charAt(i) === '/') { slashesStart = i i-- } return slashesStart === -1 ? str : str.slice(0, slashesStart) } /***/ }), /***/ 4402: /***/ ((__unused_webpack_module, exports) => { "use strict"; // map types from key to human-friendly name exports.name = new Map([ ['0', 'File'], // same as File ['', 'OldFile'], ['1', 'Link'], ['2', 'SymbolicLink'], // Devices and FIFOs aren't fully supported // they are parsed, but skipped when unpacking ['3', 'CharacterDevice'], ['4', 'BlockDevice'], ['5', 'Directory'], ['6', 'FIFO'], // same as File ['7', 'ContiguousFile'], // pax headers ['g', 'GlobalExtendedHeader'], ['x', 'ExtendedHeader'], // vendor-specific stuff // skip ['A', 'SolarisACL'], // like 5, but with data, which should be skipped ['D', 'GNUDumpDir'], // metadata only, skip ['I', 'Inode'], // data = link path of next file ['K', 'NextFileHasLongLinkpath'], // data = path of next file ['L', 'NextFileHasLongPath'], // skip ['M', 'ContinuationFile'], // like L ['N', 'OldGnuLongPath'], // skip ['S', 'SparseFile'], // skip ['V', 'TapeVolumeHeader'], // like x ['X', 'OldExtendedHeader'], ]) // map the other direction exports.code = new Map(Array.from(exports.name).map(kv => [kv[1], kv[0]])) /***/ }), /***/ 2699: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; // the PEND/UNPEND stuff tracks whether we're ready to emit end/close yet. // but the path reservations are required to avoid race conditions where // parallelized unpack ops may mess with one another, due to dependencies // (like a Link depending on its target) or destructive operations (like // clobbering an fs object to create one of a different type.) const assert = __webpack_require__(9491) const Parser = __webpack_require__(6824) const fs = __webpack_require__(7147) const fsm = __webpack_require__(292) const path = __webpack_require__(1017) const mkdir = __webpack_require__(3248) const wc = __webpack_require__(619) const pathReservations = __webpack_require__(10) const stripAbsolutePath = __webpack_require__(2214) const normPath = __webpack_require__(2905) const stripSlash = __webpack_require__(4922) const normalize = __webpack_require__(1946) const ONENTRY = Symbol('onEntry') const CHECKFS = Symbol('checkFs') const CHECKFS2 = Symbol('checkFs2') const PRUNECACHE = Symbol('pruneCache') const ISREUSABLE = Symbol('isReusable') const MAKEFS = Symbol('makeFs') const FILE = Symbol('file') const DIRECTORY = Symbol('directory') const LINK = Symbol('link') const SYMLINK = Symbol('symlink') const HARDLINK = Symbol('hardlink') const UNSUPPORTED = Symbol('unsupported') const CHECKPATH = Symbol('checkPath') const MKDIR = Symbol('mkdir') const ONERROR = Symbol('onError') const PENDING = Symbol('pending') const PEND = Symbol('pend') const UNPEND = Symbol('unpend') const ENDED = Symbol('ended') const MAYBECLOSE = Symbol('maybeClose') const SKIP = Symbol('skip') const DOCHOWN = Symbol('doChown') const UID = Symbol('uid') const GID = Symbol('gid') const CHECKED_CWD = Symbol('checkedCwd') const crypto = __webpack_require__(6113) const getFlag = __webpack_require__(5879) const platform = process.env.TESTING_TAR_FAKE_PLATFORM || process.platform const isWindows = platform === 'win32' // Unlinks on Windows are not atomic. // // This means that if you have a file entry, followed by another // file entry with an identical name, and you cannot re-use the file // (because it's a hardlink, or because unlink:true is set, or it's // Windows, which does not have useful nlink values), then the unlink // will be committed to the disk AFTER the new file has been written // over the old one, deleting the new file. // // To work around this, on Windows systems, we rename the file and then // delete the renamed file. It's a sloppy kludge, but frankly, I do not // know of a better way to do this, given windows' non-atomic unlink // semantics. // // See: https://github.com/npm/node-tar/issues/183 /* istanbul ignore next */ const unlinkFile = (path, cb) => { if (!isWindows) return fs.unlink(path, cb) const name = path + '.DELETE.' + crypto.randomBytes(16).toString('hex') fs.rename(path, name, er => { if (er) return cb(er) fs.unlink(name, cb) }) } /* istanbul ignore next */ const unlinkFileSync = path => { if (!isWindows) return fs.unlinkSync(path) const name = path + '.DELETE.' + crypto.randomBytes(16).toString('hex') fs.renameSync(path, name) fs.unlinkSync(name) } // this.gid, entry.gid, this.processUid const uint32 = (a, b, c) => a === a >>> 0 ? a : b === b >>> 0 ? b : c // clear the cache if it's a case-insensitive unicode-squashing match. // we can't know if the current file system is case-sensitive or supports // unicode fully, so we check for similarity on the maximally compatible // representation. Err on the side of pruning, since all it's doing is // preventing lstats, and it's not the end of the world if we get a false // positive. // Note that on windows, we always drop the entire cache whenever a // symbolic link is encountered, because 8.3 filenames are impossible // to reason about, and collisions are hazards rather than just failures. const cacheKeyNormalize = path => normalize(stripSlash(normPath(path))) .toLowerCase() const pruneCache = (cache, abs) => { abs = cacheKeyNormalize(abs) for (const path of cache.keys()) { const pnorm = cacheKeyNormalize(path) if (pnorm === abs || pnorm.indexOf(abs + '/') === 0) cache.delete(path) } } const dropCache = cache => { for (const key of cache.keys()) cache.delete(key) } class Unpack extends Parser { constructor (opt) { if (!opt) opt = {} opt.ondone = _ => { this[ENDED] = true this[MAYBECLOSE]() } super(opt) this[CHECKED_CWD] = false this.reservations = pathReservations() this.transform = typeof opt.transform === 'function' ? opt.transform : null this.writable = true this.readable = false this[PENDING] = 0 this[ENDED] = false this.dirCache = opt.dirCache || new Map() if (typeof opt.uid === 'number' || typeof opt.gid === 'number') { // need both or neither if (typeof opt.uid !== 'number' || typeof opt.gid !== 'number') throw new TypeError('cannot set owner without number uid and gid') if (opt.preserveOwner) { throw new TypeError( 'cannot preserve owner in archive and also set owner explicitly') } this.uid = opt.uid this.gid = opt.gid this.setOwner = true } else { this.uid = null this.gid = null this.setOwner = false } // default true for root if (opt.preserveOwner === undefined && typeof opt.uid !== 'number') this.preserveOwner = process.getuid && process.getuid() === 0 else this.preserveOwner = !!opt.preserveOwner this.processUid = (this.preserveOwner || this.setOwner) && process.getuid ? process.getuid() : null this.processGid = (this.preserveOwner || this.setOwner) && process.getgid ? process.getgid() : null // mostly just for testing, but useful in some cases. // Forcibly trigger a chown on every entry, no matter what this.forceChown = opt.forceChown === true // turn > this[ONENTRY](entry)) } // a bad or damaged archive is a warning for Parser, but an error // when extracting. Mark those errors as unrecoverable, because // the Unpack contract cannot be met. warn (code, msg, data = {}) { if (code === 'TAR_BAD_ARCHIVE' || code === 'TAR_ABORT') data.recoverable = false return super.warn(code, msg, data) } [MAYBECLOSE] () { if (this[ENDED] && this[PENDING] === 0) { this.emit('prefinish') this.emit('finish') this.emit('end') this.emit('close') } } [CHECKPATH] (entry) { if (this.strip) { const parts = normPath(entry.path).split('/') if (parts.length < this.strip) return false entry.path = parts.slice(this.strip).join('/') if (entry.type === 'Link') { const linkparts = normPath(entry.linkpath).split('/') if (linkparts.length >= this.strip) entry.linkpath = linkparts.slice(this.strip).join('/') else return false } } if (!this.preservePaths) { const p = normPath(entry.path) const parts = p.split('/') if (parts.includes('..') || isWindows && /^[a-z]:\.\.$/i.test(parts[0])) { this.warn('TAR_ENTRY_ERROR', `path contains '..'`, { entry, path: p, }) return false } // strip off the root const [root, stripped] = stripAbsolutePath(p) if (root) { entry.path = stripped this.warn('TAR_ENTRY_INFO', `stripping ${root} from absolute path`, { entry, path: p, }) } } if (path.isAbsolute(entry.path)) entry.absolute = normPath(path.resolve(entry.path)) else entry.absolute = normPath(path.resolve(this.cwd, entry.path)) // if we somehow ended up with a path that escapes the cwd, and we are // not in preservePaths mode, then something is fishy! This should have // been prevented above, so ignore this for coverage. /* istanbul ignore if - defense in depth */ if (!this.preservePaths && entry.absolute.indexOf(this.cwd + '/') !== 0 && entry.absolute !== this.cwd) { this.warn('TAR_ENTRY_ERROR', 'path escaped extraction target', { entry, path: normPath(entry.path), resolvedPath: entry.absolute, cwd: this.cwd, }) return false } // an archive can set properties on the extraction directory, but it // may not replace the cwd with a different kind of thing entirely. if (entry.absolute === this.cwd && entry.type !== 'Directory' && entry.type !== 'GNUDumpDir') return false // only encode : chars that aren't drive letter indicators if (this.win32) { const { root: aRoot } = path.win32.parse(entry.absolute) entry.absolute = aRoot + wc.encode(entry.absolute.substr(aRoot.length)) const { root: pRoot } = path.win32.parse(entry.path) entry.path = pRoot + wc.encode(entry.path.substr(pRoot.length)) } return true } [ONENTRY] (entry) { if (!this[CHECKPATH](entry)) return entry.resume() assert.equal(typeof entry.absolute, 'string') switch (entry.type) { case 'Directory': case 'GNUDumpDir': if (entry.mode) entry.mode = entry.mode | 0o700 case 'File': case 'OldFile': case 'ContiguousFile': case 'Link': case 'SymbolicLink': return this[CHECKFS](entry) case 'CharacterDevice': case 'BlockDevice': case 'FIFO': default: return this[UNSUPPORTED](entry) } } [ONERROR] (er, entry) { // Cwd has to exist, or else nothing works. That's serious. // Other errors are warnings, which raise the error in strict // mode, but otherwise continue on. if (er.name === 'CwdError') this.emit('error', er) else { this.warn('TAR_ENTRY_ERROR', er, {entry}) this[UNPEND]() entry.resume() } } [MKDIR] (dir, mode, cb) { mkdir(normPath(dir), { uid: this.uid, gid: this.gid, processUid: this.processUid, processGid: this.processGid, umask: this.processUmask, preserve: this.preservePaths, unlink: this.unlink, cache: this.dirCache, cwd: this.cwd, mode: mode, noChmod: this.noChmod, }, cb) } [DOCHOWN] (entry) { // in preserve owner mode, chown if the entry doesn't match process // in set owner mode, chown if setting doesn't match process return this.forceChown || this.preserveOwner && (typeof entry.uid === 'number' && entry.uid !== this.processUid || typeof entry.gid === 'number' && entry.gid !== this.processGid) || (typeof this.uid === 'number' && this.uid !== this.processUid || typeof this.gid === 'number' && this.gid !== this.processGid) } [UID] (entry) { return uint32(this.uid, entry.uid, this.processUid) } [GID] (entry) { return uint32(this.gid, entry.gid, this.processGid) } [FILE] (entry, fullyDone) { const mode = entry.mode & 0o7777 || this.fmode const stream = new fsm.WriteStream(entry.absolute, { flags: getFlag(entry.size), mode: mode, autoClose: false, }) stream.on('error', er => { if (stream.fd) fs.close(stream.fd, () => {}) // flush all the data out so that we aren't left hanging // if the error wasn't actually fatal. otherwise the parse // is blocked, and we never proceed. stream.write = () => true this[ONERROR](er, entry) fullyDone() }) let actions = 1 const done = er => { if (er) { /* istanbul ignore else - we should always have a fd by now */ if (stream.fd) fs.close(stream.fd, () => {}) this[ONERROR](er, entry) fullyDone() return } if (--actions === 0) { fs.close(stream.fd, er => { if (er) this[ONERROR](er, entry) else this[UNPEND]() fullyDone() }) } } stream.on('finish', _ => { // if futimes fails, try utimes // if utimes fails, fail with the original error // same for fchown/chown const abs = entry.absolute const fd = stream.fd if (entry.mtime && !this.noMtime) { actions++ const atime = entry.atime || new Date() const mtime = entry.mtime fs.futimes(fd, atime, mtime, er => er ? fs.utimes(abs, atime, mtime, er2 => done(er2 && er)) : done()) } if (this[DOCHOWN](entry)) { actions++ const uid = this[UID](entry) const gid = this[GID](entry) fs.fchown(fd, uid, gid, er => er ? fs.chown(abs, uid, gid, er2 => done(er2 && er)) : done()) } done() }) const tx = this.transform ? this.transform(entry) || entry : entry if (tx !== entry) { tx.on('error', er => { this[ONERROR](er, entry) fullyDone() }) entry.pipe(tx) } tx.pipe(stream) } [DIRECTORY] (entry, fullyDone) { const mode = entry.mode & 0o7777 || this.dmode this[MKDIR](entry.absolute, mode, er => { if (er) { this[ONERROR](er, entry) fullyDone() return } let actions = 1 const done = _ => { if (--actions === 0) { fullyDone() this[UNPEND]() entry.resume() } } if (entry.mtime && !this.noMtime) { actions++ fs.utimes(entry.absolute, entry.atime || new Date(), entry.mtime, done) } if (this[DOCHOWN](entry)) { actions++ fs.chown(entry.absolute, this[UID](entry), this[GID](entry), done) } done() }) } [UNSUPPORTED] (entry) { entry.unsupported = true this.warn('TAR_ENTRY_UNSUPPORTED', `unsupported entry type: ${entry.type}`, {entry}) entry.resume() } [SYMLINK] (entry, done) { this[LINK](entry, entry.linkpath, 'symlink', done) } [HARDLINK] (entry, done) { const linkpath = normPath(path.resolve(this.cwd, entry.linkpath)) this[LINK](entry, linkpath, 'link', done) } [PEND] () { this[PENDING]++ } [UNPEND] () { this[PENDING]-- this[MAYBECLOSE]() } [SKIP] (entry) { this[UNPEND]() entry.resume() } // Check if we can reuse an existing filesystem entry safely and // overwrite it, rather than unlinking and recreating // Windows doesn't report a useful nlink, so we just never reuse entries [ISREUSABLE] (entry, st) { return entry.type === 'File' && !this.unlink && st.isFile() && st.nlink <= 1 && !isWindows } // check if a thing is there, and if so, try to clobber it [CHECKFS] (entry) { this[PEND]() const paths = [entry.path] if (entry.linkpath) paths.push(entry.linkpath) this.reservations.reserve(paths, done => this[CHECKFS2](entry, done)) } [PRUNECACHE] (entry) { // if we are not creating a directory, and the path is in the dirCache, // then that means we are about to delete the directory we created // previously, and it is no longer going to be a directory, and neither // is any of its children. // If a symbolic link is encountered, all bets are off. There is no // reasonable way to sanitize the cache in such a way we will be able to // avoid having filesystem collisions. If this happens with a non-symlink // entry, it'll just fail to unpack, but a symlink to a directory, using an // 8.3 shortname or certain unicode attacks, can evade detection and lead // to arbitrary writes to anywhere on the system. if (entry.type === 'SymbolicLink') dropCache(this.dirCache) else if (entry.type !== 'Directory') pruneCache(this.dirCache, entry.absolute) } [CHECKFS2] (entry, fullyDone) { this[PRUNECACHE](entry) const done = er => { this[PRUNECACHE](entry) fullyDone(er) } const checkCwd = () => { this[MKDIR](this.cwd, this.dmode, er => { if (er) { this[ONERROR](er, entry) done() return } this[CHECKED_CWD] = true start() }) } const start = () => { if (entry.absolute !== this.cwd) { const parent = normPath(path.dirname(entry.absolute)) if (parent !== this.cwd) { return this[MKDIR](parent, this.dmode, er => { if (er) { this[ONERROR](er, entry) done() return } afterMakeParent() }) } } afterMakeParent() } const afterMakeParent = () => { fs.lstat(entry.absolute, (lstatEr, st) => { if (st && (this.keep || this.newer && st.mtime > entry.mtime)) { this[SKIP](entry) done() return } if (lstatEr || this[ISREUSABLE](entry, st)) return this[MAKEFS](null, entry, done) if (st.isDirectory()) { if (entry.type === 'Directory') { const needChmod = !this.noChmod && entry.mode && (st.mode & 0o7777) !== entry.mode const afterChmod = er => this[MAKEFS](er, entry, done) if (!needChmod) return afterChmod() return fs.chmod(entry.absolute, entry.mode, afterChmod) } // Not a dir entry, have to remove it. // NB: the only way to end up with an entry that is the cwd // itself, in such a way that == does not detect, is a // tricky windows absolute path with UNC or 8.3 parts (and // preservePaths:true, or else it will have been stripped). // In that case, the user has opted out of path protections // explicitly, so if they blow away the cwd, c'est la vie. if (entry.absolute !== this.cwd) { return fs.rmdir(entry.absolute, er => this[MAKEFS](er, entry, done)) } } // not a dir, and not reusable // don't remove if the cwd, we want that error if (entry.absolute === this.cwd) return this[MAKEFS](null, entry, done) unlinkFile(entry.absolute, er => this[MAKEFS](er, entry, done)) }) } if (this[CHECKED_CWD]) start() else checkCwd() } [MAKEFS] (er, entry, done) { if (er) { this[ONERROR](er, entry) done() return } switch (entry.type) { case 'File': case 'OldFile': case 'ContiguousFile': return this[FILE](entry, done) case 'Link': return this[HARDLINK](entry, done) case 'SymbolicLink': return this[SYMLINK](entry, done) case 'Directory': case 'GNUDumpDir': return this[DIRECTORY](entry, done) } } [LINK] (entry, linkpath, link, done) { // XXX: get the type ('symlink' or 'junction') for windows fs[link](linkpath, entry.absolute, er => { if (er) this[ONERROR](er, entry) else { this[UNPEND]() entry.resume() } done() }) } } const callSync = fn => { try { return [null, fn()] } catch (er) { return [er, null] } } class UnpackSync extends Unpack { [MAKEFS] (er, entry) { return super[MAKEFS](er, entry, () => {}) } [CHECKFS] (entry) { this[PRUNECACHE](entry) if (!this[CHECKED_CWD]) { const er = this[MKDIR](this.cwd, this.dmode) if (er) return this[ONERROR](er, entry) this[CHECKED_CWD] = true } // don't bother to make the parent if the current entry is the cwd, // we've already checked it. if (entry.absolute !== this.cwd) { const parent = normPath(path.dirname(entry.absolute)) if (parent !== this.cwd) { const mkParent = this[MKDIR](parent, this.dmode) if (mkParent) return this[ONERROR](mkParent, entry) } } const [lstatEr, st] = callSync(() => fs.lstatSync(entry.absolute)) if (st && (this.keep || this.newer && st.mtime > entry.mtime)) return this[SKIP](entry) if (lstatEr || this[ISREUSABLE](entry, st)) return this[MAKEFS](null, entry) if (st.isDirectory()) { if (entry.type === 'Directory') { const needChmod = !this.noChmod && entry.mode && (st.mode & 0o7777) !== entry.mode const [er] = needChmod ? callSync(() => { fs.chmodSync(entry.absolute, entry.mode) }) : [] return this[MAKEFS](er, entry) } // not a dir entry, have to remove it const [er] = callSync(() => fs.rmdirSync(entry.absolute)) this[MAKEFS](er, entry) } // not a dir, and not reusable. // don't remove if it's the cwd, since we want that error. const [er] = entry.absolute === this.cwd ? [] : callSync(() => unlinkFileSync(entry.absolute)) this[MAKEFS](er, entry) } [FILE] (entry, done) { const mode = entry.mode & 0o7777 || this.fmode const oner = er => { let closeError try { fs.closeSync(fd) } catch (e) { closeError = e } if (er || closeError) this[ONERROR](er || closeError, entry) done() } let fd try { fd = fs.openSync(entry.absolute, getFlag(entry.size), mode) } catch (er) { return oner(er) } const tx = this.transform ? this.transform(entry) || entry : entry if (tx !== entry) { tx.on('error', er => this[ONERROR](er, entry)) entry.pipe(tx) } tx.on('data', chunk => { try { fs.writeSync(fd, chunk, 0, chunk.length) } catch (er) { oner(er) } }) tx.on('end', _ => { let er = null // try both, falling futimes back to utimes // if either fails, handle the first error if (entry.mtime && !this.noMtime) { const atime = entry.atime || new Date() const mtime = entry.mtime try { fs.futimesSync(fd, atime, mtime) } catch (futimeser) { try { fs.utimesSync(entry.absolute, atime, mtime) } catch (utimeser) { er = futimeser } } } if (this[DOCHOWN](entry)) { const uid = this[UID](entry) const gid = this[GID](entry) try { fs.fchownSync(fd, uid, gid) } catch (fchowner) { try { fs.chownSync(entry.absolute, uid, gid) } catch (chowner) { er = er || fchowner } } } oner(er) }) } [DIRECTORY] (entry, done) { const mode = entry.mode & 0o7777 || this.dmode const er = this[MKDIR](entry.absolute, mode) if (er) { this[ONERROR](er, entry) done() return } if (entry.mtime && !this.noMtime) { try { fs.utimesSync(entry.absolute, entry.atime || new Date(), entry.mtime) } catch (er) {} } if (this[DOCHOWN](entry)) { try { fs.chownSync(entry.absolute, this[UID](entry), this[GID](entry)) } catch (er) {} } done() entry.resume() } [MKDIR] (dir, mode) { try { return mkdir.sync(normPath(dir), { uid: this.uid, gid: this.gid, processUid: this.processUid, processGid: this.processGid, umask: this.processUmask, preserve: this.preservePaths, unlink: this.unlink, cache: this.dirCache, cwd: this.cwd, mode: mode, }) } catch (er) { return er } } [LINK] (entry, linkpath, link, done) { try { fs[link + 'Sync'](linkpath, entry.absolute) done() entry.resume() } catch (er) { return this[ONERROR](er, entry) } } } Unpack.Sync = UnpackSync module.exports = Unpack /***/ }), /***/ 5997: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; // tar -u const hlo = __webpack_require__(2093) const r = __webpack_require__(1746) // just call tar.r with the filter and mtimeCache module.exports = (opt_, files, cb) => { const opt = hlo(opt_) if (!opt.file) throw new TypeError('file is required') if (opt.gzip) throw new TypeError('cannot append to compressed archives') if (!files || !Array.isArray(files) || !files.length) throw new TypeError('no files or directories specified') files = Array.from(files) mtimeFilter(opt) return r(opt, files, cb) } const mtimeFilter = opt => { const filter = opt.filter if (!opt.mtimeCache) opt.mtimeCache = new Map() opt.filter = filter ? (path, stat) => filter(path, stat) && !(opt.mtimeCache.get(path) > stat.mtime) : (path, stat) => !(opt.mtimeCache.get(path) > stat.mtime) } /***/ }), /***/ 7902: /***/ ((module) => { "use strict"; module.exports = Base => class extends Base { warn (code, message, data = {}) { if (this.file) data.file = this.file if (this.cwd) data.cwd = this.cwd data.code = message instanceof Error && message.code || code data.tarCode = code if (!this.strict && data.recoverable !== false) { if (message instanceof Error) { data = Object.assign(message, data) message = message.message } this.emit('warn', data.tarCode, message, data) } else if (message instanceof Error) this.emit('error', Object.assign(message, data)) else this.emit('error', Object.assign(new Error(`${code}: ${message}`), data)) } } /***/ }), /***/ 619: /***/ ((module) => { "use strict"; // When writing files on Windows, translate the characters to their // 0xf000 higher-encoded versions. const raw = [ '|', '<', '>', '?', ':', ] const win = raw.map(char => String.fromCharCode(0xf000 + char.charCodeAt(0))) const toWin = new Map(raw.map((char, i) => [char, win[i]])) const toRaw = new Map(win.map((char, i) => [char, raw[i]])) module.exports = { encode: s => raw.reduce((s, c) => s.split(c).join(toWin.get(c)), s), decode: s => win.reduce((s, c) => s.split(c).join(toRaw.get(c)), s), } /***/ }), /***/ 7620: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const MiniPass = __webpack_require__(5736) const Pax = __webpack_require__(4747) const Header = __webpack_require__(7134) const fs = __webpack_require__(7147) const path = __webpack_require__(1017) const normPath = __webpack_require__(2905) const stripSlash = __webpack_require__(4922) const prefixPath = (path, prefix) => { if (!prefix) return normPath(path) path = normPath(path).replace(/^\.(\/|$)/, '') return stripSlash(prefix) + '/' + path } const maxReadSize = 16 * 1024 * 1024 const PROCESS = Symbol('process') const FILE = Symbol('file') const DIRECTORY = Symbol('directory') const SYMLINK = Symbol('symlink') const HARDLINK = Symbol('hardlink') const HEADER = Symbol('header') const READ = Symbol('read') const LSTAT = Symbol('lstat') const ONLSTAT = Symbol('onlstat') const ONREAD = Symbol('onread') const ONREADLINK = Symbol('onreadlink') const OPENFILE = Symbol('openfile') const ONOPENFILE = Symbol('onopenfile') const CLOSE = Symbol('close') const MODE = Symbol('mode') const AWAITDRAIN = Symbol('awaitDrain') const ONDRAIN = Symbol('ondrain') const PREFIX = Symbol('prefix') const HAD_ERROR = Symbol('hadError') const warner = __webpack_require__(7902) const winchars = __webpack_require__(619) const stripAbsolutePath = __webpack_require__(2214) const modeFix = __webpack_require__(7716) const WriteEntry = warner(class WriteEntry extends MiniPass { constructor (p, opt) { opt = opt || {} super(opt) if (typeof p !== 'string') throw new TypeError('path is required') this.path = normPath(p) // suppress atime, ctime, uid, gid, uname, gname this.portable = !!opt.portable // until node has builtin pwnam functions, this'll have to do this.myuid = process.getuid && process.getuid() || 0 this.myuser = process.env.USER || '' this.maxReadSize = opt.maxReadSize || maxReadSize this.linkCache = opt.linkCache || new Map() this.statCache = opt.statCache || new Map() this.preservePaths = !!opt.preservePaths this.cwd = normPath(opt.cwd || process.cwd()) this.strict = !!opt.strict this.noPax = !!opt.noPax this.noMtime = !!opt.noMtime this.mtime = opt.mtime || null this.prefix = opt.prefix ? normPath(opt.prefix) : null this.fd = null this.blockLen = null this.blockRemain = null this.buf = null this.offset = null this.length = null this.pos = null this.remain = null if (typeof opt.onwarn === 'function') this.on('warn', opt.onwarn) let pathWarn = false if (!this.preservePaths) { const [root, stripped] = stripAbsolutePath(this.path) if (root) { this.path = stripped pathWarn = root } } this.win32 = !!opt.win32 || process.platform === 'win32' if (this.win32) { // force the \ to / normalization, since we might not *actually* // be on windows, but want \ to be considered a path separator. this.path = winchars.decode(this.path.replace(/\\/g, '/')) p = p.replace(/\\/g, '/') } this.absolute = normPath(opt.absolute || path.resolve(this.cwd, p)) if (this.path === '') this.path = './' if (pathWarn) { this.warn('TAR_ENTRY_INFO', `stripping ${pathWarn} from absolute path`, { entry: this, path: pathWarn + this.path, }) } if (this.statCache.has(this.absolute)) this[ONLSTAT](this.statCache.get(this.absolute)) else this[LSTAT]() } emit (ev, ...data) { if (ev === 'error') this[HAD_ERROR] = true return super.emit(ev, ...data) } [LSTAT] () { fs.lstat(this.absolute, (er, stat) => { if (er) return this.emit('error', er) this[ONLSTAT](stat) }) } [ONLSTAT] (stat) { this.statCache.set(this.absolute, stat) this.stat = stat if (!stat.isFile()) stat.size = 0 this.type = getType(stat) this.emit('stat', stat) this[PROCESS]() } [PROCESS] () { switch (this.type) { case 'File': return this[FILE]() case 'Directory': return this[DIRECTORY]() case 'SymbolicLink': return this[SYMLINK]() // unsupported types are ignored. default: return this.end() } } [MODE] (mode) { return modeFix(mode, this.type === 'Directory', this.portable) } [PREFIX] (path) { return prefixPath(path, this.prefix) } [HEADER] () { if (this.type === 'Directory' && this.portable) this.noMtime = true this.header = new Header({ path: this[PREFIX](this.path), // only apply the prefix to hard links. linkpath: this.type === 'Link' ? this[PREFIX](this.linkpath) : this.linkpath, // only the permissions and setuid/setgid/sticky bitflags // not the higher-order bits that specify file type mode: this[MODE](this.stat.mode), uid: this.portable ? null : this.stat.uid, gid: this.portable ? null : this.stat.gid, size: this.stat.size, mtime: this.noMtime ? null : this.mtime || this.stat.mtime, type: this.type, uname: this.portable ? null : this.stat.uid === this.myuid ? this.myuser : '', atime: this.portable ? null : this.stat.atime, ctime: this.portable ? null : this.stat.ctime, }) if (this.header.encode() && !this.noPax) { super.write(new Pax({ atime: this.portable ? null : this.header.atime, ctime: this.portable ? null : this.header.ctime, gid: this.portable ? null : this.header.gid, mtime: this.noMtime ? null : this.mtime || this.header.mtime, path: this[PREFIX](this.path), linkpath: this.type === 'Link' ? this[PREFIX](this.linkpath) : this.linkpath, size: this.header.size, uid: this.portable ? null : this.header.uid, uname: this.portable ? null : this.header.uname, dev: this.portable ? null : this.stat.dev, ino: this.portable ? null : this.stat.ino, nlink: this.portable ? null : this.stat.nlink, }).encode()) } super.write(this.header.block) } [DIRECTORY] () { if (this.path.substr(-1) !== '/') this.path += '/' this.stat.size = 0 this[HEADER]() this.end() } [SYMLINK] () { fs.readlink(this.absolute, (er, linkpath) => { if (er) return this.emit('error', er) this[ONREADLINK](linkpath) }) } [ONREADLINK] (linkpath) { this.linkpath = normPath(linkpath) this[HEADER]() this.end() } [HARDLINK] (linkpath) { this.type = 'Link' this.linkpath = normPath(path.relative(this.cwd, linkpath)) this.stat.size = 0 this[HEADER]() this.end() } [FILE] () { if (this.stat.nlink > 1) { const linkKey = this.stat.dev + ':' + this.stat.ino if (this.linkCache.has(linkKey)) { const linkpath = this.linkCache.get(linkKey) if (linkpath.indexOf(this.cwd) === 0) return this[HARDLINK](linkpath) } this.linkCache.set(linkKey, this.absolute) } this[HEADER]() if (this.stat.size === 0) return this.end() this[OPENFILE]() } [OPENFILE] () { fs.open(this.absolute, 'r', (er, fd) => { if (er) return this.emit('error', er) this[ONOPENFILE](fd) }) } [ONOPENFILE] (fd) { this.fd = fd if (this[HAD_ERROR]) return this[CLOSE]() this.blockLen = 512 * Math.ceil(this.stat.size / 512) this.blockRemain = this.blockLen const bufLen = Math.min(this.blockLen, this.maxReadSize) this.buf = Buffer.allocUnsafe(bufLen) this.offset = 0 this.pos = 0 this.remain = this.stat.size this.length = this.buf.length this[READ]() } [READ] () { const { fd, buf, offset, length, pos } = this fs.read(fd, buf, offset, length, pos, (er, bytesRead) => { if (er) { // ignoring the error from close(2) is a bad practice, but at // this point we already have an error, don't need another one return this[CLOSE](() => this.emit('error', er)) } this[ONREAD](bytesRead) }) } [CLOSE] (cb) { fs.close(this.fd, cb) } [ONREAD] (bytesRead) { if (bytesRead <= 0 && this.remain > 0) { const er = new Error('encountered unexpected EOF') er.path = this.absolute er.syscall = 'read' er.code = 'EOF' return this[CLOSE](() => this.emit('error', er)) } if (bytesRead > this.remain) { const er = new Error('did not encounter expected EOF') er.path = this.absolute er.syscall = 'read' er.code = 'EOF' return this[CLOSE](() => this.emit('error', er)) } // null out the rest of the buffer, if we could fit the block padding // at the end of this loop, we've incremented bytesRead and this.remain // to be incremented up to the blockRemain level, as if we had expected // to get a null-padded file, and read it until the end. then we will // decrement both remain and blockRemain by bytesRead, and know that we // reached the expected EOF, without any null buffer to append. if (bytesRead === this.remain) { for (let i = bytesRead; i < this.length && bytesRead < this.blockRemain; i++) { this.buf[i + this.offset] = 0 bytesRead++ this.remain++ } } const writeBuf = this.offset === 0 && bytesRead === this.buf.length ? this.buf : this.buf.slice(this.offset, this.offset + bytesRead) const flushed = this.write(writeBuf) if (!flushed) this[AWAITDRAIN](() => this[ONDRAIN]()) else this[ONDRAIN]() } [AWAITDRAIN] (cb) { this.once('drain', cb) } write (writeBuf) { if (this.blockRemain < writeBuf.length) { const er = new Error('writing more data than expected') er.path = this.absolute return this.emit('error', er) } this.remain -= writeBuf.length this.blockRemain -= writeBuf.length this.pos += writeBuf.length this.offset += writeBuf.length return super.write(writeBuf) } [ONDRAIN] () { if (!this.remain) { if (this.blockRemain) super.write(Buffer.alloc(this.blockRemain)) return this[CLOSE](er => er ? this.emit('error', er) : this.end()) } if (this.offset >= this.length) { // if we only have a smaller bit left to read, alloc a smaller buffer // otherwise, keep it the same length it was before. this.buf = Buffer.allocUnsafe(Math.min(this.blockRemain, this.buf.length)) this.offset = 0 } this.length = this.buf.length - this.offset this[READ]() } }) class WriteEntrySync extends WriteEntry { [LSTAT] () { this[ONLSTAT](fs.lstatSync(this.absolute)) } [SYMLINK] () { this[ONREADLINK](fs.readlinkSync(this.absolute)) } [OPENFILE] () { this[ONOPENFILE](fs.openSync(this.absolute, 'r')) } [READ] () { let threw = true try { const { fd, buf, offset, length, pos } = this const bytesRead = fs.readSync(fd, buf, offset, length, pos) this[ONREAD](bytesRead) threw = false } finally { // ignoring the error from close(2) is a bad practice, but at // this point we already have an error, don't need another one if (threw) { try { this[CLOSE](() => {}) } catch (er) {} } } } [AWAITDRAIN] (cb) { cb() } [CLOSE] (cb) { fs.closeSync(this.fd) cb() } } const WriteEntryTar = warner(class WriteEntryTar extends MiniPass { constructor (readEntry, opt) { opt = opt || {} super(opt) this.preservePaths = !!opt.preservePaths this.portable = !!opt.portable this.strict = !!opt.strict this.noPax = !!opt.noPax this.noMtime = !!opt.noMtime this.readEntry = readEntry this.type = readEntry.type if (this.type === 'Directory' && this.portable) this.noMtime = true this.prefix = opt.prefix || null this.path = normPath(readEntry.path) this.mode = this[MODE](readEntry.mode) this.uid = this.portable ? null : readEntry.uid this.gid = this.portable ? null : readEntry.gid this.uname = this.portable ? null : readEntry.uname this.gname = this.portable ? null : readEntry.gname this.size = readEntry.size this.mtime = this.noMtime ? null : opt.mtime || readEntry.mtime this.atime = this.portable ? null : readEntry.atime this.ctime = this.portable ? null : readEntry.ctime this.linkpath = normPath(readEntry.linkpath) if (typeof opt.onwarn === 'function') this.on('warn', opt.onwarn) let pathWarn = false if (!this.preservePaths) { const [root, stripped] = stripAbsolutePath(this.path) if (root) { this.path = stripped pathWarn = root } } this.remain = readEntry.size this.blockRemain = readEntry.startBlockSize this.header = new Header({ path: this[PREFIX](this.path), linkpath: this.type === 'Link' ? this[PREFIX](this.linkpath) : this.linkpath, // only the permissions and setuid/setgid/sticky bitflags // not the higher-order bits that specify file type mode: this.mode, uid: this.portable ? null : this.uid, gid: this.portable ? null : this.gid, size: this.size, mtime: this.noMtime ? null : this.mtime, type: this.type, uname: this.portable ? null : this.uname, atime: this.portable ? null : this.atime, ctime: this.portable ? null : this.ctime, }) if (pathWarn) { this.warn('TAR_ENTRY_INFO', `stripping ${pathWarn} from absolute path`, { entry: this, path: pathWarn + this.path, }) } if (this.header.encode() && !this.noPax) { super.write(new Pax({ atime: this.portable ? null : this.atime, ctime: this.portable ? null : this.ctime, gid: this.portable ? null : this.gid, mtime: this.noMtime ? null : this.mtime, path: this[PREFIX](this.path), linkpath: this.type === 'Link' ? this[PREFIX](this.linkpath) : this.linkpath, size: this.size, uid: this.portable ? null : this.uid, uname: this.portable ? null : this.uname, dev: this.portable ? null : this.readEntry.dev, ino: this.portable ? null : this.readEntry.ino, nlink: this.portable ? null : this.readEntry.nlink, }).encode()) } super.write(this.header.block) readEntry.pipe(this) } [PREFIX] (path) { return prefixPath(path, this.prefix) } [MODE] (mode) { return modeFix(mode, this.type === 'Directory', this.portable) } write (data) { const writeLen = data.length if (writeLen > this.blockRemain) throw new Error('writing more to entry than is appropriate') this.blockRemain -= writeLen return super.write(data) } end () { if (this.blockRemain) super.write(Buffer.alloc(this.blockRemain)) return super.end() } }) WriteEntry.Sync = WriteEntrySync WriteEntry.Tar = WriteEntryTar const getType = stat => stat.isFile() ? 'File' : stat.isDirectory() ? 'Directory' : stat.isSymbolicLink() ? 'SymbolicLink' : 'Unsupported' module.exports = WriteEntry /***/ }), /***/ 265: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /* Copyright (C) 2019-2021 Julian Valentin, LTeX Development Community * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); // #if TARGET == 'vscode' const Code = __importStar(__webpack_require__(9496)); // #elseif TARGET == 'coc.nvim' // import clipboard from 'clipboardy'; // import * as Code from 'coc.nvim'; // #endif const Fs = __importStar(__webpack_require__(7147)); const Os = __importStar(__webpack_require__(2037)); const Path = __importStar(__webpack_require__(1017)); const Url = __importStar(__webpack_require__(7310)); const I18n_1 = __webpack_require__(6187); const Logger_1 = __importDefault(__webpack_require__(7819)); class BugReporter { constructor(context, dependencyManager, statusInformationPrinter) { this._context = context; this._dependencyManager = dependencyManager; this._statusPrinter = statusInformationPrinter; } createReport() { var _a; return __awaiter(this, void 0, void 0, function* () { this._statusPrinter.print(); const templatePath = Path.resolve(this._context.extensionPath, '.github', 'ISSUE_TEMPLATE', 'bug-report.md'); let bugReport = Fs.readFileSync(templatePath, { encoding: 'utf-8' }); let pos; pos = bugReport.indexOf('---'); if (pos > -1) { pos = bugReport.indexOf('---', pos + 3); if (pos > -1) { pos = bugReport.indexOf('**', pos + 3); if (pos > -1) bugReport = bugReport.substring(pos); } } const document = // #if TARGET == 'vscode' (_a = Code.window.activeTextEditor) === null || _a === void 0 ? void 0 : _a.document; // #elseif TARGET == 'coc.nvim' // (await Code.workspace.document).textDocument; // #endif if (document != null) { let codeLanguage; switch (document.languageId) { case 'bibtex': case 'latex': case 'markdown': { codeLanguage = document.languageId; break; } default: { codeLanguage = 'plaintext'; break; } } pos = bugReport.indexOf('REPLACE_THIS_WITH_SAMPLE_DOCUMENT'); if (pos > -1) { pos = bugReport.lastIndexOf('```', pos); if (pos > -1) { bugReport = bugReport.substring(0, pos + 3) + codeLanguage + bugReport.substring(pos + 3); } } const documentText = BugReporter.truncateStringAtEnd(document.getText(), BugReporter._maxNumberOfDocumentLines); bugReport = bugReport.replace('REPLACE_THIS_WITH_SAMPLE_DOCUMENT', documentText); } const config = JSON.parse(JSON.stringify(Code.workspace.getConfiguration('ltex'))); let configJson = JSON.stringify(config, null, 2); configJson = BugReporter.truncateStringAtEnd(configJson, BugReporter._maxNumberOfConfigLines); bugReport = bugReport.replace('REPLACE_THIS_WITH_LTEX_CONFIGURATION', configJson); const serverLog = BugReporter.truncateStringAtStart(Logger_1.default.serverOutputChannel.content, BugReporter._maxNumberOfServerLogLines); bugReport = bugReport.replace('REPLACE_THIS_WITH_LTEX_LANGUAGE_SERVER_LOG', serverLog); let clientLog = Logger_1.default.clientOutputChannel.content; clientLog = BugReporter.truncateStringAtStart(clientLog, BugReporter._maxNumberOfClientLogLines); bugReport = bugReport.replace('REPLACE_THIS_WITH_LTEX_LANGUAGE_CLIENT_LOG', clientLog); const platform = `${Os.type} (${Os.platform}), ${Os.arch}, ${Os.release}`; bugReport = bugReport.replace(/^- Operating system: .*$/m, `- Operating system: ${platform}`); const vscodeReplacement = // #if TARGET == 'vscode' `- VS Code: ${Code.version}`; // #elseif TARGET == 'coc.nvim' // '- coc.nvim'; // #endif bugReport = bugReport.replace(/^- VS Code: .*$/m, vscodeReplacement); // deprecated: replace with self._context.extension starting with VS Code 1.55.0 const extension = // #if TARGET == 'vscode' Code.extensions.getExtension('valentjn.vscode-ltex'); // #elseif TARGET == 'coc.nvim' // Code.extensions.all.find( // (extension: Code.Extension) => extension.id == 'coc-ltex'); // #endif if (extension != null) { bugReport = bugReport.replace(/^- vscode-ltex: .*$/m, `- vscode-ltex: ${extension.packageJSON.version}`); } if (this._dependencyManager != null) { const ltexLsVersion = this._dependencyManager.ltexLsVersion; if (ltexLsVersion != null) { bugReport = bugReport.replace(/^- ltex-ls: .*$/m, `- ltex-ls: ${ltexLsVersion}`); } const javaVersion = this._dependencyManager.javaVersion; if (javaVersion != null) { bugReport = bugReport.replace(/^- Java: .*$/m, `- Java: ${javaVersion}`); } } return Promise.resolve(bugReport); }); } static truncateStringAtStart(str, maxNumberOfLines) { const lines = str.split('\n'); return ((lines.length > maxNumberOfLines) ? ('[... truncated]\n' + lines.slice(-maxNumberOfLines).join('\n')) : str); } static truncateStringAtEnd(str, maxNumberOfLines) { const lines = str.split('\n'); return ((lines.length > maxNumberOfLines) ? (lines.slice(0, maxNumberOfLines).join('\n') + '\n[... truncated]') : str); } report() { return __awaiter(this, void 0, void 0, function* () { Logger_1.default.log((0, I18n_1.i18n)('creatingBugReport')); const bugReport = yield this.createReport(); Code.window.showInformationMessage((0, I18n_1.i18n)('thanksForReportingBug'), (0, I18n_1.i18n)('setLtexTraceServerToVerbose'), (0, I18n_1.i18n)('copyReportAndCreateIssue')).then((selectedItem) => __awaiter(this, void 0, void 0, function* () { if (selectedItem == (0, I18n_1.i18n)('setLtexTraceServerToVerbose')) { const config = Code.workspace.getConfiguration('ltex'); // #if TARGET == 'vscode' config.update('trace.server', 'verbose', Code.ConfigurationTarget.Global); // #elseif TARGET == 'coc.nvim' // config.update('trace.server', 'verbose'); // #endif Code.window.showInformationMessage((0, I18n_1.i18n)('ltexTraceServerSetToVerbose')); } else if (selectedItem == (0, I18n_1.i18n)('copyReportAndCreateIssue')) { const url = new Url.URL(BugReporter._bugReportUrl); url.searchParams.set('body', (0, I18n_1.i18n)('enterSummaryOfIssueInTitleFieldAndReplaceSentence')); // #if TARGET == 'vscode' Code.env.clipboard.writeText(bugReport); Code.env.openExternal(Code.Uri.parse(url.toString())); // #elseif TARGET == 'coc.nvim' // await clipboard.write(bugReport); // Code.workspace.openResource(url.toString()); // #endif } })); }); } } exports["default"] = BugReporter; BugReporter._maxNumberOfDocumentLines = 200; BugReporter._maxNumberOfConfigLines = 1000; BugReporter._maxNumberOfServerLogLines = 100; BugReporter._maxNumberOfClientLogLines = 1000; BugReporter._bugReportUrl = 'https://github.com/valentjn/vscode-ltex/' + 'issues/new?assignees=&labels=1-bug%20%F0%9F%90%9B%2C+2-unconfirmed&' + 'template=bug-report.md&title=&body='; /***/ }), /***/ 1216: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /* Copyright (C) 2019-2021 Julian Valentin, LTeX Development Community * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); // #if TARGET == 'vscode' const Code = __importStar(__webpack_require__(9496)); // #elseif TARGET == 'coc.nvim' // import * as Code from 'coc.nvim'; // import CodeLanguageClient = Code; // import * as Glob from 'glob'; // #endif const Path = __importStar(__webpack_require__(1017)); const Extension = __importStar(__webpack_require__(7015)); const I18n_1 = __webpack_require__(6187); const Logger_1 = __importDefault(__webpack_require__(7819)); const ProgressStack_1 = __importDefault(__webpack_require__(6004)); const WorkspaceConfigurationRequestHandler_1 = __importDefault(__webpack_require__(4862)); class CommandHandler { constructor(context, externalFileManager, statusInformationPrinter, bugReporter) { this._context = context; this._statusPrinter = statusInformationPrinter; this._bugReporter = bugReporter; this._languageClient = null; this._externalFileManager = externalFileManager; context.subscriptions.push(Code.commands.registerCommand('ltex.activateExtension', this.activateExtension.bind(this))); context.subscriptions.push(Code.commands.registerCommand('ltex.checkSelection', this.checkSelection.bind(this))); context.subscriptions.push(Code.commands.registerCommand('ltex.checkCurrentDocument', this.checkCurrentDocument.bind(this))); context.subscriptions.push(Code.commands.registerCommand('ltex.checkAllDocumentsInWorkspace', this.checkAllDocumentsInWorkspace.bind(this))); context.subscriptions.push(Code.commands.registerCommand('ltex.clearDiagnosticsInCurrentDocument', this.clearDiagnosticsInCurrentDocument.bind(this))); context.subscriptions.push(Code.commands.registerCommand('ltex.clearAllDiagnostics', this.clearAllDiagnostics.bind(this))); context.subscriptions.push(Code.commands.registerCommand('ltex.showStatusInformation', this.showStatusInformation.bind(this))); context.subscriptions.push(Code.commands.registerCommand('ltex.resetAndRestart', this.resetAndRestart.bind(this))); context.subscriptions.push(Code.commands.registerCommand('ltex.reportBug', this._bugReporter.report.bind(this._bugReporter))); context.subscriptions.push(Code.commands.registerCommand('ltex.requestFeature', this.requestFeature.bind(this))); context.subscriptions.push(Code.commands.registerCommand('_ltex.openMarkdownExample', this.openMarkdownExample.bind(this))); context.subscriptions.push(Code.commands.registerCommand('_ltex.openLatexExample', this.openLatexExample.bind(this))); context.subscriptions.push(Code.commands.registerCommand('_ltex.addToDictionary', this.addToDictionary.bind(this))); context.subscriptions.push(Code.commands.registerCommand('_ltex.disableRules', this.disableRules.bind(this))); context.subscriptions.push(Code.commands.registerCommand('_ltex.hideFalsePositives', this.hideFalsePositives.bind(this))); } set languageClient(languageClient) { this._languageClient = languageClient; } activateExtension() { } checkDocument(uri, codeLanguageId, text, range) { return __awaiter(this, void 0, void 0, function* () { if (this._languageClient == null) { Code.window.showErrorMessage((0, I18n_1.i18n)('ltexNotInitialized')); return Promise.resolve(false); } const params = { uri: uri.toString(), codeLanguageId: codeLanguageId, text: text, range: range, }; let result = { success: false, }; try { yield Promise.race([ this._languageClient.onReady(), new Promise((_resolve, reject) => { setTimeout(() => reject(new Error((0, I18n_1.i18n)('ltexNotInitialized'))), 30000); }), ]); result = yield this._languageClient.sendRequest('workspace/executeCommand', { command: '_ltex.checkDocument', arguments: [params] }); } catch (e) { result.success = false; try { result.errorMessage = e.message; } catch (_a) { // do nothing } } if (result.success) { return Promise.resolve(true); } else { Code.window.showErrorMessage((0, I18n_1.i18n)('couldNotCheckDocument', uri.fsPath, result.errorMessage)); return Promise.resolve(false); } }); } checkSelection() { return __awaiter(this, void 0, void 0, function* () { if (this._languageClient == null) { Code.window.showErrorMessage((0, I18n_1.i18n)('ltexNotInitialized')); return Promise.resolve(false); } // #if TARGET == 'vscode' const textEditor = Code.window.activeTextEditor; if (textEditor == null) { Code.window.showErrorMessage((0, I18n_1.i18n)('noEditorOpenToCheckDocument')); return Promise.resolve(false); } return this.checkDocument(textEditor.document.uri, textEditor.document.languageId, textEditor.document.getText(), textEditor.selection); // #elseif TARGET == 'coc.nvim' // const document: Code.Document = await Code.workspace.document; // const range: Code.Range | null = await Code.workspace.getSelectedRange('v', document); // if (range == null) { // return Promise.resolve(false); // } // return this.checkDocument(Code.Uri.parse(document.uri), document.filetype, // document.content, range); // #endif }); } checkCurrentDocument() { return __awaiter(this, void 0, void 0, function* () { if (this._languageClient == null) { Code.window.showErrorMessage((0, I18n_1.i18n)('ltexNotInitialized')); return Promise.resolve(false); } // #if TARGET == 'vscode' const textEditor = Code.window.activeTextEditor; if (textEditor == null) { Code.window.showErrorMessage((0, I18n_1.i18n)('noEditorOpenToCheckDocument')); return Promise.resolve(false); } return this.checkDocument(textEditor.document.uri, textEditor.document.languageId, textEditor.document.getText()); // #elseif TARGET == 'coc.nvim' // const document: Code.Document = await Code.workspace.document; // return this.checkDocument(Code.Uri.parse(document.uri), document.filetype, // document.content); // #endif }); } checkAllDocumentsInWorkspace() { return __awaiter(this, void 0, void 0, function* () { if (this._languageClient == null) { Code.window.showErrorMessage((0, I18n_1.i18n)('ltexNotInitialized')); return Promise.resolve(false); } const progressOptions = { title: 'LTeX', // #if TARGET == 'vscode' location: Code.ProgressLocation.Notification, // #endif cancellable: true, }; return Code.window.withProgress(progressOptions, (progress, token) => __awaiter(this, void 0, void 0, function* () { const codeProgress = new ProgressStack_1.default((0, I18n_1.i18n)('checkingAllDocumentsInWorkspace'), progress); codeProgress.startTask(0.1, (0, I18n_1.i18n)('findingAllDocumentsInWorkspace')); if (token.isCancellationRequested) return Promise.resolve(true); const fileExtensions = CommandHandler.getEnabledFileExtensions(); if (fileExtensions.length == 0) return Promise.resolve(true); const fileExtensionWildcard = fileExtensions.join(','); const uris = yield CommandHandler.findFiles(`**/*.{${fileExtensionWildcard}}`, token); uris.sort((lhs, rhs) => lhs.fsPath.localeCompare(rhs.fsPath)); codeProgress.finishTask(); codeProgress.startTask(0.9, (0, I18n_1.i18n)('checkingAllDocumentsInWorkspace')); const n = uris.length; for (let i = 0; i < n; i++) { codeProgress.updateTask(i / n, (0, I18n_1.i18n)('checkingDocumentN', i + 1, n, Path.basename(uris[i].fsPath))); if (token.isCancellationRequested) return Promise.resolve(true); const success = yield this.checkDocument(uris[i]); if (!success) return Promise.resolve(false); } codeProgress.finishTask(); if (n > 0) { return Promise.resolve(true); } else { Code.window.showErrorMessage((Code.workspace.workspaceFolders == null) ? (0, I18n_1.i18n)('couldNotCheckDocumentsAsNoFoldersWereOpened') : (0, I18n_1.i18n)('couldNotCheckDocumentsAsNoDocumentsWereFound')); return Promise.resolve(false); } })); }); } static findFiles(globPattern, _token) { return __awaiter(this, void 0, void 0, function* () { // #if TARGET == 'vscode' return yield Code.workspace.findFiles(globPattern, undefined, undefined, _token); // #elseif TARGET == 'coc.nvim' // const filePaths: Code.Uri[] = []; // for (const workspaceFolder of Code.workspace.workspaceFolders) { // const workspaceFolderPath: string = Code.Uri.parse(workspaceFolder.uri).fsPath; // const curFilePaths: string[] = Glob.glob.sync(globPattern, {cwd: workspaceFolderPath}); // filePaths.concat(curFilePaths.map((filePath: string) => Code.Uri.file(filePath))); // } // return filePaths; // #endif }); } static getDefaultCodeLanguageIds() { return CommandHandler._defaultCodeLanguageIds; } static getEnabledFileExtensions() { const workspaceConfig = Code.workspace.getConfiguration('ltex'); const enabled = workspaceConfig.get('enabled'); let enabledCodeLanguageIds; if ((enabled === true) || (enabled === false)) { enabledCodeLanguageIds = (enabled ? CommandHandler._defaultCodeLanguageIds : []); } else { enabledCodeLanguageIds = enabled; } const enabledFileExtensions = new Set(); for (const codeLanguageId of enabledCodeLanguageIds) { switch (codeLanguageId) { case 'bibtex': { enabledFileExtensions.add('bib'); break; } case 'c': { enabledFileExtensions.add('c'); enabledFileExtensions.add('h'); break; } case 'clojure': { enabledFileExtensions.add('clj'); break; } case 'coffeescript': { enabledFileExtensions.add('coffee'); break; } case 'cpp': { enabledFileExtensions.add('cc'); enabledFileExtensions.add('cpp'); enabledFileExtensions.add('cxx'); enabledFileExtensions.add('hh'); enabledFileExtensions.add('hpp'); enabledFileExtensions.add('inl'); break; } case 'csharp': { enabledFileExtensions.add('cs'); break; } case 'context': { enabledFileExtensions.add('tex'); break; } case 'context.tex': { enabledFileExtensions.add('tex'); break; } case 'dart': { enabledFileExtensions.add('dart'); break; } case 'elixir': { enabledFileExtensions.add('ex'); break; } case 'elm': { enabledFileExtensions.add('elm'); break; } case 'erlang': { enabledFileExtensions.add('erl'); break; } case 'fortran-modern': { enabledFileExtensions.add('f90'); break; } case 'fsharp': { enabledFileExtensions.add('fs'); break; } case 'go': { enabledFileExtensions.add('go'); break; } case 'groovy': { enabledFileExtensions.add('groovy'); break; } case 'haskell': { enabledFileExtensions.add('hs'); break; } case 'html': { enabledFileExtensions.add('htm'); enabledFileExtensions.add('html'); enabledFileExtensions.add('xht'); enabledFileExtensions.add('xhtml'); break; } case 'java': { enabledFileExtensions.add('java'); break; } case 'javascript': { enabledFileExtensions.add('js'); break; } case 'julia': { enabledFileExtensions.add('jl'); break; } case 'kotlin': { enabledFileExtensions.add('kt'); break; } case 'latex': { enabledFileExtensions.add('tex'); break; } case 'lisp': { enabledFileExtensions.add('lisp'); break; } case 'lua': { enabledFileExtensions.add('lua'); break; } case 'markdown': { enabledFileExtensions.add('md'); break; } case 'matlab': { enabledFileExtensions.add('m'); break; } case 'org': { enabledFileExtensions.add('org'); break; } case 'perl': { enabledFileExtensions.add('pl'); break; } case 'php': { enabledFileExtensions.add('php'); break; } case 'powershell': { enabledFileExtensions.add('ps1'); break; } case 'puppet': { enabledFileExtensions.add('pp'); break; } case 'python': { enabledFileExtensions.add('py'); break; } case 'r': { enabledFileExtensions.add('r'); break; } case 'restructuredtext': { enabledFileExtensions.add('rst'); break; } case 'rsweave': { enabledFileExtensions.add('Rnw'); enabledFileExtensions.add('rnw'); enabledFileExtensions.add('tex'); break; } case 'ruby': { enabledFileExtensions.add('rb'); break; } case 'rust': { enabledFileExtensions.add('rs'); break; } case 'scala': { enabledFileExtensions.add('scala'); break; } case 'shellscript': { enabledFileExtensions.add('sh'); break; } case 'sql': { enabledFileExtensions.add('sql'); break; } case 'swift': { enabledFileExtensions.add('swift'); break; } case 'typescript': { enabledFileExtensions.add('ts'); break; } case 'vb': { enabledFileExtensions.add('vb'); break; } case 'verilog': { enabledFileExtensions.add('v'); break; } } } return Array.from(enabledFileExtensions).sort(); } clearDiagnosticsInCurrentDocument() { return __awaiter(this, void 0, void 0, function* () { if (this._languageClient == null) { Code.window.showErrorMessage((0, I18n_1.i18n)('ltexNotInitialized')); return Promise.resolve(false); } const diagnosticCollection = this._languageClient.diagnostics; if (diagnosticCollection == null) return Promise.resolve(true); // #if TARGET == 'vscode' const textEditor = Code.window.activeTextEditor; if (textEditor != null) diagnosticCollection.set(textEditor.document.uri, undefined); // #elseif TARGET == 'coc.nvim' // const document: Code.Document = await Code.workspace.document; // diagnosticCollection.set(document.uri, null); // #endif return Promise.resolve(true); }); } clearAllDiagnostics() { if (this._languageClient == null) { Code.window.showErrorMessage((0, I18n_1.i18n)('ltexNotInitialized')); return false; } const diagnosticCollection = this._languageClient.diagnostics; if (diagnosticCollection != null) diagnosticCollection.clear(); return true; } showStatusInformation() { return __awaiter(this, void 0, void 0, function* () { yield this._statusPrinter.print(); Logger_1.default.showClientOutputChannel(); return Promise.resolve(); }); } resetAndRestart() { return __awaiter(this, void 0, void 0, function* () { for (const disposable of this._context.subscriptions) { // #if TARGET == 'vscode' yield disposable.dispose(); // #elseif TARGET == 'coc.nvim' // disposable.dispose(); // #endif } yield Extension.activate(this._context); return Promise.resolve(); }); } requestFeature() { return __awaiter(this, void 0, void 0, function* () { yield Code.window.showInformationMessage((0, I18n_1.i18n)('thanksForRequestingFeature'), (0, I18n_1.i18n)('createIssue')).then((selectedItem) => __awaiter(this, void 0, void 0, function* () { if (selectedItem == (0, I18n_1.i18n)('createIssue')) { // #if TARGET == 'vscode' Code.env.openExternal(Code.Uri.parse(CommandHandler._featureRequestUrl)); // #elseif TARGET == 'coc.nvim' // Code.workspace.openResource(CommandHandler._featureRequestUrl); // #endif } })); return Promise.resolve(); }); } openMarkdownExample() { return __awaiter(this, void 0, void 0, function* () { // #if TARGET == 'vscode' yield Code.workspace.openTextDocument({ language: 'markdown', content: `# Markdown Example This is a sentence *without any errors.* This is a sentence *with a speling error in it.* Finally, this is a sentence *with an grammar error in it.* ` }); // #endif return Promise.resolve(); }); } openLatexExample() { return __awaiter(this, void 0, void 0, function* () { // #if TARGET == 'vscode' yield Code.workspace.openTextDocument({ language: 'latex', content: `\\section{\\LaTeX{} Example} This is a sentence \\emph{without any errors.} This is a sentence \\emph{with a speling error.} Finally, this is a sentence \\emph{with an grammar error.} ` }); // #endif return Promise.resolve(); }); } addToDictionary(params) { this.addToLanguageSpecificSetting(Code.Uri.parse(params.uri), 'dictionary', params.words); this.checkCurrentDocument(); } disableRules(params) { this.addToLanguageSpecificSetting(Code.Uri.parse(params.uri), 'disabledRules', params.ruleIds); this.checkCurrentDocument(); } hideFalsePositives(params) { this.addToLanguageSpecificSetting(Code.Uri.parse(params.uri), 'hiddenFalsePositives', params.falsePositives); this.checkCurrentDocument(); } addToLanguageSpecificSetting(uri, settingName, entries) { const resourceConfig = // #if TARGET == 'vscode' Code.workspace.getConfiguration('ltex.configurationTarget', uri); // #elseif TARGET == 'coc.nvim' // Code.workspace.getConfiguration('ltex.configurationTarget', uri.toString()); // #endif const scopeString = resourceConfig.get(settingName); let scopes; if ((scopeString == null) || scopeString.startsWith('workspaceFolder')) { scopes = [Code.ConfigurationTarget.WorkspaceFolder, Code.ConfigurationTarget.Workspace, Code.ConfigurationTarget.Global]; } else if (scopeString.startsWith('workspace')) { scopes = [Code.ConfigurationTarget.Workspace, Code.ConfigurationTarget.Global]; } else if (scopeString.startsWith('user')) { scopes = [Code.ConfigurationTarget.Global]; } else { Logger_1.default.error((0, I18n_1.i18n)('invalidValueForConfigurationTarget', scopeString)); return; } if ((scopeString == null) || scopeString.endsWith('ExternalFile')) { this.addToLanguageSpecificSettingExternalFile(uri, settingName, scopes, entries); } else { this.addToLanguageSpecificSettingInternalSetting(uri, settingName, scopes, entries); } } addToLanguageSpecificSettingExternalFile(uri, settingName, scopes, entries) { for (const language in entries) { if (!Object.prototype.hasOwnProperty.call(entries, language)) continue; let settingWritten = false; for (const scope of scopes) { const externalFilePath = this._externalFileManager.getFirstExternalFilePath(uri, settingName, scope, language); if (externalFilePath != null) { this._externalFileManager.appendToFile(externalFilePath, settingName, entries[language]); settingWritten = true; break; } } if (!settingWritten) { const languageEntries = {}; languageEntries[language] = entries[language]; this.addToLanguageSpecificSettingInternalSetting(uri, settingName, scopes, languageEntries); } } } addToLanguageSpecificSettingInternalSetting(uri, settingName, scopes, entries) { return __awaiter(this, void 0, void 0, function* () { const resourceConfig = // #if TARGET == 'vscode' Code.workspace.getConfiguration('ltex', uri); // #elseif TARGET == 'coc.nvim' // Code.workspace.getConfiguration('ltex', uri.toString()); // #endif const settingValue = resourceConfig.get(settingName, {}); for (const language in entries) { if (!Object.prototype.hasOwnProperty.call(entries, language)) continue; let languageSettingValue = ((settingValue[language] != null) ? settingValue[language] : []); languageSettingValue = languageSettingValue.concat(entries[language]); settingValue[language] = WorkspaceConfigurationRequestHandler_1.default. cleanUpWorkspaceSpecificStringArray(languageSettingValue); } for (let i = 0; i < scopes.length; i++) { try { // #if TARGET == 'vscode' yield resourceConfig.update(settingName, settingValue, scopes[i]); // #elseif TARGET == 'coc.nvim' // resourceConfig.update(settingName, settingValue, // (scopes[i] == Code.ConfigurationTarget.Global)); // #endif return; } catch (e) { if (i == scopes.length - 1) Logger_1.default.error((0, I18n_1.i18n)('couldNotSetConfiguration', settingName), e); } } }); } } exports["default"] = CommandHandler; CommandHandler._featureRequestUrl = 'https://github.com/valentjn/vscode-ltex/' + 'issues/new?assignees=&labels=1-feature-request%20%E2%9C%A8&' + 'template=feature-request.md&title='; CommandHandler._defaultCodeLanguageIds = [ 'bibtex', 'context', 'context.tex', 'html', 'latex', 'markdown', 'org', 'restructuredtext', 'rsweave', ]; /***/ }), /***/ 9604: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /* Copyright (C) 2019-2021 Julian Valentin, LTeX Development Community * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); // #if TARGET == 'vscode' const Code = __importStar(__webpack_require__(9496)); // #elseif TARGET == 'coc.nvim' // import * as Code from 'coc.nvim'; // import CodeLanguageClient = Code; // #endif const ChildProcess = __importStar(__webpack_require__(2081)); const Crypto = __importStar(__webpack_require__(6113)); const extract_zip_1 = __importDefault(__webpack_require__(2106)); const Fs = __importStar(__webpack_require__(7147)); const Https = __importStar(__webpack_require__(5687)); const Net = __importStar(__webpack_require__(1808)); const Os = __importStar(__webpack_require__(2037)); const Path = __importStar(__webpack_require__(1017)); const SemVer = __importStar(__webpack_require__(1249)); const Tar = __importStar(__webpack_require__(7998)); const Url = __importStar(__webpack_require__(7310)); const I18n_1 = __webpack_require__(6187); const Logger_1 = __importDefault(__webpack_require__(7819)); const ProgressStack_1 = __importDefault(__webpack_require__(6004)); class DependencyManager { constructor(context) { this._ltexLsPath = null; this._javaPath = null; this._ltexLsVersion = null; this._javaVersion = null; this._context = context; // deprecated: replace with context.extension starting with VS Code 1.55.0 const vscodeLtexExtension = // #if TARGET == 'vscode' Code.extensions.getExtension('valentjn.vscode-ltex'); // #elseif TARGET == 'coc.nvim' // Code.extensions.all.find( // (extension: Code.Extension) => extension.id == 'coc-ltex'); // #endif if (vscodeLtexExtension == null) throw new Error((0, I18n_1.i18n)('couldNotGetVscodeLtexVersion')); this._vscodeLtexVersion = vscodeLtexExtension.packageJSON.version; } static isValidPath(path) { return ((path != null) && (path.length > 0)); } static normalizePath(path) { if (path == null) return null; const homeDirPath = Os.homedir(); return path.replace(/^~($|\/|\\)/, `${homeDirPath}$1`); } static parseUrl(urlStr) { const url = new Url.URL(urlStr); return { hostname: url.hostname, path: url.pathname + url.search, headers: { 'User-Agent': 'vscode-ltex' }, }; } static downloadFile(urlStr, path, codeProgress) { return __awaiter(this, void 0, void 0, function* () { const file = Fs.createWriteStream(path); const origTaskName = codeProgress.getTaskName(); return new Promise((resolve, reject) => { Https.get(DependencyManager.parseUrl(urlStr), (response) => { if ((response.statusCode === 301) || (response.statusCode === 302) || (response.statusCode === 307)) { if (response.headers.location == null) { reject(new Error((0, I18n_1.i18n)('receivedRedirectionStatusCodeWithoutLocationHeader', response.statusCode))); return; } Logger_1.default.log((0, I18n_1.i18n)('redirectedTo', response.headers.location)); DependencyManager.downloadFile(response.headers.location, path, codeProgress) .then(resolve).catch(reject); return; } else if (response.statusCode !== 200) { response.resume(); reject(new Error((0, I18n_1.i18n)('requestFailedWithStatusCode', response.statusCode))); return; } const totalBytes = ((response.headers['content-length'] != null) ? parseInt(response.headers['content-length']) : 0); const totalMb = Math.round(totalBytes / 1e6); let downloadedBytes = 0; let lastTaskNameUpdate = Date.now(); codeProgress.updateTask(0, ((totalBytes > 0) ? `${origTaskName} 0MB/${totalMb}MB` : origTaskName)); response.pipe(file); if (totalBytes > 0) { response.on('data', (chunk) => { downloadedBytes += chunk.length; const now = Date.now(); if (now - lastTaskNameUpdate >= 500) { lastTaskNameUpdate = now; const downloadedMb = Math.round(downloadedBytes / 1e6); const taskName = `${origTaskName} ${downloadedMb}MB/${totalMb}MB`; codeProgress.updateTask(downloadedBytes / totalBytes, taskName); } }); } file.on('finish', () => { file.close(); resolve(); }); }).on('error', (e) => { Fs.unlinkSync(path); reject(e); }); }); }); } static verifyFile(path, hashDigest) { return __awaiter(this, void 0, void 0, function* () { return new Promise((resolve, reject) => { const hash = Crypto.createHash('sha256'); const readStream = Fs.createReadStream(path); readStream.on('data', (d) => hash.update(d)); readStream.on('end', () => { const actualHashDigest = hash.digest('hex'); if (actualHashDigest === hashDigest) { resolve(); } else { reject(new Error((0, I18n_1.i18n)('couldNotVerifyDownloadedFile', path, hashDigest, actualHashDigest))); } }); readStream.on('error', (e) => reject(e)); }); }); } getLatestLtexLsVersion(versions) { let latestVersion = null; versions.forEach((version) => { if (SemVer.valid(version) && ((latestVersion == null) || SemVer.gt(version, latestVersion))) { latestVersion = version; } }); return latestVersion; } installDependency(urlStr, hashDigest, name, codeProgress) { return __awaiter(this, void 0, void 0, function* () { codeProgress.startTask(0.1, (0, I18n_1.i18n)('downloading', name)); const url = new Url.URL(urlStr); if (url.pathname == null) throw new Error((0, I18n_1.i18n)('couldNotGetPathNameFromUrl', urlStr)); const archiveName = Path.basename(url.pathname); const archiveType = ((Path.extname(archiveName) == '.zip') ? 'zip' : 'tar.gz'); const tmpDirPath = Fs.mkdtempSync(Path.join(this._context.extensionPath, 'tmp-')); const archivePath = Path.join(tmpDirPath, archiveName); codeProgress.finishTask(); codeProgress.startTask(0.7, (0, I18n_1.i18n)('downloading', name)); Logger_1.default.log((0, I18n_1.i18n)('downloadingFromTo', name, urlStr, archivePath)); yield DependencyManager.downloadFile(urlStr, archivePath, codeProgress); codeProgress.finishTask(); codeProgress.startTask(0.1, (0, I18n_1.i18n)('verifying', name)); yield DependencyManager.verifyFile(archivePath, hashDigest); codeProgress.finishTask(); codeProgress.startTask(0.1, (0, I18n_1.i18n)('extracting', name)); Logger_1.default.log((0, I18n_1.i18n)('extractingTo', archivePath, tmpDirPath)); if (archiveType == 'zip') { yield (0, extract_zip_1.default)(archivePath, { dir: tmpDirPath }); } else { yield Tar.extract({ file: archivePath, cwd: tmpDirPath }); } codeProgress.updateTask(0.8); const fileNames = Fs.readdirSync(tmpDirPath); let extractedDirPath = null; Logger_1.default.log((0, I18n_1.i18n)('searchingForDirectory', tmpDirPath)); for (let i = 0; i < fileNames.length; i++) { const filePath = Path.join(tmpDirPath, fileNames[i]); const stats = Fs.lstatSync(filePath); if (stats.isDirectory()) { if (extractedDirPath == null) { extractedDirPath = filePath; } else { Logger_1.default.warn((0, I18n_1.i18n)('foundMultipleDirectoriesAfterExtraction', extractedDirPath, filePath)); } } else { try { Logger_1.default.log((0, I18n_1.i18n)('deleting', filePath)); Fs.unlinkSync(filePath); } catch (e) { Logger_1.default.warn((0, I18n_1.i18n)('couldNotDeleteLeavingTemporaryFileOnDisk', filePath), e); } } } if (extractedDirPath == null) { throw new Error((0, I18n_1.i18n)('couldNotFindDirectoryAfterExtractingArchive')); } Logger_1.default.log((0, I18n_1.i18n)('foundExtractedDirectory', extractedDirPath)); codeProgress.updateTask(0.85); const targetDirPath = Path.join(this._context.extensionPath, 'lib', Path.basename(extractedDirPath)); const targetExists = Fs.existsSync(targetDirPath); codeProgress.updateTask(0.9); if (targetExists) { Logger_1.default.warn((0, I18n_1.i18n)('didNotMoveAsTargetAlreadyExists', extractedDirPath, targetDirPath)); } else { Logger_1.default.log((0, I18n_1.i18n)('movingTo', extractedDirPath, targetDirPath)); Fs.renameSync(extractedDirPath, targetDirPath); } codeProgress.updateTask(0.95); try { Logger_1.default.log((0, I18n_1.i18n)('deleting', tmpDirPath)); Fs.rmdirSync(tmpDirPath); } catch (e) { Logger_1.default.warn((0, I18n_1.i18n)('couldNotDeleteLeavingTemporaryDirectoryOnDisk', tmpDirPath), e); } codeProgress.finishTask(); return Promise.resolve(); }); } installLtexLs() { return __awaiter(this, void 0, void 0, function* () { const progressOptions = { title: 'LTeX', // #if TARGET == 'vscode' location: Code.ProgressLocation.Notification, // #endif cancellable: false, }; return Code.window.withProgress(progressOptions, (progress) => __awaiter(this, void 0, void 0, function* () { const codeProgress = new ProgressStack_1.default((0, I18n_1.i18n)('downloadingAndExtractingLtexLs'), progress); let platform = 'linux'; const arch = 'x64'; let archiveType = 'tar.gz'; if (process.platform == 'win32') { platform = 'windows'; archiveType = 'zip'; } else if (process.platform == 'darwin') { platform = 'mac'; } const ltexLsArchiveName = 'ltex-ls-' + `${DependencyManager._toBeDownloadedLtexLsVersion}-${platform}-${arch}.${archiveType}`; const ltexLsUrl = 'https://github.com/valentjn/ltex-ls/releases/download/' + `${DependencyManager._toBeDownloadedLtexLsTag}/${ltexLsArchiveName}`; const ltexLsHashDigest = DependencyManager._toBeDownloadedLtexLsHashDigests[ltexLsArchiveName]; yield this.installDependency(ltexLsUrl, ltexLsHashDigest, `ltex-ls ${DependencyManager._toBeDownloadedLtexLsVersion}`, codeProgress); })); }); } searchBundledLtexLs(libDirPath) { const names = Fs.readdirSync(libDirPath); const ltexLsVersions = []; names.forEach((name) => { if (name.startsWith('ltex-ls-')) { ltexLsVersions.push(name.substr(8)); } }); const ltexLsVersion = this.getLatestLtexLsVersion(ltexLsVersions); return ((ltexLsVersion != null) ? Path.join(libDirPath, `ltex-ls-${ltexLsVersion}`) : null); } install() { return __awaiter(this, void 0, void 0, function* () { const libDirPath = Path.join(this._context.extensionPath, 'lib'); const workspaceConfig = Code.workspace.getConfiguration('ltex'); if (!Fs.existsSync(libDirPath)) { Logger_1.default.log((0, I18n_1.i18n)('creating', libDirPath)); Fs.mkdirSync(libDirPath); } try { // try 0: use ltex.ltex-ls.path // try 1: use lib/ (don't download) // try 2: download and use lib/ Logger_1.default.log(''); this._ltexLsPath = DependencyManager.normalizePath(workspaceConfig.get('ltex-ls.path', '')); if (DependencyManager.isValidPath(this._ltexLsPath)) { Logger_1.default.log((0, I18n_1.i18n)('ltexLtexLsPathSetTo', this._ltexLsPath)); } else { Logger_1.default.log((0, I18n_1.i18n)('ltexLtexLsPathNotSet')); Logger_1.default.log((0, I18n_1.i18n)('searchingForLtexLsIn', libDirPath)); this._ltexLsPath = this.searchBundledLtexLs(libDirPath); if (DependencyManager.isValidPath(this._ltexLsPath)) { Logger_1.default.log((0, I18n_1.i18n)('ltexLsFoundIn', this._ltexLsPath)); } else { Logger_1.default.log((0, I18n_1.i18n)('couldNotFindVersionOfLtexLsIn', libDirPath)); Logger_1.default.log((0, I18n_1.i18n)('initiatingDownloadOfLtexLs')); yield this.installLtexLs(); this._ltexLsPath = this.searchBundledLtexLs(libDirPath); if (DependencyManager.isValidPath(this._ltexLsPath)) { Logger_1.default.log((0, I18n_1.i18n)('ltexLsFoundIn', this._ltexLsPath)); } else { throw Error((0, I18n_1.i18n)('couldNotDownloadOrExtractLtexLs')); } } } } catch (e) { Logger_1.default.error((0, I18n_1.i18n)('downloadOrExtractionOfLtexLsFailed'), e); Logger_1.default.log((0, I18n_1.i18n)('youMightWantToTryOfflineInstallationSee', DependencyManager._offlineInstructionsUrl)); Logger_1.default.showClientOutputChannel(); return this.showOfflineInstallationInstructions((0, I18n_1.i18n)('couldNotInstallLtexLs')); } Logger_1.default.log(''); Logger_1.default.log((0, I18n_1.i18n)('usingLtexLsFrom', this._ltexLsPath)); this._javaPath = DependencyManager.normalizePath(workspaceConfig.get('java.path')); if (DependencyManager.isValidPath(this._javaPath)) { Logger_1.default.log((0, I18n_1.i18n)('usingJavaFrom', this._javaPath)); } else { Logger_1.default.log((0, I18n_1.i18n)('usingJavaBundledWithLtexLs')); } if (yield this.test()) { Logger_1.default.log(''); return true; } else { Logger_1.default.log((0, I18n_1.i18n)('youMightWantToTryOfflineInstallationSee', DependencyManager._offlineInstructionsUrl)); Logger_1.default.showClientOutputChannel(); return yield this.showOfflineInstallationInstructions((0, I18n_1.i18n)('couldNotRunLtexLs')); } }); } showOfflineInstallationInstructions(message) { return __awaiter(this, void 0, void 0, function* () { return new Promise((resolve) => { Code.window.showErrorMessage(`${message} ${(0, I18n_1.i18n)('youMightWantToTryOfflineInstallation')}`, (0, I18n_1.i18n)('tryAgain'), (0, I18n_1.i18n)('offlineInstructions')).then((selectedItem) => __awaiter(this, void 0, void 0, function* () { if (selectedItem == (0, I18n_1.i18n)('tryAgain')) { resolve(yield this.install()); return; } else if (selectedItem == (0, I18n_1.i18n)('offlineInstructions')) { // #if TARGET == 'vscode' Code.env.openExternal(Code.Uri.parse(DependencyManager._offlineInstructionsUrl)); // #elseif TARGET == 'coc.nvim' // Code.workspace.openResource( // Code.Uri.parse(DependencyManager._offlineInstructionsUrl).toString()); // #endif } resolve(false); })); }); }); } test() { return __awaiter(this, void 0, void 0, function* () { const executable = yield this.getLtexLsExecutable(); if (executable.args == null) executable.args = []; executable.args.push('--version'); const executableOptions = { encoding: 'utf-8', timeout: 15000, }; if (executable.options != null) { executableOptions.cwd = executable.options.cwd; executableOptions.env = executable.options.env; } Logger_1.default.log((0, I18n_1.i18n)('testingLtexLs')); Logger_1.default.logExecutable(executable); let childProcess = null; try { childProcess = ChildProcess.spawnSync(executable.command, executable.args, executableOptions); } catch (e) { Logger_1.default.error((0, I18n_1.i18n)('testFailed'), e); return Promise.resolve(false); } let success = false; let ltexLsVersion = ''; let javaVersion = ''; let javaMajorVersion = -1; if ((childProcess.status == 0) && childProcess.stdout.includes('ltex-ls')) { try { const versionInfo = JSON.parse(childProcess.stdout); if (Object.prototype.hasOwnProperty.call(versionInfo, 'ltex-ls')) { ltexLsVersion = versionInfo['ltex-ls']; } if (Object.prototype.hasOwnProperty.call(versionInfo, 'java')) { const match = versionInfo['java'].match(/(\d+)(?:\.(\d+))?/); if ((match != null) && (match.length >= 3)) { javaVersion = versionInfo['java']; javaMajorVersion = parseInt(match[1]); if (javaMajorVersion == 1) javaMajorVersion = parseInt(match[2]); } } if ((ltexLsVersion.length > 0) && (javaVersion.length > 0)) { success = true; } } catch (e) { // don't throw error as debug info is printed below } } if (success) { Logger_1.default.log((0, I18n_1.i18n)('testSuccessful')); this._ltexLsVersion = ltexLsVersion; this._javaVersion = javaVersion; return Promise.resolve(true); } else { Logger_1.default.error((0, I18n_1.i18n)('testFailed'), childProcess.error); if ((childProcess.status != null) && (childProcess.status != 0)) { Logger_1.default.log((0, I18n_1.i18n)('ltexLsTerminatedWithNonZeroExitCode', childProcess.status)); } else if (childProcess.signal != null) { Logger_1.default.log((0, I18n_1.i18n)('ltexLsTerminatedDueToSignal', childProcess.signal)); } else { Logger_1.default.log((0, I18n_1.i18n)('ltexLsDidNotPrintExpectVersionInformation')); } Logger_1.default.log((0, I18n_1.i18n)('stdoutOfLtexLs')); Logger_1.default.log(childProcess.stdout); Logger_1.default.log((0, I18n_1.i18n)('stderrOfLtexLs')); Logger_1.default.log(childProcess.stderr); return Promise.resolve(false); } }); } getLtexLsExecutable() { return __awaiter(this, void 0, void 0, function* () { if (!DependencyManager.isValidPath(this._ltexLsPath)) { return Promise.reject(new Error((0, I18n_1.i18n)('couldNotGetLtexLsExecutable'))); } const env = {}; for (const name in process.env) { if ((Object.prototype.hasOwnProperty.call(process.env, name)) && (name != 'JAVA_HOME')) { env[name] = process.env[name]; } } if (DependencyManager.isValidPath(this._javaPath)) { env['JAVA_HOME'] = this._javaPath; } const isWindows = (process.platform === 'win32'); const ltexLsScriptPath = Path.join(this._ltexLsPath, 'bin', (isWindows ? 'ltex-ls.bat' : 'ltex-ls')); const workspaceConfig = Code.workspace.getConfiguration('ltex'); const initialJavaHeapSize = workspaceConfig.get('java.initialHeapSize'); const maximumJavaHeapSize = workspaceConfig.get('java.maximumHeapSize'); const javaArguments = []; if (initialJavaHeapSize != null) javaArguments.push(`-Xms${initialJavaHeapSize}m`); if (maximumJavaHeapSize != null) javaArguments.push(`-Xmx${maximumJavaHeapSize}m`); env['JAVA_OPTS'] = javaArguments.join(' '); return { command: ltexLsScriptPath, args: [], options: { 'env': env } }; }); } static getDebugServerOptions() { const executableOptions = { encoding: 'utf-8', timeout: 15000, }; const childProcess = ((process.platform == 'win32') ? ChildProcess.spawnSync('wmic', ['process', 'list', 'FULL'], executableOptions) : ChildProcess.spawnSync('ps', ['-A', '-o', 'args'], executableOptions)); if (childProcess.status != 0) return null; const output = childProcess.stdout; const matchPos = output.search(/LtexLanguageServerLauncher.*--server-type(?: +|=)tcpSocket/); if (matchPos == -1) return null; const startPos = output.lastIndexOf('\n', matchPos); const endPos = output.indexOf('\n', matchPos); const line = output.substring(((startPos != -1) ? startPos : 0), ((endPos != -1) ? endPos : output.length)); const match = line.match(/--port(?: +|=)([0-9]+)/); if (match == null) return null; const port = parseInt(match[1]); if (port == 0) return null; const socket = new Net.Socket(); socket.connect(port, 'localhost'); return () => { return Promise.resolve({ writer: socket, reader: socket }); }; } get vscodeLtexVersion() { return this._vscodeLtexVersion; } get ltexLsVersion() { return this._ltexLsVersion; } get javaVersion() { return this._javaVersion; } } exports["default"] = DependencyManager; DependencyManager._offlineInstructionsUrl = 'https://valentjn.github.io/' + 'vscode-ltex/docs/installation-and-usage.html#offline-installation'; DependencyManager._toBeDownloadedLtexLsTag = '15.2.0'; DependencyManager._toBeDownloadedLtexLsVersion = '15.2.0'; DependencyManager._toBeDownloadedLtexLsHashDigests = { 'ltex-ls-15.2.0-linux-x64.tar.gz': '04d7e2ba6ef0ff91f84983554e39181ada59518f7b6268e559bed6efae0827fc', 'ltex-ls-15.2.0-mac-x64.tar.gz': 'd89b547722f165ca2343962065cbe7ee4a832316825b04266d1d2db3e46487b3', 'ltex-ls-15.2.0-windows-x64.zip': '66a8449840fd09d7cde27c1e23ecfe94c0cbe6622769c19d36b007965c0c0124', }; /***/ }), /***/ 4868: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /* Copyright (C) 2019-2021 Julian Valentin, LTeX Development Community * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); // #if TARGET == 'vscode' const Code = __importStar(__webpack_require__(9496)); // #elseif TARGET == 'coc.nvim' // import * as Code from 'coc.nvim'; // #endif const Fs = __importStar(__webpack_require__(7147)); const Os = __importStar(__webpack_require__(2037)); const Path = __importStar(__webpack_require__(1017)); const I18n_1 = __webpack_require__(6187); const Logger_1 = __importDefault(__webpack_require__(7819)); class ExternalFileManager { constructor(context) { this._context = context; this._languages = ExternalFileManager.getLanguages(context); this._watchers = {}; this._contents = {}; for (const settingName of ExternalFileManager._settingNames) { this._watchers[settingName] = {}; this._contents[settingName] = {}; } } static getLanguages(context) { const packageJsonPath = Path.resolve(context.extensionPath, 'package.json'); const packageJson = JSON.parse(Fs.readFileSync(packageJsonPath, { encoding: 'utf-8' })); const languages = packageJson['contributes']['configuration']['properties']['ltex.language']['enum']; return languages; } updateWatchers(uri, settingName) { const oldExternalFilePaths = new Set(); const watchers = this._watchers[settingName]; for (const filePath in watchers) { if (!Object.prototype.hasOwnProperty.call(watchers, filePath)) continue; oldExternalFilePaths.add(filePath); } const externalFiles = this.getExternalFilesFromSetting(uri, settingName); const newExternalFiles = new Set(); const newExternalFilePaths = new Set(); for (const language in externalFiles) { if (!Object.prototype.hasOwnProperty.call(externalFiles, language)) continue; for (const externalFile of externalFiles[language]) { if (!newExternalFilePaths.has(externalFile.resolvedPath)) { newExternalFiles.add(externalFile); newExternalFilePaths.add(externalFile.resolvedPath); } } } for (const filePath of oldExternalFilePaths) { if (!newExternalFilePaths.has(filePath)) { watchers[filePath].close(); delete this._watchers[settingName][filePath]; delete this._contents[settingName][filePath]; } } for (const externalFile of newExternalFiles) { const filePath = externalFile.resolvedPath; if (!oldExternalFilePaths.has(filePath)) { let watcher = null; let contents = null; try { // on Windows, the watcher event only receives the filename (not the full path) // => supply file path ourselves watcher = Fs.watch(filePath, this.onFileWatcherEvent.bind(this, filePath)); contents = Fs.readFileSync(filePath, { encoding: 'utf-8' }); } catch (e) { if (externalFile.explicit) { Logger_1.default.warn((0, I18n_1.i18n)('couldNotReadExternalSettingFile', filePath), e); } watcher = null; contents = null; continue; } Logger_1.default.log((0, I18n_1.i18n)('startedWatchingExternalSettingFile', filePath)); this._watchers[settingName][filePath] = watcher; this._contents[settingName][filePath] = contents; } } } getAllWatchedExternalFiles() { const filePaths = []; for (const settingName of ExternalFileManager._settingNames) { const watchers = this._watchers[settingName]; for (const filePath in watchers) { if (!Object.prototype.hasOwnProperty.call(watchers, filePath)) continue; filePaths.push(filePath); } } return filePaths; } getFirstExternalFilePath(uri, settingName, scope, language) { const externalFiles = this.analyzeSetting(uri, settingName, scope, language).externalFiles; return ((Object.prototype.hasOwnProperty.call(externalFiles, language) && (externalFiles[language].length > 0)) ? externalFiles[language][0].resolvedPath : null); } // #if TARGET == 'vscode' static preprocessUri(uri) { return uri; } static postprocessUri(uri) { return uri; } // #elseif TARGET == 'coc.nvim' // private static preprocessUri(uri: Code.Uri): string { // return uri.toString(); // } // private static postprocessUri(uri: string): Code.Uri { // return Code.Uri.parse(uri); // } // #endif getExternalFilesFromSetting(uri, settingName, language = null) { const resourceConfig = Code.workspace.getConfiguration('ltex', ExternalFileManager.preprocessUri(uri)); const settingValuePerScope = resourceConfig.inspect(settingName); const externalFiles = {}; for (const scope of [Code.ConfigurationTarget.Global, Code.ConfigurationTarget.Workspace, Code.ConfigurationTarget.WorkspaceFolder]) { const settingAnalysis = this.analyzeSetting(uri, settingName, scope, language, settingValuePerScope); const scopeExternalFiles = settingAnalysis.externalFiles; for (const curLanguage in scopeExternalFiles) { if (!Object.prototype.hasOwnProperty.call(scopeExternalFiles, curLanguage)) continue; if (!Object.prototype.hasOwnProperty.call(externalFiles, curLanguage)) { externalFiles[curLanguage] = []; } for (const externalFile of scopeExternalFiles[curLanguage]) { externalFiles[curLanguage].push(externalFile); } } } return externalFiles; } analyzeSetting(uri, settingName, scope, language = null, settingValuePerScope = undefined) { if (settingValuePerScope == null) { const resourceConfig = Code.workspace.getConfiguration('ltex', ExternalFileManager.preprocessUri(uri)); settingValuePerScope = resourceConfig.inspect(settingName); } let defaultDirPath = null; let settingValue = null; switch (scope) { case Code.ConfigurationTarget.Global: { defaultDirPath = this.getUserSettingsDirPath(); settingValue = ((settingValuePerScope != null) ? settingValuePerScope.globalValue : null); break; } case Code.ConfigurationTarget.Workspace: { defaultDirPath = this.getWorkspaceSettingsDirPath(); settingValue = ((settingValuePerScope != null) ? settingValuePerScope.workspaceValue : null); break; } case Code.ConfigurationTarget.WorkspaceFolder: { defaultDirPath = this.getWorkspaceFolderSettingsDirPath(uri); settingValue = ((settingValuePerScope != null) ? settingValuePerScope.workspaceFolderValue : null); break; } } const languages = ((language != null) ? [language] : this._languages); const externalFiles = {}; for (const curLanguage of languages) { externalFiles[curLanguage] = []; if ((settingValue != null) && Object.prototype.hasOwnProperty.call(settingValue, curLanguage)) { for (const entry of settingValue[curLanguage]) { if (!entry.startsWith(':')) continue; const originalFilePath = entry.substr(1); let filePath = ExternalFileManager.normalizePath(originalFilePath); if (!Path.isAbsolute(filePath) && (defaultDirPath != null)) { filePath = Path.resolve(defaultDirPath, filePath); } externalFiles[curLanguage].push({ originalPath: originalFilePath, resolvedPath: filePath, explicit: true, }); } } if (defaultDirPath != null) { const curLanguageSuffix = curLanguage.replace(/[^A-Za-z0-9\-_]/, ''); externalFiles[curLanguage].push({ originalPath: '', resolvedPath: Path.join(defaultDirPath, `ltex.${settingName}.${curLanguageSuffix}.txt`), explicit: false, }); } } if (settingValue == null) settingValue = null; return { settingValue: settingValue, externalFiles: externalFiles }; } getUserSettingsDirPath() { // #if TARGET == 'vscode' return Path.resolve(this._context.globalStorageUri.fsPath); // #elseif TARGET == 'coc.nvim' // return Path.resolve(this._context.storagePath); // #endif } getWorkspaceSettingsDirPath() { const workspaceFolders = Code.workspace.workspaceFolders; if ((workspaceFolders == null) || (workspaceFolders.length == 0)) return null; const workspaceDirUri = ExternalFileManager.postprocessUri(workspaceFolders[0].uri); if (workspaceDirUri.scheme != 'file') return null; return Path.resolve(workspaceDirUri.fsPath, '.vscode'); } getWorkspaceFolderSettingsDirPath(uri) { const workspaceFolder = Code.workspace.getWorkspaceFolder(ExternalFileManager.preprocessUri(uri)); if (workspaceFolder == null) return null; const workspaceFolderDirUri = ExternalFileManager.postprocessUri(workspaceFolder.uri); if (workspaceFolderDirUri.scheme != 'file') return null; return Path.resolve(workspaceFolderDirUri.fsPath, '.vscode'); } static normalizePath(path) { const match = path.match(/^~($|\/|\\\\)/); if (match != null) path = Path.resolve(Os.homedir(), path.substr(match[0].length)); return path; } onFileWatcherEvent(filePath, eventType, _) { if (!Fs.existsSync(filePath)) { Logger_1.default.log((0, I18n_1.i18n)('stoppedWatchingExternalSettingFileDueToDeletion', filePath)); for (const settingName of ExternalFileManager._settingNames) { if (!Object.prototype.hasOwnProperty.call(this._contents[settingName], filePath)) { continue; } delete this._watchers[settingName][filePath]; delete this._contents[settingName][filePath]; } } else if (eventType == 'change') { let contents = null; try { contents = Fs.readFileSync(filePath, { encoding: 'utf-8' }); } catch (e) { Logger_1.default.warn((0, I18n_1.i18n)('couldNotReadExternalSettingFile', filePath), e); return; } Logger_1.default.log((0, I18n_1.i18n)('externalSettingFileChangedReReading', filePath)); for (const settingName of ExternalFileManager._settingNames) { if (!Object.prototype.hasOwnProperty.call(this._contents[settingName], filePath)) continue; this._contents[settingName][filePath] = contents; } } } getSettingValue(uri, settingName, scope) { const settingAnalysis = this.analyzeSetting(uri, settingName, scope); const externalFiles = settingAnalysis.externalFiles; const settingValue = ((settingAnalysis.settingValue != null) ? settingAnalysis.settingValue : {}); const result = {}; for (const language in externalFiles) { if (!Object.prototype.hasOwnProperty.call(externalFiles, language)) continue; result[language] = []; for (const externalFile of externalFiles[language]) { this.loadFileAndPushToArray(externalFile.resolvedPath, settingName, result[language]); } } for (const language in settingValue) { if (!Object.prototype.hasOwnProperty.call(settingValue, language)) continue; if (!Object.prototype.hasOwnProperty.call(result, language)) result[language] = []; for (const entry of settingValue[language]) { if (entry.startsWith(':') && Object.prototype.hasOwnProperty.call(settingAnalysis.externalFiles, language)) { const filePath = ExternalFileManager.getResolvedPath(settingAnalysis.externalFiles[language], entry.substr(1)); if (filePath != null) { this.loadFileAndPushToArray(filePath, settingName, result[language]); } } else { result[language].push(entry); } } } return result; } loadFileAndPushToArray(filePath, settingName, array) { if (!Object.prototype.hasOwnProperty.call(this._contents[settingName], filePath)) return; const contents = this._contents[settingName][filePath]; for (const line of contents.split(/\r?\n/)) { const trimmedLine = line.trim(); if (trimmedLine.length > 0) array.push(line.trim()); } } static getResolvedPath(filePathInfos, originalFilePath) { for (const filePathInfo of filePathInfos) { if (filePathInfo.originalPath == originalFilePath) return filePathInfo.resolvedPath; } return null; } appendToFile(filePath, settingName, entries) { const externalFileKnown = Object.prototype.hasOwnProperty.call(this._contents[settingName], filePath); let contents; if (externalFileKnown) { contents = this._contents[settingName][filePath]; } else { this.ensureParentDirExists(filePath); this.ensureFileExists(filePath); try { contents = Fs.readFileSync(filePath, { encoding: 'utf-8' }); } catch (e) { Logger_1.default.error((0, I18n_1.i18n)('couldNotReadExternalSettingFile', filePath), e); return; } Logger_1.default.log((0, I18n_1.i18n)('readExternalSettingFile', filePath)); } if ((contents.match(/[^ \r\n]/) != null) && !contents.endsWith(Os.EOL)) contents += Os.EOL; contents += entries.join(Os.EOL) + Os.EOL; if (externalFileKnown) this.ensureParentDirExists(filePath); try { Fs.writeFileSync(filePath, contents, { encoding: 'utf-8' }); } catch (e) { Logger_1.default.error((0, I18n_1.i18n)('couldNotAppendNewEntriesToExternalSettingFile', filePath), e); return; } Logger_1.default.log((0, I18n_1.i18n)('appendedNewEntriesToExternalSettingFile', filePath)); if (externalFileKnown) this._contents[settingName][filePath] = contents; } ensureParentDirExists(filePath) { const parentDirPath = Path.dirname(filePath); if (!Fs.existsSync(parentDirPath)) { try { Fs.mkdirSync(parentDirPath); Logger_1.default.log((0, I18n_1.i18n)('createdDirectoryForExternalSettingFile', parentDirPath, filePath)); } catch (e) { Logger_1.default.warn((0, I18n_1.i18n)('couldNotCreateDirectoryForExternalSettingFile', parentDirPath, filePath), e); } } } ensureFileExists(filePath) { if (!Fs.existsSync(filePath)) { try { Fs.writeFileSync(filePath, '', { encoding: 'utf-8' }); Logger_1.default.log((0, I18n_1.i18n)('createdExternalSettingFile', filePath)); } catch (e) { Logger_1.default.warn((0, I18n_1.i18n)('couldNotCreateExternalSettingFile', filePath), e); } } } } exports["default"] = ExternalFileManager; ExternalFileManager._settingNames = [ 'dictionary', 'disabledRules', 'enabledRules', 'hiddenFalsePositives', ]; /***/ }), /***/ 6187: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /* Copyright (C) 2019-2021 Julian Valentin, LTeX Development Community * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.i18n = exports.I18n = void 0; // #elseif TARGET == 'coc.nvim' // import * as Code from 'coc.nvim'; // #endif const Fs = __importStar(__webpack_require__(7147)); const Path = __importStar(__webpack_require__(1017)); const Logger_1 = __importDefault(__webpack_require__(7819)); class I18n { static initialize(context) { this._language = I18n.getLanguage(); Logger_1.default.log(`Setting LTeX UI language to '${this._language}'.`); Logger_1.default.log('Loading i18n messages...'); this._messages = I18n.loadMessages(context); Logger_1.default.log('Loading default i18n messages...'); this._defaultMessages = I18n.loadDefaultMessages(context); } static getLanguage() { let language = 'en-US'; const codeNlsConfigStr = process.env['VSCODE_NLS_CONFIG']; if (codeNlsConfigStr != null) { try { const codeNlsConfig = JSON.parse(codeNlsConfigStr); language = codeNlsConfig.locale; } catch (_a) { // ignore errors, use default language } } return language; } static loadMessages(context) { let language = this._language.replace(/[^A-Za-z0-9\-_]/g, ''); while (true) { const filePath = Path.resolve(context.extensionPath, 'i18n', `messages.nls.${language}.json`); if (Fs.existsSync(filePath)) { return I18n.loadMessagesFile(filePath); } else { const index = language.indexOf('-'); if (index >= 0) { language = language.substr(0, index); } else { return I18n.loadDefaultMessages(context); } } } } static loadDefaultMessages(context) { return I18n.loadMessagesFile(Path.resolve(context.extensionPath, 'i18n', 'messages.nls.json')); } static loadMessagesFile(filePath) { const fileContents = Fs.readFileSync(filePath, { encoding: 'utf-8' }); return JSON.parse(fileContents); } static getMessage(key) { if (Object.prototype.hasOwnProperty.call(this._messages, key)) { return this._messages[key]; } else if (Object.prototype.hasOwnProperty.call(this._defaultMessages, key)) { return this._defaultMessages[key]; } else { Logger_1.default.warn(`Could not find i18n message key '${key}'.`); return key; } } static i18n(key, ...messageArguments) { return I18n.getMessage(key).replace(/\{(\d+)\}/g, (_match, groups) => { return String(messageArguments[parseInt(groups[0])]); }); } } exports.I18n = I18n; const i18n = I18n.i18n; exports.i18n = i18n; /***/ }), /***/ 7819: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /* Copyright (C) 2019-2021 Julian Valentin, LTeX Development Community * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); // #elseif TARGET == 'coc.nvim' // import * as Code from 'coc.nvim'; // import CodeLanguageClient = Code; // #endif const LoggingOutputChannel_1 = __importDefault(__webpack_require__(9199)); class Logger { static log(message, type = 'Info') { const timestamp = (new Date()).toISOString(); if (message == null) message = ''; const lines = message.split(/\r?\n/); lines.forEach((line) => { const logLine = `${timestamp} ${type}: ${line}`; Logger._clientOutputChannel.appendLine(logLine); }); } static warn(message, e) { Logger.log(message, 'Warning'); try { Logger.logError(e, 'Warning'); } catch (_a) { // do nothing } } static error(message, e) { Logger.log(message, 'Error'); try { Logger.logError(e, 'Error'); } catch (_a) { // do nothing } } static logError(e, type = 'Info') { Logger.log('Error details:', type); Logger.log(((e.stack != null) ? e.stack : `${e.name}: ${e.message}`), type); } static logExecutable(executable) { Logger.log(' Command: ' + JSON.stringify(executable.command)); Logger.log(' Arguments: ' + JSON.stringify(executable.args)); if (executable.options != null) { Logger.log(' env[\'JAVA_HOME\']: ' + JSON.stringify(executable.options.env['JAVA_HOME'])); Logger.log(' env[\'JAVA_OPTS\']: ' + JSON.stringify(executable.options.env['JAVA_OPTS'])); } } static createOutputChannels(context) { Logger._clientOutputChannel = new LoggingOutputChannel_1.default('LTeX Language Client'); Logger._serverOutputChannel = new LoggingOutputChannel_1.default('LTeX Language Server'); context.subscriptions.push(Logger._clientOutputChannel); context.subscriptions.push(Logger._serverOutputChannel); } static showClientOutputChannel() { Logger._clientOutputChannel.show(); } static get clientOutputChannel() { return Logger._clientOutputChannel; } static set clientOutputChannel(clientOutputChannel) { Logger._clientOutputChannel = clientOutputChannel; } static get serverOutputChannel() { return Logger._serverOutputChannel; } static set serverOutputChannel(serverOutputChannel) { Logger._serverOutputChannel = serverOutputChannel; } } exports["default"] = Logger; /***/ }), /***/ 9199: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /* Copyright (C) 2019-2021 Julian Valentin, LTeX Development Community * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", ({ value: true })); // #if TARGET == 'vscode' const Code = __importStar(__webpack_require__(9496)); var EventEmitter = Code.EventEmitter; class LoggingOutputChannel { constructor(name) { this.name = name; this._outputChannel = Code.window.createOutputChannel(name); this._entries = []; this._onAppendEventEmitter = new EventEmitter(); } pruneOldEntries() { const now = Date.now(); while (this._entries.length > 0) { if (now - this._entries[0].time >= 1000 * LoggingOutputChannel.pruneDuration) { this._entries.shift(); } else { break; } } } appendEntry(text) { this._entries.push({ time: Date.now(), text: text }); } append(value) { this._outputChannel.append(value); this.pruneOldEntries(); this.appendEntry(value); this._onAppendEventEmitter.fire(value); } appendLine(value) { this._outputChannel.appendLine(value); this.pruneOldEntries(); this.appendEntry(value + '\n'); this._onAppendEventEmitter.fire(value + '\n'); } get content() { let contents = ''; this._entries.forEach((entry) => { contents += entry.text; }); return contents; } onAppend(listener) { this._onAppendEventEmitter.event(listener); } clear() { this._outputChannel.clear(); this._entries = []; } show(_column, preserveFocus) { // #elseif TARGET == 'coc.nvim' // public show(preserveFocus?: boolean): void { // #endif this._outputChannel.show(preserveFocus); } hide() { this._outputChannel.hide(); } dispose() { this._onAppendEventEmitter.dispose(); this._outputChannel.dispose(); } } exports["default"] = LoggingOutputChannel; LoggingOutputChannel.pruneDuration = 86400; /***/ }), /***/ 6004: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* Copyright (C) 2019-2021 Julian Valentin, LTeX Development Community * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ Object.defineProperty(exports, "__esModule", ({ value: true })); // #elseif TARGET == 'coc.nvim' // import * as Code from 'coc.nvim'; // #endif const I18n_1 = __webpack_require__(6187); class ProgressStack { constructor(name, progressInterface) { this._taskProgressStack = [0]; this._taskSizeStack = [1]; this._taskNameStack = [name]; this._progressInterface = progressInterface; this._progressOnLastUpdate = 0; } startTask(size, name) { this._taskProgressStack.push(0); this._taskSizeStack.push(size); this._taskNameStack.push(name); this.showProgress(); } updateTask(progress, name) { const n = this._taskProgressStack.length; this._taskProgressStack[n - 1] = progress; if (name != null) this._taskNameStack[n - 1] = name; this.showProgress(); } finishTask() { const n = this._taskProgressStack.length - 1; if (n == 0) throw Error((0, I18n_1.i18n)('couldNotFinishTask')); this._taskProgressStack.pop(); this._taskProgressStack[n - 1] += this._taskSizeStack.pop(); this._taskNameStack.pop(); this.showProgress(); } getTaskName() { const n = this._taskProgressStack.length; return this._taskNameStack[n - 1]; } showProgress() { const n = this._taskProgressStack.length; let currentProgress = 0; let currentSize = 1; for (let i = 0; i < n; i++) { currentSize *= this._taskSizeStack[i]; currentProgress += currentSize * this._taskProgressStack[i]; } const progressIncrement = 100 * currentProgress - this._progressOnLastUpdate; const currentName = this._taskNameStack[n - 1]; this._progressInterface.report({ increment: progressIncrement, message: currentName }); this._progressOnLastUpdate = 100 * currentProgress; } } exports["default"] = ProgressStack; /***/ }), /***/ 5065: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /* Copyright (C) 2019-2021 Julian Valentin, LTeX Development Community * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); // #if TARGET == 'vscode' const Code = __importStar(__webpack_require__(9496)); // #elseif TARGET == 'coc.nvim' // import * as Code from 'coc.nvim'; // import CodeLanguageClient = Code; // #endif const I18n_1 = __webpack_require__(6187); const Logger_1 = __importDefault(__webpack_require__(7819)); var Status; (function (Status) { Status[Status["starting"] = 0] = "starting"; Status[Status["ready"] = 1] = "ready"; Status[Status["checking"] = 2] = "checking"; })(Status || (Status = {})); class StatusBarItemManager { constructor(context) { // #if TARGET == 'vscode' this._statusBarItem = Code.window.createStatusBarItem(Code.StatusBarAlignment.Left); // #elseif TARGET == 'coc.nvim' // this._statusBarItem = Code.window.createStatusBarItem(); // #endif this._progressMap = {}; this._status = Status.starting; // #if TARGET == 'vscode' this._startingStatusText = `$(loading~spin) ${(0, I18n_1.i18n)('startingLtex')}`; this._readyStatusText = `$(check) ${(0, I18n_1.i18n)('ltexReady')}`; this._checkingStatusText = `$(loading~spin) ${(0, I18n_1.i18n)('ltexIsChecking')}`; // #elseif TARGET == 'coc.nvim' // this._startingStatusText = i18n('startingLtex'); // this._readyStatusText = i18n('ltexReady'); // this._checkingStatusText = i18n('ltexIsChecking'); // #endif context.subscriptions.push(this._statusBarItem); context.subscriptions.push(Code.workspace.onDidChangeConfiguration(this.onDidChangeConfiguration, this)); this.setStatusToStarting(); } onDidChangeConfiguration(event) { if (event.affectsConfiguration('ltex.statusBarItem')) this.update(); } update() { if (this._status == Status.starting) { this._statusBarItem.text = this._startingStatusText; // #if TARGET == 'coc.nvim' // this._statusBarItem.isProgress = true; // #endif this._statusBarItem.show(); return; } const tokens = StatusBarItemManager.getKeys(this._progressMap); const now = Date.now(); for (const token of tokens) { if (now - this._progressMap[token].startTime >= StatusBarItemManager.checkingStatusDelay) { this._status = Status.checking; this._statusBarItem.text = this._checkingStatusText; // #if TARGET == 'coc.nvim' // this._statusBarItem.isProgress = true; // #endif this._statusBarItem.show(); return; } } const oldStatus = this._status; this._status = Status.ready; this._statusBarItem.text = this._readyStatusText; if (oldStatus == Status.checking) { this.setStatusToReady(); return; } const visible = Code.workspace.getConfiguration('ltex').get('statusBarItem'); if ((visible != null) && visible) { this._statusBarItem.show(); } else { this._statusBarItem.hide(); } } static getKeys(obj) { const result = []; for (const key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) result.push(key); } return result; } setStatusToStarting() { this._status = Status.starting; this.update(); } setStatusToReady() { this._status = Status.ready; this._statusBarItem.text = this._readyStatusText; // #if TARGET == 'coc.nvim' // this._statusBarItem.isProgress = true; // #endif this._statusBarItem.show(); setTimeout(this.update.bind(this), StatusBarItemManager.readyStatusDuration); } handleProgressNotification(params) { let token; try { token = JSON.parse(params.token.toString()); } catch (e) { Logger_1.default.warn((0, I18n_1.i18n)('couldNotParseTokenInProgressNotification', params.token, params)); return; } if (token.operation != 'checkDocument') { Logger_1.default.warn((0, I18n_1.i18n)('unknownOperationInProgressNotification', token.operation, params)); return; } if (params.value.kind == 'begin') { this._progressMap[params.token] = { progress: 0, startTime: Date.now() }; setTimeout(this.update.bind(this), StatusBarItemManager.checkingStatusDelay + 100); } else if (params.value.kind == 'end') { if (Object.prototype.hasOwnProperty.call(this._progressMap, params.token)) { delete this._progressMap[params.token]; this.update(); } } } } exports["default"] = StatusBarItemManager; StatusBarItemManager.readyStatusDuration = 1000; StatusBarItemManager.checkingStatusDelay = 5000; /***/ }), /***/ 84: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /* Copyright (C) 2019-2021 Julian Valentin, LTeX Development Community * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); // #if TARGET == 'vscode' const Code = __importStar(__webpack_require__(9496)); const I18n_1 = __webpack_require__(6187); const Logger_1 = __importDefault(__webpack_require__(7819)); class StatusPrinter { constructor(context, dependencyManager, externalFileManager) { this._context = context; this._dependencyManager = dependencyManager; this._externalFileManager = externalFileManager; this._languageClient = null; } set languageClient(languageClient) { this._languageClient = languageClient; } print() { return __awaiter(this, void 0, void 0, function* () { let ltexLsStatus = { success: false, processId: null, wallClockDuration: null, cpuDuration: null, cpuUsage: null, usedMemory: null, totalMemory: null, isChecking: null, documentUriBeingChecked: null, }; if (this._languageClient != null) { try { ltexLsStatus = yield this._languageClient.sendRequest('workspace/executeCommand', { command: '_ltex.getServerStatus', arguments: [] }); } catch (_a) { // ignore errors } } Logger_1.default.log((0, I18n_1.i18n)('ltexStatus')); Logger_1.default.log((0, I18n_1.i18n)('separationLine')); Logger_1.default.log((0, I18n_1.i18n)('vscodeLtexInfo')); Logger_1.default.log((0, I18n_1.i18n)('extensionDirPath', StatusPrinter.formatString(this._context.extensionPath))); Logger_1.default.log((0, I18n_1.i18n)('userSettingsDirPath', StatusPrinter.formatString(this._externalFileManager.getUserSettingsDirPath()))); Logger_1.default.log((0, I18n_1.i18n)('workspaceSettingsDirPath', StatusPrinter.formatString(this._externalFileManager.getWorkspaceSettingsDirPath()))); let activeDocumentUri = null; // #if TARGET == 'vscode' const activeTextEditor = Code.window.activeTextEditor; if (activeTextEditor != null) activeDocumentUri = activeTextEditor.document.uri; // #elseif TARGET == 'coc.nvim' // const activeDocument: Code.Document = await Code.workspace.document; // activeDocumentUri = Code.Uri.parse(activeDocument.uri); // #endif let workspaceFolderSettingsDirPath = null; if (activeDocumentUri != null) { workspaceFolderSettingsDirPath = this._externalFileManager.getWorkspaceFolderSettingsDirPath(activeDocumentUri); } Logger_1.default.log((0, I18n_1.i18n)('workspaceFolderSettingsDirPath', StatusPrinter.formatString(workspaceFolderSettingsDirPath))); Logger_1.default.log((0, I18n_1.i18n)('version', StatusPrinter.formatString(this._dependencyManager.vscodeLtexVersion))); Logger_1.default.log((0, I18n_1.i18n)('ltexLsInfo')); Logger_1.default.log((0, I18n_1.i18n)('version', StatusPrinter.formatString(this._dependencyManager.ltexLsVersion))); Logger_1.default.log((0, I18n_1.i18n)('processId', StatusPrinter.formatNumber(ltexLsStatus.processId))); Logger_1.default.log((0, I18n_1.i18n)('wallClockDuration', StatusPrinter.formatDuration(ltexLsStatus.wallClockDuration))); Logger_1.default.log((0, I18n_1.i18n)('cpuDuration', StatusPrinter.formatDuration(ltexLsStatus.cpuDuration))); Logger_1.default.log((0, I18n_1.i18n)('cpuUsage', StatusPrinter.formatFraction(ltexLsStatus.cpuUsage))); Logger_1.default.log((0, I18n_1.i18n)('totalMemory', StatusPrinter.formatMemory(ltexLsStatus.totalMemory))); Logger_1.default.log((0, I18n_1.i18n)('usedMemory', StatusPrinter.formatMemory(ltexLsStatus.usedMemory))); Logger_1.default.log((0, I18n_1.i18n)('isBusyChecking', StatusPrinter.formatBoolean(ltexLsStatus.isChecking))); Logger_1.default.log((0, I18n_1.i18n)('documentUriBeingChecked', StatusPrinter.formatString(ltexLsStatus.documentUriBeingChecked))); const watchedExternalFiles = this._externalFileManager.getAllWatchedExternalFiles(); if (watchedExternalFiles.length > 0) { Logger_1.default.log((0, I18n_1.i18n)('currentlyWatchedExternalSettingFiles')); for (const filePath of this._externalFileManager.getAllWatchedExternalFiles()) { Logger_1.default.log((0, I18n_1.i18n)('externalSettingFile', filePath)); } } else { Logger_1.default.log((0, I18n_1.i18n)('currentlyWatchedExternalSettingFilesNa')); } Logger_1.default.log((0, I18n_1.i18n)('separationLine')); return Promise.resolve(); }); } static formatString(str) { return ((str != null) ? str : (0, I18n_1.i18n)('na')); } static formatBoolean(x) { return ((x != null) ? (x ? (0, I18n_1.i18n)('true') : (0, I18n_1.i18n)('false')) : (0, I18n_1.i18n)('na')); } static formatNumber(x) { return ((x != null) ? `${x}` : (0, I18n_1.i18n)('na')); } static formatFraction(fraction) { return ((fraction != null) ? `${(100 * fraction).toFixed(1)}%` : (0, I18n_1.i18n)('na')); } static formatDuration(duration) { if (duration == null) return (0, I18n_1.i18n)('na'); const milliseconds = Math.floor(1000 * (duration % 1)); const seconds = Math.floor(duration % 60); const minutes = Math.floor(duration / 60) % 60; const hours = Math.floor(duration / 3600); const pad = ((x, length) => x.toString().padStart(length, '0')); if (hours > 0) { return `${hours}h${pad(minutes, 2)}m${pad(seconds, 2)}s.${pad(milliseconds, 3)}`; } else if (minutes > 0) { return `${minutes}m${pad(seconds, 2)}s.${pad(milliseconds, 3)}`; } else { return `${seconds}s.${pad(milliseconds, 3)}`; } } static formatMemory(memory) { return ((memory != null) ? `${(memory / 1e6).toFixed(2)}MB` : (0, I18n_1.i18n)('na')); } } exports["default"] = StatusPrinter; StatusPrinter._ltexLsStatusTimeout = 500; /***/ }), /***/ 4862: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /* Copyright (C) 2019-2021 Julian Valentin, LTeX Development Community * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", ({ value: true })); // #if TARGET == 'vscode' const Code = __importStar(__webpack_require__(9496)); class WorkspaceConfigurationRequestHandler { constructor(externalFileManager) { this._externalFileManager = externalFileManager; } mergeSettings(uri, settingName) { const result = {}; this._externalFileManager.updateWatchers(uri, settingName); const userSettingValue = this._externalFileManager.getSettingValue(uri, settingName, Code.ConfigurationTarget.Global); WorkspaceConfigurationRequestHandler.mergeLanguageSpecificSettingValue(result, userSettingValue); const workspaceSettingValue = this._externalFileManager.getSettingValue(uri, settingName, Code.ConfigurationTarget.Workspace); WorkspaceConfigurationRequestHandler.mergeLanguageSpecificSettingValue(result, workspaceSettingValue); const workspaceFolderSettingValue = this._externalFileManager.getSettingValue(uri, settingName, Code.ConfigurationTarget.WorkspaceFolder); WorkspaceConfigurationRequestHandler.mergeLanguageSpecificSettingValue(result, workspaceFolderSettingValue); for (const language in result) { if (!Object.prototype.hasOwnProperty.call(result, language)) continue; result[language] = WorkspaceConfigurationRequestHandler.cleanUpWorkspaceSpecificStringArray(result[language]); } return result; } static mergeLanguageSpecificSettingValue(value1, value2) { if (value2 == null) return; for (const language in value2) { if (!Object.prototype.hasOwnProperty.call(value2, language)) continue; if (!Object.prototype.hasOwnProperty.call(value1, language)) value1[language] = []; for (const entry of value2[language]) { value1[language].push(entry); } } } static cleanUpWorkspaceSpecificStringArray(array) { const negativeSet = new Set(); const positiveSet = new Set(); for (let entry of array) { if (entry.startsWith('-')) { entry = entry.substr(1); if (positiveSet.has(entry)) { positiveSet.delete(entry); } else { negativeSet.add(entry); } } else { positiveSet.add(entry); if (negativeSet.has(entry)) { negativeSet.delete(entry); } else { positiveSet.add(entry); } } } const result = []; for (const entry of negativeSet) result.push(`-${entry}`); for (const entry of positiveSet) result.push(entry); result.sort((a, b) => a.localeCompare(b, undefined, { sensitivity: 'base' })); return result; } handle(params) { const result = []; for (const item of params.items) { const uri = Code.Uri.parse(item.scopeUri); result.push({ dictionary: this.mergeSettings(uri, 'dictionary'), disabledRules: this.mergeSettings(uri, 'disabledRules'), enabledRules: this.mergeSettings(uri, 'enabledRules'), hiddenFalsePositives: this.mergeSettings(uri, 'hiddenFalsePositives'), }); } return result; } } exports["default"] = WorkspaceConfigurationRequestHandler; /***/ }), /***/ 7015: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /* Copyright (C) 2019-2021 Julian Valentin, LTeX Development Community * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.activate = exports.Api = void 0; // #if TARGET == 'vscode' const Code = __importStar(__webpack_require__(9496)); const CodeLanguageClient = __importStar(__webpack_require__(2847)); // #elseif TARGET == 'coc.nvim' // import * as Code from 'coc.nvim'; // import CodeLanguageClient = Code; // #endif const BugReporter_1 = __importDefault(__webpack_require__(265)); const CommandHandler_1 = __importDefault(__webpack_require__(1216)); const DependencyManager_1 = __importDefault(__webpack_require__(9604)); const ExternalFileManager_1 = __importDefault(__webpack_require__(4868)); const I18n_1 = __webpack_require__(6187); const Logger_1 = __importDefault(__webpack_require__(7819)); const StatusBarItemManager_1 = __importDefault(__webpack_require__(5065)); const StatusPrinter_1 = __importDefault(__webpack_require__(84)); const WorkspaceConfigurationRequestHandler_1 = __importDefault(__webpack_require__(4862)); class Api { constructor() { this.languageClient = null; this.clientOutputChannel = null; this.serverOutputChannel = null; } } exports.Api = Api; let dependencyManager = null; function languageClientIsReady(languageClient, externalFileManager, statusBarItemManager) { return __awaiter(this, void 0, void 0, function* () { statusBarItemManager.setStatusToReady(); languageClient.onNotification('$/progress', statusBarItemManager.handleProgressNotification.bind(statusBarItemManager)); const workspaceConfigurationRequestHandler = new WorkspaceConfigurationRequestHandler_1.default(externalFileManager); languageClient.onRequest('ltex/workspaceSpecificConfiguration', workspaceConfigurationRequestHandler.handle.bind(workspaceConfigurationRequestHandler)); }); } function startLanguageClient(context, externalFileManager, statusPrinter) { return __awaiter(this, void 0, void 0, function* () { let serverOptions = null; // #if TARGET == 'vscode' if (context.extensionMode == Code.ExtensionMode.Development) { serverOptions = DependencyManager_1.default.getDebugServerOptions(); } // #endif if (serverOptions == null) { if (dependencyManager == null) { Logger_1.default.error('DependencyManager not initialized!'); return Promise.resolve(null); } const success = yield dependencyManager.install(); if (success !== true) return Promise.resolve(null); serverOptions = yield dependencyManager.getLtexLsExecutable(); } const statusBarItemManager = new StatusBarItemManager_1.default(context); const workspaceConfig = Code.workspace.getConfiguration('ltex'); const enabled = workspaceConfig.get('enabled'); let enabledCodeLanguageIds; if ((enabled === true) || (enabled === false)) { enabledCodeLanguageIds = (enabled ? CommandHandler_1.default.getDefaultCodeLanguageIds() : []); } else { enabledCodeLanguageIds = enabled; } const documentSelector = []; for (const codeLanguageId of enabledCodeLanguageIds) { documentSelector.push({ scheme: 'file', language: codeLanguageId }); documentSelector.push({ scheme: 'untitled', language: codeLanguageId }); documentSelector.push({ scheme: 'vscode-notebook-cell', language: codeLanguageId }); } const clientOptions = { documentSelector: documentSelector, synchronize: { configurationSection: 'ltex', }, // LSP sends locale itself since LSP 3.16.0. However, this would require VS Code 1.53.0. // Currently, we only require VS Code 1.52.0. initializationOptions: { // #if TARGET == 'vscode' locale: Code.env.language, // #endif customCapabilities: { workspaceSpecificConfiguration: true, }, }, revealOutputChannelOn: CodeLanguageClient.RevealOutputChannelOn.Never, // #if TARGET == 'vscode' traceOutputChannel: Logger_1.default.clientOutputChannel, // #endif outputChannel: Logger_1.default.serverOutputChannel, }; const languageClient = new CodeLanguageClient.LanguageClient('ltex', (0, I18n_1.i18n)('ltexLanguageServer'), serverOptions, clientOptions); languageClient.onReady().then(languageClientIsReady.bind(null, languageClient, externalFileManager, statusBarItemManager)); statusPrinter.languageClient = languageClient; if ('command' in serverOptions) { Logger_1.default.log((0, I18n_1.i18n)('startingLtexLs')); Logger_1.default.logExecutable(serverOptions); Logger_1.default.log(''); } languageClient.info((0, I18n_1.i18n)('startingLtexLs')); const languageClientDisposable = languageClient.start(); context.subscriptions.push(languageClientDisposable); return Promise.resolve(languageClient); }); } function activate(context) { return __awaiter(this, void 0, void 0, function* () { Logger_1.default.createOutputChannels(context); I18n_1.I18n.initialize(context); const api = new Api(); api.clientOutputChannel = Logger_1.default.clientOutputChannel; api.serverOutputChannel = Logger_1.default.serverOutputChannel; dependencyManager = new DependencyManager_1.default(context); const externalFileManager = new ExternalFileManager_1.default(context); const statusPrinter = new StatusPrinter_1.default(context, dependencyManager, externalFileManager); const bugReporter = new BugReporter_1.default(context, dependencyManager, statusPrinter); const commandHandler = new CommandHandler_1.default(context, externalFileManager, statusPrinter, bugReporter); const workspaceConfig = Code.workspace.getConfiguration('ltex'); const enabled = workspaceConfig.get('enabled'); if ((enabled === true) || (enabled.length > 0)) { try { api.languageClient = yield startLanguageClient(context, externalFileManager, statusPrinter); commandHandler.languageClient = api.languageClient; } catch (e) { Logger_1.default.error((0, I18n_1.i18n)('couldNotStartLanguageClient'), e); Logger_1.default.showClientOutputChannel(); Code.window.showErrorMessage((0, I18n_1.i18n)('couldNotStartLanguageClient')); } } return Promise.resolve(api); }); } exports.activate = activate; /***/ }), /***/ 3870: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ /// Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CancellationSenderStrategy = exports.CancellationReceiverStrategy = exports.ConnectionError = exports.ConnectionErrors = exports.LogTraceNotification = exports.SetTraceNotification = exports.TraceFormat = exports.Trace = exports.ProgressType = exports.createMessageConnection = exports.NullLogger = exports.ConnectionOptions = exports.ConnectionStrategy = exports.WriteableStreamMessageWriter = exports.AbstractMessageWriter = exports.MessageWriter = exports.ReadableStreamMessageReader = exports.AbstractMessageReader = exports.MessageReader = exports.CancellationToken = exports.CancellationTokenSource = exports.Emitter = exports.Event = exports.Disposable = exports.ParameterStructures = exports.NotificationType9 = exports.NotificationType8 = exports.NotificationType7 = exports.NotificationType6 = exports.NotificationType5 = exports.NotificationType4 = exports.NotificationType3 = exports.NotificationType2 = exports.NotificationType1 = exports.NotificationType0 = exports.NotificationType = exports.ErrorCodes = exports.ResponseError = exports.RequestType9 = exports.RequestType8 = exports.RequestType7 = exports.RequestType6 = exports.RequestType5 = exports.RequestType4 = exports.RequestType3 = exports.RequestType2 = exports.RequestType1 = exports.RequestType0 = exports.RequestType = exports.RAL = void 0; exports.CancellationStrategy = void 0; const messages_1 = __webpack_require__(839); Object.defineProperty(exports, "RequestType", ({ enumerable: true, get: function () { return messages_1.RequestType; } })); Object.defineProperty(exports, "RequestType0", ({ enumerable: true, get: function () { return messages_1.RequestType0; } })); Object.defineProperty(exports, "RequestType1", ({ enumerable: true, get: function () { return messages_1.RequestType1; } })); Object.defineProperty(exports, "RequestType2", ({ enumerable: true, get: function () { return messages_1.RequestType2; } })); Object.defineProperty(exports, "RequestType3", ({ enumerable: true, get: function () { return messages_1.RequestType3; } })); Object.defineProperty(exports, "RequestType4", ({ enumerable: true, get: function () { return messages_1.RequestType4; } })); Object.defineProperty(exports, "RequestType5", ({ enumerable: true, get: function () { return messages_1.RequestType5; } })); Object.defineProperty(exports, "RequestType6", ({ enumerable: true, get: function () { return messages_1.RequestType6; } })); Object.defineProperty(exports, "RequestType7", ({ enumerable: true, get: function () { return messages_1.RequestType7; } })); Object.defineProperty(exports, "RequestType8", ({ enumerable: true, get: function () { return messages_1.RequestType8; } })); Object.defineProperty(exports, "RequestType9", ({ enumerable: true, get: function () { return messages_1.RequestType9; } })); Object.defineProperty(exports, "ResponseError", ({ enumerable: true, get: function () { return messages_1.ResponseError; } })); Object.defineProperty(exports, "ErrorCodes", ({ enumerable: true, get: function () { return messages_1.ErrorCodes; } })); Object.defineProperty(exports, "NotificationType", ({ enumerable: true, get: function () { return messages_1.NotificationType; } })); Object.defineProperty(exports, "NotificationType0", ({ enumerable: true, get: function () { return messages_1.NotificationType0; } })); Object.defineProperty(exports, "NotificationType1", ({ enumerable: true, get: function () { return messages_1.NotificationType1; } })); Object.defineProperty(exports, "NotificationType2", ({ enumerable: true, get: function () { return messages_1.NotificationType2; } })); Object.defineProperty(exports, "NotificationType3", ({ enumerable: true, get: function () { return messages_1.NotificationType3; } })); Object.defineProperty(exports, "NotificationType4", ({ enumerable: true, get: function () { return messages_1.NotificationType4; } })); Object.defineProperty(exports, "NotificationType5", ({ enumerable: true, get: function () { return messages_1.NotificationType5; } })); Object.defineProperty(exports, "NotificationType6", ({ enumerable: true, get: function () { return messages_1.NotificationType6; } })); Object.defineProperty(exports, "NotificationType7", ({ enumerable: true, get: function () { return messages_1.NotificationType7; } })); Object.defineProperty(exports, "NotificationType8", ({ enumerable: true, get: function () { return messages_1.NotificationType8; } })); Object.defineProperty(exports, "NotificationType9", ({ enumerable: true, get: function () { return messages_1.NotificationType9; } })); Object.defineProperty(exports, "ParameterStructures", ({ enumerable: true, get: function () { return messages_1.ParameterStructures; } })); const disposable_1 = __webpack_require__(3911); Object.defineProperty(exports, "Disposable", ({ enumerable: true, get: function () { return disposable_1.Disposable; } })); const events_1 = __webpack_require__(7135); Object.defineProperty(exports, "Event", ({ enumerable: true, get: function () { return events_1.Event; } })); Object.defineProperty(exports, "Emitter", ({ enumerable: true, get: function () { return events_1.Emitter; } })); const cancellation_1 = __webpack_require__(3881); Object.defineProperty(exports, "CancellationTokenSource", ({ enumerable: true, get: function () { return cancellation_1.CancellationTokenSource; } })); Object.defineProperty(exports, "CancellationToken", ({ enumerable: true, get: function () { return cancellation_1.CancellationToken; } })); const messageReader_1 = __webpack_require__(6525); Object.defineProperty(exports, "MessageReader", ({ enumerable: true, get: function () { return messageReader_1.MessageReader; } })); Object.defineProperty(exports, "AbstractMessageReader", ({ enumerable: true, get: function () { return messageReader_1.AbstractMessageReader; } })); Object.defineProperty(exports, "ReadableStreamMessageReader", ({ enumerable: true, get: function () { return messageReader_1.ReadableStreamMessageReader; } })); const messageWriter_1 = __webpack_require__(6654); Object.defineProperty(exports, "MessageWriter", ({ enumerable: true, get: function () { return messageWriter_1.MessageWriter; } })); Object.defineProperty(exports, "AbstractMessageWriter", ({ enumerable: true, get: function () { return messageWriter_1.AbstractMessageWriter; } })); Object.defineProperty(exports, "WriteableStreamMessageWriter", ({ enumerable: true, get: function () { return messageWriter_1.WriteableStreamMessageWriter; } })); const connection_1 = __webpack_require__(1343); Object.defineProperty(exports, "ConnectionStrategy", ({ enumerable: true, get: function () { return connection_1.ConnectionStrategy; } })); Object.defineProperty(exports, "ConnectionOptions", ({ enumerable: true, get: function () { return connection_1.ConnectionOptions; } })); Object.defineProperty(exports, "NullLogger", ({ enumerable: true, get: function () { return connection_1.NullLogger; } })); Object.defineProperty(exports, "createMessageConnection", ({ enumerable: true, get: function () { return connection_1.createMessageConnection; } })); Object.defineProperty(exports, "ProgressType", ({ enumerable: true, get: function () { return connection_1.ProgressType; } })); Object.defineProperty(exports, "Trace", ({ enumerable: true, get: function () { return connection_1.Trace; } })); Object.defineProperty(exports, "TraceFormat", ({ enumerable: true, get: function () { return connection_1.TraceFormat; } })); Object.defineProperty(exports, "SetTraceNotification", ({ enumerable: true, get: function () { return connection_1.SetTraceNotification; } })); Object.defineProperty(exports, "LogTraceNotification", ({ enumerable: true, get: function () { return connection_1.LogTraceNotification; } })); Object.defineProperty(exports, "ConnectionErrors", ({ enumerable: true, get: function () { return connection_1.ConnectionErrors; } })); Object.defineProperty(exports, "ConnectionError", ({ enumerable: true, get: function () { return connection_1.ConnectionError; } })); Object.defineProperty(exports, "CancellationReceiverStrategy", ({ enumerable: true, get: function () { return connection_1.CancellationReceiverStrategy; } })); Object.defineProperty(exports, "CancellationSenderStrategy", ({ enumerable: true, get: function () { return connection_1.CancellationSenderStrategy; } })); Object.defineProperty(exports, "CancellationStrategy", ({ enumerable: true, get: function () { return connection_1.CancellationStrategy; } })); const ral_1 = __webpack_require__(147); exports.RAL = ral_1.default; //# sourceMappingURL=api.js.map /***/ }), /***/ 3881: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CancellationTokenSource = exports.CancellationToken = void 0; const ral_1 = __webpack_require__(147); const Is = __webpack_require__(7574); const events_1 = __webpack_require__(7135); var CancellationToken; (function (CancellationToken) { CancellationToken.None = Object.freeze({ isCancellationRequested: false, onCancellationRequested: events_1.Event.None }); CancellationToken.Cancelled = Object.freeze({ isCancellationRequested: true, onCancellationRequested: events_1.Event.None }); function is(value) { const candidate = value; return candidate && (candidate === CancellationToken.None || candidate === CancellationToken.Cancelled || (Is.boolean(candidate.isCancellationRequested) && !!candidate.onCancellationRequested)); } CancellationToken.is = is; })(CancellationToken = exports.CancellationToken || (exports.CancellationToken = {})); const shortcutEvent = Object.freeze(function (callback, context) { const handle = ral_1.default().timer.setTimeout(callback.bind(context), 0); return { dispose() { ral_1.default().timer.clearTimeout(handle); } }; }); class MutableToken { constructor() { this._isCancelled = false; } cancel() { if (!this._isCancelled) { this._isCancelled = true; if (this._emitter) { this._emitter.fire(undefined); this.dispose(); } } } get isCancellationRequested() { return this._isCancelled; } get onCancellationRequested() { if (this._isCancelled) { return shortcutEvent; } if (!this._emitter) { this._emitter = new events_1.Emitter(); } return this._emitter.event; } dispose() { if (this._emitter) { this._emitter.dispose(); this._emitter = undefined; } } } class CancellationTokenSource { get token() { if (!this._token) { // be lazy and create the token only when // actually needed this._token = new MutableToken(); } return this._token; } cancel() { if (!this._token) { // save an object by returning the default // cancelled token when cancellation happens // before someone asks for the token this._token = CancellationToken.Cancelled; } else { this._token.cancel(); } } dispose() { if (!this._token) { // ensure to initialize with an empty token if we had none this._token = CancellationToken.None; } else if (this._token instanceof MutableToken) { // actually dispose this._token.dispose(); } } } exports.CancellationTokenSource = CancellationTokenSource; //# sourceMappingURL=cancellation.js.map /***/ }), /***/ 1343: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createMessageConnection = exports.ConnectionOptions = exports.CancellationStrategy = exports.CancellationSenderStrategy = exports.CancellationReceiverStrategy = exports.ConnectionStrategy = exports.ConnectionError = exports.ConnectionErrors = exports.LogTraceNotification = exports.SetTraceNotification = exports.TraceFormat = exports.Trace = exports.NullLogger = exports.ProgressType = void 0; const ral_1 = __webpack_require__(147); const Is = __webpack_require__(7574); const messages_1 = __webpack_require__(839); const linkedMap_1 = __webpack_require__(6184); const events_1 = __webpack_require__(7135); const cancellation_1 = __webpack_require__(3881); var CancelNotification; (function (CancelNotification) { CancelNotification.type = new messages_1.NotificationType('$/cancelRequest'); })(CancelNotification || (CancelNotification = {})); var ProgressNotification; (function (ProgressNotification) { ProgressNotification.type = new messages_1.NotificationType('$/progress'); })(ProgressNotification || (ProgressNotification = {})); class ProgressType { constructor() { } } exports.ProgressType = ProgressType; var StarRequestHandler; (function (StarRequestHandler) { function is(value) { return Is.func(value); } StarRequestHandler.is = is; })(StarRequestHandler || (StarRequestHandler = {})); exports.NullLogger = Object.freeze({ error: () => { }, warn: () => { }, info: () => { }, log: () => { } }); var Trace; (function (Trace) { Trace[Trace["Off"] = 0] = "Off"; Trace[Trace["Messages"] = 1] = "Messages"; Trace[Trace["Verbose"] = 2] = "Verbose"; })(Trace = exports.Trace || (exports.Trace = {})); (function (Trace) { function fromString(value) { if (!Is.string(value)) { return Trace.Off; } value = value.toLowerCase(); switch (value) { case 'off': return Trace.Off; case 'messages': return Trace.Messages; case 'verbose': return Trace.Verbose; default: return Trace.Off; } } Trace.fromString = fromString; function toString(value) { switch (value) { case Trace.Off: return 'off'; case Trace.Messages: return 'messages'; case Trace.Verbose: return 'verbose'; default: return 'off'; } } Trace.toString = toString; })(Trace = exports.Trace || (exports.Trace = {})); var TraceFormat; (function (TraceFormat) { TraceFormat["Text"] = "text"; TraceFormat["JSON"] = "json"; })(TraceFormat = exports.TraceFormat || (exports.TraceFormat = {})); (function (TraceFormat) { function fromString(value) { value = value.toLowerCase(); if (value === 'json') { return TraceFormat.JSON; } else { return TraceFormat.Text; } } TraceFormat.fromString = fromString; })(TraceFormat = exports.TraceFormat || (exports.TraceFormat = {})); var SetTraceNotification; (function (SetTraceNotification) { SetTraceNotification.type = new messages_1.NotificationType('$/setTrace'); })(SetTraceNotification = exports.SetTraceNotification || (exports.SetTraceNotification = {})); var LogTraceNotification; (function (LogTraceNotification) { LogTraceNotification.type = new messages_1.NotificationType('$/logTrace'); })(LogTraceNotification = exports.LogTraceNotification || (exports.LogTraceNotification = {})); var ConnectionErrors; (function (ConnectionErrors) { /** * The connection is closed. */ ConnectionErrors[ConnectionErrors["Closed"] = 1] = "Closed"; /** * The connection got disposed. */ ConnectionErrors[ConnectionErrors["Disposed"] = 2] = "Disposed"; /** * The connection is already in listening mode. */ ConnectionErrors[ConnectionErrors["AlreadyListening"] = 3] = "AlreadyListening"; })(ConnectionErrors = exports.ConnectionErrors || (exports.ConnectionErrors = {})); class ConnectionError extends Error { constructor(code, message) { super(message); this.code = code; Object.setPrototypeOf(this, ConnectionError.prototype); } } exports.ConnectionError = ConnectionError; var ConnectionStrategy; (function (ConnectionStrategy) { function is(value) { const candidate = value; return candidate && Is.func(candidate.cancelUndispatched); } ConnectionStrategy.is = is; })(ConnectionStrategy = exports.ConnectionStrategy || (exports.ConnectionStrategy = {})); var CancellationReceiverStrategy; (function (CancellationReceiverStrategy) { CancellationReceiverStrategy.Message = Object.freeze({ createCancellationTokenSource(_) { return new cancellation_1.CancellationTokenSource(); } }); function is(value) { const candidate = value; return candidate && Is.func(candidate.createCancellationTokenSource); } CancellationReceiverStrategy.is = is; })(CancellationReceiverStrategy = exports.CancellationReceiverStrategy || (exports.CancellationReceiverStrategy = {})); var CancellationSenderStrategy; (function (CancellationSenderStrategy) { CancellationSenderStrategy.Message = Object.freeze({ sendCancellation(conn, id) { conn.sendNotification(CancelNotification.type, { id }); }, cleanup(_) { } }); function is(value) { const candidate = value; return candidate && Is.func(candidate.sendCancellation) && Is.func(candidate.cleanup); } CancellationSenderStrategy.is = is; })(CancellationSenderStrategy = exports.CancellationSenderStrategy || (exports.CancellationSenderStrategy = {})); var CancellationStrategy; (function (CancellationStrategy) { CancellationStrategy.Message = Object.freeze({ receiver: CancellationReceiverStrategy.Message, sender: CancellationSenderStrategy.Message }); function is(value) { const candidate = value; return candidate && CancellationReceiverStrategy.is(candidate.receiver) && CancellationSenderStrategy.is(candidate.sender); } CancellationStrategy.is = is; })(CancellationStrategy = exports.CancellationStrategy || (exports.CancellationStrategy = {})); var ConnectionOptions; (function (ConnectionOptions) { function is(value) { const candidate = value; return candidate && (CancellationStrategy.is(candidate.cancellationStrategy) || ConnectionStrategy.is(candidate.connectionStrategy)); } ConnectionOptions.is = is; })(ConnectionOptions = exports.ConnectionOptions || (exports.ConnectionOptions = {})); var ConnectionState; (function (ConnectionState) { ConnectionState[ConnectionState["New"] = 1] = "New"; ConnectionState[ConnectionState["Listening"] = 2] = "Listening"; ConnectionState[ConnectionState["Closed"] = 3] = "Closed"; ConnectionState[ConnectionState["Disposed"] = 4] = "Disposed"; })(ConnectionState || (ConnectionState = {})); function createMessageConnection(messageReader, messageWriter, _logger, options) { const logger = _logger !== undefined ? _logger : exports.NullLogger; let sequenceNumber = 0; let notificationSquenceNumber = 0; let unknownResponseSquenceNumber = 0; const version = '2.0'; let starRequestHandler = undefined; const requestHandlers = Object.create(null); let starNotificationHandler = undefined; const notificationHandlers = Object.create(null); const progressHandlers = new Map(); let timer; let messageQueue = new linkedMap_1.LinkedMap(); let responsePromises = Object.create(null); let requestTokens = Object.create(null); let trace = Trace.Off; let traceFormat = TraceFormat.Text; let tracer; let state = ConnectionState.New; const errorEmitter = new events_1.Emitter(); const closeEmitter = new events_1.Emitter(); const unhandledNotificationEmitter = new events_1.Emitter(); const unhandledProgressEmitter = new events_1.Emitter(); const disposeEmitter = new events_1.Emitter(); const cancellationStrategy = (options && options.cancellationStrategy) ? options.cancellationStrategy : CancellationStrategy.Message; function createRequestQueueKey(id) { if (id === null) { throw new Error(`Can't send requests with id null since the response can't be correlated.`); } return 'req-' + id.toString(); } function createResponseQueueKey(id) { if (id === null) { return 'res-unknown-' + (++unknownResponseSquenceNumber).toString(); } else { return 'res-' + id.toString(); } } function createNotificationQueueKey() { return 'not-' + (++notificationSquenceNumber).toString(); } function addMessageToQueue(queue, message) { if (messages_1.isRequestMessage(message)) { queue.set(createRequestQueueKey(message.id), message); } else if (messages_1.isResponseMessage(message)) { queue.set(createResponseQueueKey(message.id), message); } else { queue.set(createNotificationQueueKey(), message); } } function cancelUndispatched(_message) { return undefined; } function isListening() { return state === ConnectionState.Listening; } function isClosed() { return state === ConnectionState.Closed; } function isDisposed() { return state === ConnectionState.Disposed; } function closeHandler() { if (state === ConnectionState.New || state === ConnectionState.Listening) { state = ConnectionState.Closed; closeEmitter.fire(undefined); } // If the connection is disposed don't sent close events. } function readErrorHandler(error) { errorEmitter.fire([error, undefined, undefined]); } function writeErrorHandler(data) { errorEmitter.fire(data); } messageReader.onClose(closeHandler); messageReader.onError(readErrorHandler); messageWriter.onClose(closeHandler); messageWriter.onError(writeErrorHandler); function triggerMessageQueue() { if (timer || messageQueue.size === 0) { return; } timer = ral_1.default().timer.setImmediate(() => { timer = undefined; processMessageQueue(); }); } function processMessageQueue() { if (messageQueue.size === 0) { return; } const message = messageQueue.shift(); try { if (messages_1.isRequestMessage(message)) { handleRequest(message); } else if (messages_1.isNotificationMessage(message)) { handleNotification(message); } else if (messages_1.isResponseMessage(message)) { handleResponse(message); } else { handleInvalidMessage(message); } } finally { triggerMessageQueue(); } } const callback = (message) => { try { // We have received a cancellation message. Check if the message is still in the queue // and cancel it if allowed to do so. if (messages_1.isNotificationMessage(message) && message.method === CancelNotification.type.method) { const key = createRequestQueueKey(message.params.id); const toCancel = messageQueue.get(key); if (messages_1.isRequestMessage(toCancel)) { const strategy = options === null || options === void 0 ? void 0 : options.connectionStrategy; const response = (strategy && strategy.cancelUndispatched) ? strategy.cancelUndispatched(toCancel, cancelUndispatched) : cancelUndispatched(toCancel); if (response && (response.error !== undefined || response.result !== undefined)) { messageQueue.delete(key); response.id = toCancel.id; traceSendingResponse(response, message.method, Date.now()); messageWriter.write(response); return; } } } addMessageToQueue(messageQueue, message); } finally { triggerMessageQueue(); } }; function handleRequest(requestMessage) { if (isDisposed()) { // we return here silently since we fired an event when the // connection got disposed. return; } function reply(resultOrError, method, startTime) { const message = { jsonrpc: version, id: requestMessage.id }; if (resultOrError instanceof messages_1.ResponseError) { message.error = resultOrError.toJson(); } else { message.result = resultOrError === undefined ? null : resultOrError; } traceSendingResponse(message, method, startTime); messageWriter.write(message); } function replyError(error, method, startTime) { const message = { jsonrpc: version, id: requestMessage.id, error: error.toJson() }; traceSendingResponse(message, method, startTime); messageWriter.write(message); } function replySuccess(result, method, startTime) { // The JSON RPC defines that a response must either have a result or an error // So we can't treat undefined as a valid response result. if (result === undefined) { result = null; } const message = { jsonrpc: version, id: requestMessage.id, result: result }; traceSendingResponse(message, method, startTime); messageWriter.write(message); } traceReceivedRequest(requestMessage); const element = requestHandlers[requestMessage.method]; let type; let requestHandler; if (element) { type = element.type; requestHandler = element.handler; } const startTime = Date.now(); if (requestHandler || starRequestHandler) { const tokenKey = String(requestMessage.id); const cancellationSource = cancellationStrategy.receiver.createCancellationTokenSource(tokenKey); requestTokens[tokenKey] = cancellationSource; try { let handlerResult; if (requestHandler) { if (requestMessage.params === undefined) { if (type !== undefined && type.numberOfParams !== 0) { replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InvalidParams, `Request ${requestMessage.method} defines ${type.numberOfParams} params but recevied none.`), requestMessage.method, startTime); return; } handlerResult = requestHandler(cancellationSource.token); } else if (Array.isArray(requestMessage.params)) { if (type !== undefined && type.parameterStructures === messages_1.ParameterStructures.byName) { replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InvalidParams, `Request ${requestMessage.method} defines parameters by name but received parameters by position`), requestMessage.method, startTime); return; } handlerResult = requestHandler(...requestMessage.params, cancellationSource.token); } else { if (type !== undefined && type.parameterStructures === messages_1.ParameterStructures.byPosition) { replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InvalidParams, `Request ${requestMessage.method} defines parameters by position but received parameters by name`), requestMessage.method, startTime); return; } handlerResult = requestHandler(requestMessage.params, cancellationSource.token); } } else if (starRequestHandler) { handlerResult = starRequestHandler(requestMessage.method, requestMessage.params, cancellationSource.token); } const promise = handlerResult; if (!handlerResult) { delete requestTokens[tokenKey]; replySuccess(handlerResult, requestMessage.method, startTime); } else if (promise.then) { promise.then((resultOrError) => { delete requestTokens[tokenKey]; reply(resultOrError, requestMessage.method, startTime); }, error => { delete requestTokens[tokenKey]; if (error instanceof messages_1.ResponseError) { replyError(error, requestMessage.method, startTime); } else if (error && Is.string(error.message)) { replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed with message: ${error.message}`), requestMessage.method, startTime); } else { replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime); } }); } else { delete requestTokens[tokenKey]; reply(handlerResult, requestMessage.method, startTime); } } catch (error) { delete requestTokens[tokenKey]; if (error instanceof messages_1.ResponseError) { reply(error, requestMessage.method, startTime); } else if (error && Is.string(error.message)) { replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed with message: ${error.message}`), requestMessage.method, startTime); } else { replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime); } } } else { replyError(new messages_1.ResponseError(messages_1.ErrorCodes.MethodNotFound, `Unhandled method ${requestMessage.method}`), requestMessage.method, startTime); } } function handleResponse(responseMessage) { if (isDisposed()) { // See handle request. return; } if (responseMessage.id === null) { if (responseMessage.error) { logger.error(`Received response message without id: Error is: \n${JSON.stringify(responseMessage.error, undefined, 4)}`); } else { logger.error(`Received response message without id. No further error information provided.`); } } else { const key = String(responseMessage.id); const responsePromise = responsePromises[key]; traceReceivedResponse(responseMessage, responsePromise); if (responsePromise) { delete responsePromises[key]; try { if (responseMessage.error) { const error = responseMessage.error; responsePromise.reject(new messages_1.ResponseError(error.code, error.message, error.data)); } else if (responseMessage.result !== undefined) { responsePromise.resolve(responseMessage.result); } else { throw new Error('Should never happen.'); } } catch (error) { if (error.message) { logger.error(`Response handler '${responsePromise.method}' failed with message: ${error.message}`); } else { logger.error(`Response handler '${responsePromise.method}' failed unexpectedly.`); } } } } } function handleNotification(message) { if (isDisposed()) { // See handle request. return; } let type = undefined; let notificationHandler; if (message.method === CancelNotification.type.method) { notificationHandler = (params) => { const id = params.id; const source = requestTokens[String(id)]; if (source) { source.cancel(); } }; } else { const element = notificationHandlers[message.method]; if (element) { notificationHandler = element.handler; type = element.type; } } if (notificationHandler || starNotificationHandler) { try { traceReceivedNotification(message); if (notificationHandler) { if (message.params === undefined) { if (type !== undefined) { if (type.numberOfParams !== 0 && type.parameterStructures !== messages_1.ParameterStructures.byName) { logger.error(`Notification ${message.method} defines ${type.numberOfParams} params but recevied none.`); } } notificationHandler(); } else if (Array.isArray(message.params)) { if (type !== undefined) { if (type.parameterStructures === messages_1.ParameterStructures.byName) { logger.error(`Notification ${message.method} defines parameters by name but received parameters by position`); } if (type.numberOfParams !== message.params.length) { logger.error(`Notification ${message.method} defines ${type.numberOfParams} params but received ${message.params.length} argumennts`); } } notificationHandler(...message.params); } else { if (type !== undefined && type.parameterStructures === messages_1.ParameterStructures.byPosition) { logger.error(`Notification ${message.method} defines parameters by position but received parameters by name`); } notificationHandler(message.params); } } else if (starNotificationHandler) { starNotificationHandler(message.method, message.params); } } catch (error) { if (error.message) { logger.error(`Notification handler '${message.method}' failed with message: ${error.message}`); } else { logger.error(`Notification handler '${message.method}' failed unexpectedly.`); } } } else { unhandledNotificationEmitter.fire(message); } } function handleInvalidMessage(message) { if (!message) { logger.error('Received empty message.'); return; } logger.error(`Received message which is neither a response nor a notification message:\n${JSON.stringify(message, null, 4)}`); // Test whether we find an id to reject the promise const responseMessage = message; if (Is.string(responseMessage.id) || Is.number(responseMessage.id)) { const key = String(responseMessage.id); const responseHandler = responsePromises[key]; if (responseHandler) { responseHandler.reject(new Error('The received response has neither a result nor an error property.')); } } } function traceSendingRequest(message) { if (trace === Trace.Off || !tracer) { return; } if (traceFormat === TraceFormat.Text) { let data = undefined; if (trace === Trace.Verbose && message.params) { data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`; } tracer.log(`Sending request '${message.method} - (${message.id})'.`, data); } else { logLSPMessage('send-request', message); } } function traceSendingNotification(message) { if (trace === Trace.Off || !tracer) { return; } if (traceFormat === TraceFormat.Text) { let data = undefined; if (trace === Trace.Verbose) { if (message.params) { data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`; } else { data = 'No parameters provided.\n\n'; } } tracer.log(`Sending notification '${message.method}'.`, data); } else { logLSPMessage('send-notification', message); } } function traceSendingResponse(message, method, startTime) { if (trace === Trace.Off || !tracer) { return; } if (traceFormat === TraceFormat.Text) { let data = undefined; if (trace === Trace.Verbose) { if (message.error && message.error.data) { data = `Error data: ${JSON.stringify(message.error.data, null, 4)}\n\n`; } else { if (message.result) { data = `Result: ${JSON.stringify(message.result, null, 4)}\n\n`; } else if (message.error === undefined) { data = 'No result returned.\n\n'; } } } tracer.log(`Sending response '${method} - (${message.id})'. Processing request took ${Date.now() - startTime}ms`, data); } else { logLSPMessage('send-response', message); } } function traceReceivedRequest(message) { if (trace === Trace.Off || !tracer) { return; } if (traceFormat === TraceFormat.Text) { let data = undefined; if (trace === Trace.Verbose && message.params) { data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`; } tracer.log(`Received request '${message.method} - (${message.id})'.`, data); } else { logLSPMessage('receive-request', message); } } function traceReceivedNotification(message) { if (trace === Trace.Off || !tracer || message.method === LogTraceNotification.type.method) { return; } if (traceFormat === TraceFormat.Text) { let data = undefined; if (trace === Trace.Verbose) { if (message.params) { data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`; } else { data = 'No parameters provided.\n\n'; } } tracer.log(`Received notification '${message.method}'.`, data); } else { logLSPMessage('receive-notification', message); } } function traceReceivedResponse(message, responsePromise) { if (trace === Trace.Off || !tracer) { return; } if (traceFormat === TraceFormat.Text) { let data = undefined; if (trace === Trace.Verbose) { if (message.error && message.error.data) { data = `Error data: ${JSON.stringify(message.error.data, null, 4)}\n\n`; } else { if (message.result) { data = `Result: ${JSON.stringify(message.result, null, 4)}\n\n`; } else if (message.error === undefined) { data = 'No result returned.\n\n'; } } } if (responsePromise) { const error = message.error ? ` Request failed: ${message.error.message} (${message.error.code}).` : ''; tracer.log(`Received response '${responsePromise.method} - (${message.id})' in ${Date.now() - responsePromise.timerStart}ms.${error}`, data); } else { tracer.log(`Received response ${message.id} without active response promise.`, data); } } else { logLSPMessage('receive-response', message); } } function logLSPMessage(type, message) { if (!tracer || trace === Trace.Off) { return; } const lspMessage = { isLSPMessage: true, type, message, timestamp: Date.now() }; tracer.log(lspMessage); } function throwIfClosedOrDisposed() { if (isClosed()) { throw new ConnectionError(ConnectionErrors.Closed, 'Connection is closed.'); } if (isDisposed()) { throw new ConnectionError(ConnectionErrors.Disposed, 'Connection is disposed.'); } } function throwIfListening() { if (isListening()) { throw new ConnectionError(ConnectionErrors.AlreadyListening, 'Connection is already listening'); } } function throwIfNotListening() { if (!isListening()) { throw new Error('Call listen() first.'); } } function undefinedToNull(param) { if (param === undefined) { return null; } else { return param; } } function nullToUndefined(param) { if (param === null) { return undefined; } else { return param; } } function isNamedParam(param) { return param !== undefined && param !== null && !Array.isArray(param) && typeof param === 'object'; } function computeSingleParam(parameterStructures, param) { switch (parameterStructures) { case messages_1.ParameterStructures.auto: if (isNamedParam(param)) { return nullToUndefined(param); } else { return [undefinedToNull(param)]; } break; case messages_1.ParameterStructures.byName: if (!isNamedParam(param)) { throw new Error(`Recevied parameters by name but param is not an object literal.`); } return nullToUndefined(param); case messages_1.ParameterStructures.byPosition: return [undefinedToNull(param)]; default: throw new Error(`Unknown parameter structure ${parameterStructures.toString()}`); } } function computeMessageParams(type, params) { let result; const numberOfParams = type.numberOfParams; switch (numberOfParams) { case 0: result = undefined; break; case 1: result = computeSingleParam(type.parameterStructures, params[0]); break; default: result = []; for (let i = 0; i < params.length && i < numberOfParams; i++) { result.push(undefinedToNull(params[i])); } if (params.length < numberOfParams) { for (let i = params.length; i < numberOfParams; i++) { result.push(null); } } break; } return result; } const connection = { sendNotification: (type, ...args) => { throwIfClosedOrDisposed(); let method; let messageParams; if (Is.string(type)) { method = type; const first = args[0]; let paramStart = 0; let parameterStructures = messages_1.ParameterStructures.auto; if (messages_1.ParameterStructures.is(first)) { paramStart = 1; parameterStructures = first; } let paramEnd = args.length; const numberOfParams = paramEnd - paramStart; switch (numberOfParams) { case 0: messageParams = undefined; break; case 1: messageParams = computeSingleParam(parameterStructures, args[paramStart]); break; default: if (parameterStructures === messages_1.ParameterStructures.byName) { throw new Error(`Recevied ${numberOfParams} parameters for 'by Name' notification parameter structure.`); } messageParams = args.slice(paramStart, paramEnd).map(value => undefinedToNull(value)); break; } } else { const params = args; method = type.method; messageParams = computeMessageParams(type, params); } const notificationMessage = { jsonrpc: version, method: method, params: messageParams }; traceSendingNotification(notificationMessage); messageWriter.write(notificationMessage); }, onNotification: (type, handler) => { throwIfClosedOrDisposed(); let method; if (Is.func(type)) { starNotificationHandler = type; } else if (handler) { if (Is.string(type)) { method = type; notificationHandlers[type] = { type: undefined, handler }; } else { method = type.method; notificationHandlers[type.method] = { type, handler }; } } return { dispose: () => { if (method !== undefined) { delete notificationHandlers[method]; } else { starNotificationHandler = undefined; } } }; }, onProgress: (_type, token, handler) => { if (progressHandlers.has(token)) { throw new Error(`Progress handler for token ${token} already registered`); } progressHandlers.set(token, handler); return { dispose: () => { progressHandlers.delete(token); } }; }, sendProgress: (_type, token, value) => { connection.sendNotification(ProgressNotification.type, { token, value }); }, onUnhandledProgress: unhandledProgressEmitter.event, sendRequest: (type, ...args) => { throwIfClosedOrDisposed(); throwIfNotListening(); let method; let messageParams; let token = undefined; if (Is.string(type)) { method = type; const first = args[0]; const last = args[args.length - 1]; let paramStart = 0; let parameterStructures = messages_1.ParameterStructures.auto; if (messages_1.ParameterStructures.is(first)) { paramStart = 1; parameterStructures = first; } let paramEnd = args.length; if (cancellation_1.CancellationToken.is(last)) { paramEnd = paramEnd - 1; token = last; } const numberOfParams = paramEnd - paramStart; switch (numberOfParams) { case 0: messageParams = undefined; break; case 1: messageParams = computeSingleParam(parameterStructures, args[paramStart]); break; default: if (parameterStructures === messages_1.ParameterStructures.byName) { throw new Error(`Recevied ${numberOfParams} parameters for 'by Name' request parameter structure.`); } messageParams = args.slice(paramStart, paramEnd).map(value => undefinedToNull(value)); break; } } else { const params = args; method = type.method; messageParams = computeMessageParams(type, params); const numberOfParams = type.numberOfParams; token = cancellation_1.CancellationToken.is(params[numberOfParams]) ? params[numberOfParams] : undefined; } const id = sequenceNumber++; let disposable; if (token) { disposable = token.onCancellationRequested(() => { cancellationStrategy.sender.sendCancellation(connection, id); }); } const result = new Promise((resolve, reject) => { const requestMessage = { jsonrpc: version, id: id, method: method, params: messageParams }; const resolveWithCleanup = (r) => { resolve(r); cancellationStrategy.sender.cleanup(id); disposable === null || disposable === void 0 ? void 0 : disposable.dispose(); }; const rejectWithCleanup = (r) => { reject(r); cancellationStrategy.sender.cleanup(id); disposable === null || disposable === void 0 ? void 0 : disposable.dispose(); }; let responsePromise = { method: method, timerStart: Date.now(), resolve: resolveWithCleanup, reject: rejectWithCleanup }; traceSendingRequest(requestMessage); try { messageWriter.write(requestMessage); } catch (e) { // Writing the message failed. So we need to reject the promise. responsePromise.reject(new messages_1.ResponseError(messages_1.ErrorCodes.MessageWriteError, e.message ? e.message : 'Unknown reason')); responsePromise = null; } if (responsePromise) { responsePromises[String(id)] = responsePromise; } }); return result; }, onRequest: (type, handler) => { throwIfClosedOrDisposed(); let method = null; if (StarRequestHandler.is(type)) { method = undefined; starRequestHandler = type; } else if (Is.string(type)) { method = null; if (handler !== undefined) { method = type; requestHandlers[type] = { handler: handler, type: undefined }; } } else { if (handler !== undefined) { method = type.method; requestHandlers[type.method] = { type, handler }; } } return { dispose: () => { if (method === null) { return; } if (method !== undefined) { delete requestHandlers[method]; } else { starRequestHandler = undefined; } } }; }, trace: (_value, _tracer, sendNotificationOrTraceOptions) => { let _sendNotification = false; let _traceFormat = TraceFormat.Text; if (sendNotificationOrTraceOptions !== undefined) { if (Is.boolean(sendNotificationOrTraceOptions)) { _sendNotification = sendNotificationOrTraceOptions; } else { _sendNotification = sendNotificationOrTraceOptions.sendNotification || false; _traceFormat = sendNotificationOrTraceOptions.traceFormat || TraceFormat.Text; } } trace = _value; traceFormat = _traceFormat; if (trace === Trace.Off) { tracer = undefined; } else { tracer = _tracer; } if (_sendNotification && !isClosed() && !isDisposed()) { connection.sendNotification(SetTraceNotification.type, { value: Trace.toString(_value) }); } }, onError: errorEmitter.event, onClose: closeEmitter.event, onUnhandledNotification: unhandledNotificationEmitter.event, onDispose: disposeEmitter.event, end: () => { messageWriter.end(); }, dispose: () => { if (isDisposed()) { return; } state = ConnectionState.Disposed; disposeEmitter.fire(undefined); const error = new Error('Connection got disposed.'); Object.keys(responsePromises).forEach((key) => { responsePromises[key].reject(error); }); responsePromises = Object.create(null); requestTokens = Object.create(null); messageQueue = new linkedMap_1.LinkedMap(); // Test for backwards compatibility if (Is.func(messageWriter.dispose)) { messageWriter.dispose(); } if (Is.func(messageReader.dispose)) { messageReader.dispose(); } }, listen: () => { throwIfClosedOrDisposed(); throwIfListening(); state = ConnectionState.Listening; messageReader.listen(callback); }, inspect: () => { // eslint-disable-next-line no-console ral_1.default().console.log('inspect'); } }; connection.onNotification(LogTraceNotification.type, (params) => { if (trace === Trace.Off || !tracer) { return; } tracer.log(params.message, trace === Trace.Verbose ? params.verbose : undefined); }); connection.onNotification(ProgressNotification.type, (params) => { const handler = progressHandlers.get(params.token); if (handler) { handler(params.value); } else { unhandledProgressEmitter.fire(params); } }); return connection; } exports.createMessageConnection = createMessageConnection; //# sourceMappingURL=connection.js.map /***/ }), /***/ 3911: /***/ ((__unused_webpack_module, exports) => { "use strict"; /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Disposable = void 0; var Disposable; (function (Disposable) { function create(func) { return { dispose: func }; } Disposable.create = create; })(Disposable = exports.Disposable || (exports.Disposable = {})); //# sourceMappingURL=disposable.js.map /***/ }), /***/ 7135: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Emitter = exports.Event = void 0; const ral_1 = __webpack_require__(147); var Event; (function (Event) { const _disposable = { dispose() { } }; Event.None = function () { return _disposable; }; })(Event = exports.Event || (exports.Event = {})); class CallbackList { add(callback, context = null, bucket) { if (!this._callbacks) { this._callbacks = []; this._contexts = []; } this._callbacks.push(callback); this._contexts.push(context); if (Array.isArray(bucket)) { bucket.push({ dispose: () => this.remove(callback, context) }); } } remove(callback, context = null) { if (!this._callbacks) { return; } let foundCallbackWithDifferentContext = false; for (let i = 0, len = this._callbacks.length; i < len; i++) { if (this._callbacks[i] === callback) { if (this._contexts[i] === context) { // callback & context match => remove it this._callbacks.splice(i, 1); this._contexts.splice(i, 1); return; } else { foundCallbackWithDifferentContext = true; } } } if (foundCallbackWithDifferentContext) { throw new Error('When adding a listener with a context, you should remove it with the same context'); } } invoke(...args) { if (!this._callbacks) { return []; } const ret = [], callbacks = this._callbacks.slice(0), contexts = this._contexts.slice(0); for (let i = 0, len = callbacks.length; i < len; i++) { try { ret.push(callbacks[i].apply(contexts[i], args)); } catch (e) { // eslint-disable-next-line no-console ral_1.default().console.error(e); } } return ret; } isEmpty() { return !this._callbacks || this._callbacks.length === 0; } dispose() { this._callbacks = undefined; this._contexts = undefined; } } class Emitter { constructor(_options) { this._options = _options; } /** * For the public to allow to subscribe * to events from this Emitter */ get event() { if (!this._event) { this._event = (listener, thisArgs, disposables) => { if (!this._callbacks) { this._callbacks = new CallbackList(); } if (this._options && this._options.onFirstListenerAdd && this._callbacks.isEmpty()) { this._options.onFirstListenerAdd(this); } this._callbacks.add(listener, thisArgs); const result = { dispose: () => { if (!this._callbacks) { // disposable is disposed after emitter is disposed. return; } this._callbacks.remove(listener, thisArgs); result.dispose = Emitter._noop; if (this._options && this._options.onLastListenerRemove && this._callbacks.isEmpty()) { this._options.onLastListenerRemove(this); } } }; if (Array.isArray(disposables)) { disposables.push(result); } return result; }; } return this._event; } /** * To be kept private to fire an event to * subscribers */ fire(event) { if (this._callbacks) { this._callbacks.invoke.call(this._callbacks, event); } } dispose() { if (this._callbacks) { this._callbacks.dispose(); this._callbacks = undefined; } } } exports.Emitter = Emitter; Emitter._noop = function () { }; //# sourceMappingURL=events.js.map /***/ }), /***/ 7574: /***/ ((__unused_webpack_module, exports) => { "use strict"; /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.stringArray = exports.array = exports.func = exports.error = exports.number = exports.string = exports.boolean = void 0; function boolean(value) { return value === true || value === false; } exports.boolean = boolean; function string(value) { return typeof value === 'string' || value instanceof String; } exports.string = string; function number(value) { return typeof value === 'number' || value instanceof Number; } exports.number = number; function error(value) { return value instanceof Error; } exports.error = error; function func(value) { return typeof value === 'function'; } exports.func = func; function array(value) { return Array.isArray(value); } exports.array = array; function stringArray(value) { return array(value) && value.every(elem => string(elem)); } exports.stringArray = stringArray; //# sourceMappingURL=is.js.map /***/ }), /***/ 6184: /***/ ((__unused_webpack_module, exports) => { "use strict"; /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.LRUCache = exports.LinkedMap = exports.Touch = void 0; var Touch; (function (Touch) { Touch.None = 0; Touch.First = 1; Touch.AsOld = Touch.First; Touch.Last = 2; Touch.AsNew = Touch.Last; })(Touch = exports.Touch || (exports.Touch = {})); class LinkedMap { constructor() { this[Symbol.toStringTag] = 'LinkedMap'; this._map = new Map(); this._head = undefined; this._tail = undefined; this._size = 0; this._state = 0; } clear() { this._map.clear(); this._head = undefined; this._tail = undefined; this._size = 0; this._state++; } isEmpty() { return !this._head && !this._tail; } get size() { return this._size; } get first() { var _a; return (_a = this._head) === null || _a === void 0 ? void 0 : _a.value; } get last() { var _a; return (_a = this._tail) === null || _a === void 0 ? void 0 : _a.value; } has(key) { return this._map.has(key); } get(key, touch = Touch.None) { const item = this._map.get(key); if (!item) { return undefined; } if (touch !== Touch.None) { this.touch(item, touch); } return item.value; } set(key, value, touch = Touch.None) { let item = this._map.get(key); if (item) { item.value = value; if (touch !== Touch.None) { this.touch(item, touch); } } else { item = { key, value, next: undefined, previous: undefined }; switch (touch) { case Touch.None: this.addItemLast(item); break; case Touch.First: this.addItemFirst(item); break; case Touch.Last: this.addItemLast(item); break; default: this.addItemLast(item); break; } this._map.set(key, item); this._size++; } return this; } delete(key) { return !!this.remove(key); } remove(key) { const item = this._map.get(key); if (!item) { return undefined; } this._map.delete(key); this.removeItem(item); this._size--; return item.value; } shift() { if (!this._head && !this._tail) { return undefined; } if (!this._head || !this._tail) { throw new Error('Invalid list'); } const item = this._head; this._map.delete(item.key); this.removeItem(item); this._size--; return item.value; } forEach(callbackfn, thisArg) { const state = this._state; let current = this._head; while (current) { if (thisArg) { callbackfn.bind(thisArg)(current.value, current.key, this); } else { callbackfn(current.value, current.key, this); } if (this._state !== state) { throw new Error(`LinkedMap got modified during iteration.`); } current = current.next; } } keys() { const map = this; const state = this._state; let current = this._head; const iterator = { [Symbol.iterator]() { return iterator; }, next() { if (map._state !== state) { throw new Error(`LinkedMap got modified during iteration.`); } if (current) { const result = { value: current.key, done: false }; current = current.next; return result; } else { return { value: undefined, done: true }; } } }; return iterator; } values() { const map = this; const state = this._state; let current = this._head; const iterator = { [Symbol.iterator]() { return iterator; }, next() { if (map._state !== state) { throw new Error(`LinkedMap got modified during iteration.`); } if (current) { const result = { value: current.value, done: false }; current = current.next; return result; } else { return { value: undefined, done: true }; } } }; return iterator; } entries() { const map = this; const state = this._state; let current = this._head; const iterator = { [Symbol.iterator]() { return iterator; }, next() { if (map._state !== state) { throw new Error(`LinkedMap got modified during iteration.`); } if (current) { const result = { value: [current.key, current.value], done: false }; current = current.next; return result; } else { return { value: undefined, done: true }; } } }; return iterator; } [Symbol.iterator]() { return this.entries(); } trimOld(newSize) { if (newSize >= this.size) { return; } if (newSize === 0) { this.clear(); return; } let current = this._head; let currentSize = this.size; while (current && currentSize > newSize) { this._map.delete(current.key); current = current.next; currentSize--; } this._head = current; this._size = currentSize; if (current) { current.previous = undefined; } this._state++; } addItemFirst(item) { // First time Insert if (!this._head && !this._tail) { this._tail = item; } else if (!this._head) { throw new Error('Invalid list'); } else { item.next = this._head; this._head.previous = item; } this._head = item; this._state++; } addItemLast(item) { // First time Insert if (!this._head && !this._tail) { this._head = item; } else if (!this._tail) { throw new Error('Invalid list'); } else { item.previous = this._tail; this._tail.next = item; } this._tail = item; this._state++; } removeItem(item) { if (item === this._head && item === this._tail) { this._head = undefined; this._tail = undefined; } else if (item === this._head) { // This can only happend if size === 1 which is handle // by the case above. if (!item.next) { throw new Error('Invalid list'); } item.next.previous = undefined; this._head = item.next; } else if (item === this._tail) { // This can only happend if size === 1 which is handle // by the case above. if (!item.previous) { throw new Error('Invalid list'); } item.previous.next = undefined; this._tail = item.previous; } else { const next = item.next; const previous = item.previous; if (!next || !previous) { throw new Error('Invalid list'); } next.previous = previous; previous.next = next; } item.next = undefined; item.previous = undefined; this._state++; } touch(item, touch) { if (!this._head || !this._tail) { throw new Error('Invalid list'); } if ((touch !== Touch.First && touch !== Touch.Last)) { return; } if (touch === Touch.First) { if (item === this._head) { return; } const next = item.next; const previous = item.previous; // Unlink the item if (item === this._tail) { // previous must be defined since item was not head but is tail // So there are more than on item in the map previous.next = undefined; this._tail = previous; } else { // Both next and previous are not undefined since item was neither head nor tail. next.previous = previous; previous.next = next; } // Insert the node at head item.previous = undefined; item.next = this._head; this._head.previous = item; this._head = item; this._state++; } else if (touch === Touch.Last) { if (item === this._tail) { return; } const next = item.next; const previous = item.previous; // Unlink the item. if (item === this._head) { // next must be defined since item was not tail but is head // So there are more than on item in the map next.previous = undefined; this._head = next; } else { // Both next and previous are not undefined since item was neither head nor tail. next.previous = previous; previous.next = next; } item.next = undefined; item.previous = this._tail; this._tail.next = item; this._tail = item; this._state++; } } toJSON() { const data = []; this.forEach((value, key) => { data.push([key, value]); }); return data; } fromJSON(data) { this.clear(); for (const [key, value] of data) { this.set(key, value); } } } exports.LinkedMap = LinkedMap; class LRUCache extends LinkedMap { constructor(limit, ratio = 1) { super(); this._limit = limit; this._ratio = Math.min(Math.max(0, ratio), 1); } get limit() { return this._limit; } set limit(limit) { this._limit = limit; this.checkTrim(); } get ratio() { return this._ratio; } set ratio(ratio) { this._ratio = Math.min(Math.max(0, ratio), 1); this.checkTrim(); } get(key, touch = Touch.AsNew) { return super.get(key, touch); } peek(key) { return super.get(key, Touch.None); } set(key, value) { super.set(key, value, Touch.Last); this.checkTrim(); return this; } checkTrim() { if (this.size > this._limit) { this.trimOld(Math.round(this._limit * this._ratio)); } } } exports.LRUCache = LRUCache; //# sourceMappingURL=linkedMap.js.map /***/ }), /***/ 5530: /***/ ((__unused_webpack_module, exports) => { "use strict"; /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.AbstractMessageBuffer = void 0; const CR = 13; const LF = 10; const CRLF = '\r\n'; class AbstractMessageBuffer { constructor(encoding = 'utf-8') { this._encoding = encoding; this._chunks = []; this._totalLength = 0; } get encoding() { return this._encoding; } append(chunk) { const toAppend = typeof chunk === 'string' ? this.fromString(chunk, this._encoding) : chunk; this._chunks.push(toAppend); this._totalLength += toAppend.byteLength; } tryReadHeaders() { if (this._chunks.length === 0) { return undefined; } let state = 0; let chunkIndex = 0; let offset = 0; let chunkBytesRead = 0; row: while (chunkIndex < this._chunks.length) { const chunk = this._chunks[chunkIndex]; offset = 0; column: while (offset < chunk.length) { const value = chunk[offset]; switch (value) { case CR: switch (state) { case 0: state = 1; break; case 2: state = 3; break; default: state = 0; } break; case LF: switch (state) { case 1: state = 2; break; case 3: state = 4; offset++; break row; default: state = 0; } break; default: state = 0; } offset++; } chunkBytesRead += chunk.byteLength; chunkIndex++; } if (state !== 4) { return undefined; } // The buffer contains the two CRLF at the end. So we will // have two empty lines after the split at the end as well. const buffer = this._read(chunkBytesRead + offset); const result = new Map(); const headers = this.toString(buffer, 'ascii').split(CRLF); if (headers.length < 2) { return result; } for (let i = 0; i < headers.length - 2; i++) { const header = headers[i]; const index = header.indexOf(':'); if (index === -1) { throw new Error('Message header must separate key and value using :'); } const key = header.substr(0, index); const value = header.substr(index + 1).trim(); result.set(key, value); } return result; } tryReadBody(length) { if (this._totalLength < length) { return undefined; } return this._read(length); } get numberOfBytes() { return this._totalLength; } _read(byteCount) { if (byteCount === 0) { return this.emptyBuffer(); } if (byteCount > this._totalLength) { throw new Error(`Cannot read so many bytes!`); } if (this._chunks[0].byteLength === byteCount) { // super fast path, precisely first chunk must be returned const chunk = this._chunks[0]; this._chunks.shift(); this._totalLength -= byteCount; return this.asNative(chunk); } if (this._chunks[0].byteLength > byteCount) { // fast path, the reading is entirely within the first chunk const chunk = this._chunks[0]; const result = this.asNative(chunk, byteCount); this._chunks[0] = chunk.slice(byteCount); this._totalLength -= byteCount; return result; } const result = this.allocNative(byteCount); let resultOffset = 0; let chunkIndex = 0; while (byteCount > 0) { const chunk = this._chunks[chunkIndex]; if (chunk.byteLength > byteCount) { // this chunk will survive const chunkPart = chunk.slice(0, byteCount); result.set(chunkPart, resultOffset); resultOffset += byteCount; this._chunks[chunkIndex] = chunk.slice(byteCount); this._totalLength -= byteCount; byteCount -= byteCount; } else { // this chunk will be entirely read result.set(chunk, resultOffset); resultOffset += chunk.byteLength; this._chunks.shift(); this._totalLength -= chunk.byteLength; byteCount -= chunk.byteLength; } } return result; } } exports.AbstractMessageBuffer = AbstractMessageBuffer; //# sourceMappingURL=messageBuffer.js.map /***/ }), /***/ 6525: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ReadableStreamMessageReader = exports.AbstractMessageReader = exports.MessageReader = void 0; const ral_1 = __webpack_require__(147); const Is = __webpack_require__(7574); const events_1 = __webpack_require__(7135); var MessageReader; (function (MessageReader) { function is(value) { let candidate = value; return candidate && Is.func(candidate.listen) && Is.func(candidate.dispose) && Is.func(candidate.onError) && Is.func(candidate.onClose) && Is.func(candidate.onPartialMessage); } MessageReader.is = is; })(MessageReader = exports.MessageReader || (exports.MessageReader = {})); class AbstractMessageReader { constructor() { this.errorEmitter = new events_1.Emitter(); this.closeEmitter = new events_1.Emitter(); this.partialMessageEmitter = new events_1.Emitter(); } dispose() { this.errorEmitter.dispose(); this.closeEmitter.dispose(); } get onError() { return this.errorEmitter.event; } fireError(error) { this.errorEmitter.fire(this.asError(error)); } get onClose() { return this.closeEmitter.event; } fireClose() { this.closeEmitter.fire(undefined); } get onPartialMessage() { return this.partialMessageEmitter.event; } firePartialMessage(info) { this.partialMessageEmitter.fire(info); } asError(error) { if (error instanceof Error) { return error; } else { return new Error(`Reader received error. Reason: ${Is.string(error.message) ? error.message : 'unknown'}`); } } } exports.AbstractMessageReader = AbstractMessageReader; var ResolvedMessageReaderOptions; (function (ResolvedMessageReaderOptions) { function fromOptions(options) { var _a; let charset; let result; let contentDecoder; const contentDecoders = new Map(); let contentTypeDecoder; const contentTypeDecoders = new Map(); if (options === undefined || typeof options === 'string') { charset = options !== null && options !== void 0 ? options : 'utf-8'; } else { charset = (_a = options.charset) !== null && _a !== void 0 ? _a : 'utf-8'; if (options.contentDecoder !== undefined) { contentDecoder = options.contentDecoder; contentDecoders.set(contentDecoder.name, contentDecoder); } if (options.contentDecoders !== undefined) { for (const decoder of options.contentDecoders) { contentDecoders.set(decoder.name, decoder); } } if (options.contentTypeDecoder !== undefined) { contentTypeDecoder = options.contentTypeDecoder; contentTypeDecoders.set(contentTypeDecoder.name, contentTypeDecoder); } if (options.contentTypeDecoders !== undefined) { for (const decoder of options.contentTypeDecoders) { contentTypeDecoders.set(decoder.name, decoder); } } } if (contentTypeDecoder === undefined) { contentTypeDecoder = ral_1.default().applicationJson.decoder; contentTypeDecoders.set(contentTypeDecoder.name, contentTypeDecoder); } return { charset, contentDecoder, contentDecoders, contentTypeDecoder, contentTypeDecoders }; } ResolvedMessageReaderOptions.fromOptions = fromOptions; })(ResolvedMessageReaderOptions || (ResolvedMessageReaderOptions = {})); class ReadableStreamMessageReader extends AbstractMessageReader { constructor(readable, options) { super(); this.readable = readable; this.options = ResolvedMessageReaderOptions.fromOptions(options); this.buffer = ral_1.default().messageBuffer.create(this.options.charset); this._partialMessageTimeout = 10000; this.nextMessageLength = -1; this.messageToken = 0; } set partialMessageTimeout(timeout) { this._partialMessageTimeout = timeout; } get partialMessageTimeout() { return this._partialMessageTimeout; } listen(callback) { this.nextMessageLength = -1; this.messageToken = 0; this.partialMessageTimer = undefined; this.callback = callback; const result = this.readable.onData((data) => { this.onData(data); }); this.readable.onError((error) => this.fireError(error)); this.readable.onClose(() => this.fireClose()); return result; } onData(data) { this.buffer.append(data); while (true) { if (this.nextMessageLength === -1) { const headers = this.buffer.tryReadHeaders(); if (!headers) { return; } const contentLength = headers.get('Content-Length'); if (!contentLength) { throw new Error('Header must provide a Content-Length property.'); } const length = parseInt(contentLength); if (isNaN(length)) { throw new Error('Content-Length value must be a number.'); } this.nextMessageLength = length; } const body = this.buffer.tryReadBody(this.nextMessageLength); if (body === undefined) { /** We haven't received the full message yet. */ this.setPartialMessageTimer(); return; } this.clearPartialMessageTimer(); this.nextMessageLength = -1; let p; if (this.options.contentDecoder !== undefined) { p = this.options.contentDecoder.decode(body); } else { p = Promise.resolve(body); } p.then((value) => { this.options.contentTypeDecoder.decode(value, this.options).then((msg) => { this.callback(msg); }, (error) => { this.fireError(error); }); }, (error) => { this.fireError(error); }); } } clearPartialMessageTimer() { if (this.partialMessageTimer) { ral_1.default().timer.clearTimeout(this.partialMessageTimer); this.partialMessageTimer = undefined; } } setPartialMessageTimer() { this.clearPartialMessageTimer(); if (this._partialMessageTimeout <= 0) { return; } this.partialMessageTimer = ral_1.default().timer.setTimeout((token, timeout) => { this.partialMessageTimer = undefined; if (token === this.messageToken) { this.firePartialMessage({ messageToken: token, waitingTime: timeout }); this.setPartialMessageTimer(); } }, this._partialMessageTimeout, this.messageToken, this._partialMessageTimeout); } } exports.ReadableStreamMessageReader = ReadableStreamMessageReader; //# sourceMappingURL=messageReader.js.map /***/ }), /***/ 6654: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.WriteableStreamMessageWriter = exports.AbstractMessageWriter = exports.MessageWriter = void 0; const ral_1 = __webpack_require__(147); const Is = __webpack_require__(7574); const semaphore_1 = __webpack_require__(142); const events_1 = __webpack_require__(7135); const ContentLength = 'Content-Length: '; const CRLF = '\r\n'; var MessageWriter; (function (MessageWriter) { function is(value) { let candidate = value; return candidate && Is.func(candidate.dispose) && Is.func(candidate.onClose) && Is.func(candidate.onError) && Is.func(candidate.write); } MessageWriter.is = is; })(MessageWriter = exports.MessageWriter || (exports.MessageWriter = {})); class AbstractMessageWriter { constructor() { this.errorEmitter = new events_1.Emitter(); this.closeEmitter = new events_1.Emitter(); } dispose() { this.errorEmitter.dispose(); this.closeEmitter.dispose(); } get onError() { return this.errorEmitter.event; } fireError(error, message, count) { this.errorEmitter.fire([this.asError(error), message, count]); } get onClose() { return this.closeEmitter.event; } fireClose() { this.closeEmitter.fire(undefined); } asError(error) { if (error instanceof Error) { return error; } else { return new Error(`Writer received error. Reason: ${Is.string(error.message) ? error.message : 'unknown'}`); } } } exports.AbstractMessageWriter = AbstractMessageWriter; var ResolvedMessageWriterOptions; (function (ResolvedMessageWriterOptions) { function fromOptions(options) { var _a, _b; if (options === undefined || typeof options === 'string') { return { charset: options !== null && options !== void 0 ? options : 'utf-8', contentTypeEncoder: ral_1.default().applicationJson.encoder }; } else { return { charset: (_a = options.charset) !== null && _a !== void 0 ? _a : 'utf-8', contentEncoder: options.contentEncoder, contentTypeEncoder: (_b = options.contentTypeEncoder) !== null && _b !== void 0 ? _b : ral_1.default().applicationJson.encoder }; } } ResolvedMessageWriterOptions.fromOptions = fromOptions; })(ResolvedMessageWriterOptions || (ResolvedMessageWriterOptions = {})); class WriteableStreamMessageWriter extends AbstractMessageWriter { constructor(writable, options) { super(); this.writable = writable; this.options = ResolvedMessageWriterOptions.fromOptions(options); this.errorCount = 0; this.writeSemaphore = new semaphore_1.Semaphore(1); this.writable.onError((error) => this.fireError(error)); this.writable.onClose(() => this.fireClose()); } async write(msg) { return this.writeSemaphore.lock(async () => { const payload = this.options.contentTypeEncoder.encode(msg, this.options).then((buffer) => { if (this.options.contentEncoder !== undefined) { return this.options.contentEncoder.encode(buffer); } else { return buffer; } }); return payload.then((buffer) => { const headers = []; headers.push(ContentLength, buffer.byteLength.toString(), CRLF); headers.push(CRLF); return this.doWrite(msg, headers, buffer); }, (error) => { this.fireError(error); throw error; }); }); } async doWrite(msg, headers, data) { try { await this.writable.write(headers.join(''), 'ascii'); return this.writable.write(data); } catch (error) { this.handleError(error, msg); return Promise.reject(error); } } handleError(error, msg) { this.errorCount++; this.fireError(error, msg, this.errorCount); } end() { this.writable.end(); } } exports.WriteableStreamMessageWriter = WriteableStreamMessageWriter; //# sourceMappingURL=messageWriter.js.map /***/ }), /***/ 839: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isResponseMessage = exports.isNotificationMessage = exports.isRequestMessage = exports.NotificationType9 = exports.NotificationType8 = exports.NotificationType7 = exports.NotificationType6 = exports.NotificationType5 = exports.NotificationType4 = exports.NotificationType3 = exports.NotificationType2 = exports.NotificationType1 = exports.NotificationType0 = exports.NotificationType = exports.RequestType9 = exports.RequestType8 = exports.RequestType7 = exports.RequestType6 = exports.RequestType5 = exports.RequestType4 = exports.RequestType3 = exports.RequestType2 = exports.RequestType1 = exports.RequestType = exports.RequestType0 = exports.AbstractMessageSignature = exports.ParameterStructures = exports.ResponseError = exports.ErrorCodes = void 0; const is = __webpack_require__(7574); /** * Predefined error codes. */ var ErrorCodes; (function (ErrorCodes) { // Defined by JSON RPC ErrorCodes.ParseError = -32700; ErrorCodes.InvalidRequest = -32600; ErrorCodes.MethodNotFound = -32601; ErrorCodes.InvalidParams = -32602; ErrorCodes.InternalError = -32603; /** * This is the start range of JSON RPC reserved error codes. * It doesn't denote a real error code. No application error codes should * be defined between the start and end range. For backwards * compatibility the `ServerNotInitialized` and the `UnknownErrorCode` * are left in the range. * * @since 3.16.0 */ ErrorCodes.jsonrpcReservedErrorRangeStart = -32099; /** @deprecated use jsonrpcReservedErrorRangeStart */ ErrorCodes.serverErrorStart = ErrorCodes.jsonrpcReservedErrorRangeStart; ErrorCodes.MessageWriteError = -32099; ErrorCodes.MessageReadError = -32098; ErrorCodes.ServerNotInitialized = -32002; ErrorCodes.UnknownErrorCode = -32001; /** * This is the end range of JSON RPC reserved error codes. * It doesn't denote a real error code. * * @since 3.16.0 */ ErrorCodes.jsonrpcReservedErrorRangeEnd = -32000; /** @deprecated use jsonrpcReservedErrorRangeEnd */ ErrorCodes.serverErrorEnd = ErrorCodes.jsonrpcReservedErrorRangeEnd; })(ErrorCodes = exports.ErrorCodes || (exports.ErrorCodes = {})); /** * An error object return in a response in case a request * has failed. */ class ResponseError extends Error { constructor(code, message, data) { super(message); this.code = is.number(code) ? code : ErrorCodes.UnknownErrorCode; this.data = data; Object.setPrototypeOf(this, ResponseError.prototype); } toJson() { return { code: this.code, message: this.message, data: this.data, }; } } exports.ResponseError = ResponseError; class ParameterStructures { constructor(kind) { this.kind = kind; } static is(value) { return value === ParameterStructures.auto || value === ParameterStructures.byName || value === ParameterStructures.byPosition; } toString() { return this.kind; } } exports.ParameterStructures = ParameterStructures; /** * The parameter structure is automatically inferred on the number of parameters * and the parameter type in case of a single param. */ ParameterStructures.auto = new ParameterStructures('auto'); /** * Forces `byPosition` parameter structure. This is useful if you have a single * parameter which has a literal type. */ ParameterStructures.byPosition = new ParameterStructures('byPosition'); /** * Forces `byName` parameter structure. This is only useful when having a single * parameter. The library will report errors if used with a different number of * parameters. */ ParameterStructures.byName = new ParameterStructures('byName'); /** * An abstract implementation of a MessageType. */ class AbstractMessageSignature { constructor(method, numberOfParams) { this.method = method; this.numberOfParams = numberOfParams; } get parameterStructures() { return ParameterStructures.auto; } } exports.AbstractMessageSignature = AbstractMessageSignature; /** * Classes to type request response pairs */ class RequestType0 extends AbstractMessageSignature { constructor(method) { super(method, 0); } } exports.RequestType0 = RequestType0; class RequestType extends AbstractMessageSignature { constructor(method, _parameterStructures = ParameterStructures.auto) { super(method, 1); this._parameterStructures = _parameterStructures; } get parameterStructures() { return this._parameterStructures; } } exports.RequestType = RequestType; class RequestType1 extends AbstractMessageSignature { constructor(method, _parameterStructures = ParameterStructures.auto) { super(method, 1); this._parameterStructures = _parameterStructures; } get parameterStructures() { return this._parameterStructures; } } exports.RequestType1 = RequestType1; class RequestType2 extends AbstractMessageSignature { constructor(method) { super(method, 2); } } exports.RequestType2 = RequestType2; class RequestType3 extends AbstractMessageSignature { constructor(method) { super(method, 3); } } exports.RequestType3 = RequestType3; class RequestType4 extends AbstractMessageSignature { constructor(method) { super(method, 4); } } exports.RequestType4 = RequestType4; class RequestType5 extends AbstractMessageSignature { constructor(method) { super(method, 5); } } exports.RequestType5 = RequestType5; class RequestType6 extends AbstractMessageSignature { constructor(method) { super(method, 6); } } exports.RequestType6 = RequestType6; class RequestType7 extends AbstractMessageSignature { constructor(method) { super(method, 7); } } exports.RequestType7 = RequestType7; class RequestType8 extends AbstractMessageSignature { constructor(method) { super(method, 8); } } exports.RequestType8 = RequestType8; class RequestType9 extends AbstractMessageSignature { constructor(method) { super(method, 9); } } exports.RequestType9 = RequestType9; class NotificationType extends AbstractMessageSignature { constructor(method, _parameterStructures = ParameterStructures.auto) { super(method, 1); this._parameterStructures = _parameterStructures; } get parameterStructures() { return this._parameterStructures; } } exports.NotificationType = NotificationType; class NotificationType0 extends AbstractMessageSignature { constructor(method) { super(method, 0); } } exports.NotificationType0 = NotificationType0; class NotificationType1 extends AbstractMessageSignature { constructor(method, _parameterStructures = ParameterStructures.auto) { super(method, 1); this._parameterStructures = _parameterStructures; } get parameterStructures() { return this._parameterStructures; } } exports.NotificationType1 = NotificationType1; class NotificationType2 extends AbstractMessageSignature { constructor(method) { super(method, 2); } } exports.NotificationType2 = NotificationType2; class NotificationType3 extends AbstractMessageSignature { constructor(method) { super(method, 3); } } exports.NotificationType3 = NotificationType3; class NotificationType4 extends AbstractMessageSignature { constructor(method) { super(method, 4); } } exports.NotificationType4 = NotificationType4; class NotificationType5 extends AbstractMessageSignature { constructor(method) { super(method, 5); } } exports.NotificationType5 = NotificationType5; class NotificationType6 extends AbstractMessageSignature { constructor(method) { super(method, 6); } } exports.NotificationType6 = NotificationType6; class NotificationType7 extends AbstractMessageSignature { constructor(method) { super(method, 7); } } exports.NotificationType7 = NotificationType7; class NotificationType8 extends AbstractMessageSignature { constructor(method) { super(method, 8); } } exports.NotificationType8 = NotificationType8; class NotificationType9 extends AbstractMessageSignature { constructor(method) { super(method, 9); } } exports.NotificationType9 = NotificationType9; /** * Tests if the given message is a request message */ function isRequestMessage(message) { const candidate = message; return candidate && is.string(candidate.method) && (is.string(candidate.id) || is.number(candidate.id)); } exports.isRequestMessage = isRequestMessage; /** * Tests if the given message is a notification message */ function isNotificationMessage(message) { const candidate = message; return candidate && is.string(candidate.method) && message.id === void 0; } exports.isNotificationMessage = isNotificationMessage; /** * Tests if the given message is a response message */ function isResponseMessage(message) { const candidate = message; return candidate && (candidate.result !== void 0 || !!candidate.error) && (is.string(candidate.id) || is.number(candidate.id) || candidate.id === null); } exports.isResponseMessage = isResponseMessage; //# sourceMappingURL=messages.js.map /***/ }), /***/ 147: /***/ ((__unused_webpack_module, exports) => { "use strict"; /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ Object.defineProperty(exports, "__esModule", ({ value: true })); let _ral; function RAL() { if (_ral === undefined) { throw new Error(`No runtime abstraction layer installed`); } return _ral; } (function (RAL) { function install(ral) { if (ral === undefined) { throw new Error(`No runtime abstraction layer provided`); } _ral = ral; } RAL.install = install; })(RAL || (RAL = {})); exports["default"] = RAL; //# sourceMappingURL=ral.js.map /***/ }), /***/ 142: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Semaphore = void 0; const ral_1 = __webpack_require__(147); class Semaphore { constructor(capacity = 1) { if (capacity <= 0) { throw new Error('Capacity must be greater than 0'); } this._capacity = capacity; this._active = 0; this._waiting = []; } lock(thunk) { return new Promise((resolve, reject) => { this._waiting.push({ thunk, resolve, reject }); this.runNext(); }); } get active() { return this._active; } runNext() { if (this._waiting.length === 0 || this._active === this._capacity) { return; } ral_1.default().timer.setImmediate(() => this.doRunNext()); } doRunNext() { if (this._waiting.length === 0 || this._active === this._capacity) { return; } const next = this._waiting.shift(); this._active++; if (this._active > this._capacity) { throw new Error(`To many thunks active`); } try { const result = next.thunk(); if (result instanceof Promise) { result.then((value) => { this._active--; next.resolve(value); this.runNext(); }, (err) => { this._active--; next.reject(err); this.runNext(); }); } else { this._active--; next.resolve(result); this.runNext(); } } catch (err) { this._active--; next.reject(err); this.runNext(); } } } exports.Semaphore = Semaphore; //# sourceMappingURL=semaphore.js.map /***/ }), /***/ 4389: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __exportStar = (this && this.__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.createMessageConnection = exports.createServerSocketTransport = exports.createClientSocketTransport = exports.createServerPipeTransport = exports.createClientPipeTransport = exports.generateRandomPipeName = exports.StreamMessageWriter = exports.StreamMessageReader = exports.SocketMessageWriter = exports.SocketMessageReader = exports.IPCMessageWriter = exports.IPCMessageReader = void 0; /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ----------------------------------------------------------------------------------------- */ const ril_1 = __webpack_require__(3034); // Install the node runtime abstract. ril_1.default.install(); const api_1 = __webpack_require__(3870); const path = __webpack_require__(1017); const os = __webpack_require__(2037); const crypto_1 = __webpack_require__(6113); const net_1 = __webpack_require__(1808); __exportStar(__webpack_require__(3870), exports); class IPCMessageReader extends api_1.AbstractMessageReader { constructor(process) { super(); this.process = process; let eventEmitter = this.process; eventEmitter.on('error', (error) => this.fireError(error)); eventEmitter.on('close', () => this.fireClose()); } listen(callback) { this.process.on('message', callback); return api_1.Disposable.create(() => this.process.off('message', callback)); } } exports.IPCMessageReader = IPCMessageReader; class IPCMessageWriter extends api_1.AbstractMessageWriter { constructor(process) { super(); this.process = process; this.errorCount = 0; let eventEmitter = this.process; eventEmitter.on('error', (error) => this.fireError(error)); eventEmitter.on('close', () => this.fireClose); } write(msg) { try { if (typeof this.process.send === 'function') { this.process.send(msg, undefined, undefined, (error) => { if (error) { this.errorCount++; this.handleError(error, msg); } else { this.errorCount = 0; } }); } return Promise.resolve(); } catch (error) { this.handleError(error, msg); return Promise.reject(error); } } handleError(error, msg) { this.errorCount++; this.fireError(error, msg, this.errorCount); } end() { } } exports.IPCMessageWriter = IPCMessageWriter; class SocketMessageReader extends api_1.ReadableStreamMessageReader { constructor(socket, encoding = 'utf-8') { super(ril_1.default().stream.asReadableStream(socket), encoding); } } exports.SocketMessageReader = SocketMessageReader; class SocketMessageWriter extends api_1.WriteableStreamMessageWriter { constructor(socket, options) { super(ril_1.default().stream.asWritableStream(socket), options); this.socket = socket; } dispose() { super.dispose(); this.socket.destroy(); } } exports.SocketMessageWriter = SocketMessageWriter; class StreamMessageReader extends api_1.ReadableStreamMessageReader { constructor(readble, encoding) { super(ril_1.default().stream.asReadableStream(readble), encoding); } } exports.StreamMessageReader = StreamMessageReader; class StreamMessageWriter extends api_1.WriteableStreamMessageWriter { constructor(writable, options) { super(ril_1.default().stream.asWritableStream(writable), options); } } exports.StreamMessageWriter = StreamMessageWriter; const XDG_RUNTIME_DIR = process.env['XDG_RUNTIME_DIR']; const safeIpcPathLengths = new Map([ ['linux', 107], ['darwin', 103] ]); function generateRandomPipeName() { const randomSuffix = crypto_1.randomBytes(21).toString('hex'); if (process.platform === 'win32') { return `\\\\.\\pipe\\vscode-jsonrpc-${randomSuffix}-sock`; } let result; if (XDG_RUNTIME_DIR) { result = path.join(XDG_RUNTIME_DIR, `vscode-ipc-${randomSuffix}.sock`); } else { result = path.join(os.tmpdir(), `vscode-${randomSuffix}.sock`); } const limit = safeIpcPathLengths.get(process.platform); if (limit !== undefined && result.length >= limit) { ril_1.default().console.warn(`WARNING: IPC handle "${result}" is longer than ${limit} characters.`); } return result; } exports.generateRandomPipeName = generateRandomPipeName; function createClientPipeTransport(pipeName, encoding = 'utf-8') { let connectResolve; const connected = new Promise((resolve, _reject) => { connectResolve = resolve; }); return new Promise((resolve, reject) => { let server = net_1.createServer((socket) => { server.close(); connectResolve([ new SocketMessageReader(socket, encoding), new SocketMessageWriter(socket, encoding) ]); }); server.on('error', reject); server.listen(pipeName, () => { server.removeListener('error', reject); resolve({ onConnected: () => { return connected; } }); }); }); } exports.createClientPipeTransport = createClientPipeTransport; function createServerPipeTransport(pipeName, encoding = 'utf-8') { const socket = net_1.createConnection(pipeName); return [ new SocketMessageReader(socket, encoding), new SocketMessageWriter(socket, encoding) ]; } exports.createServerPipeTransport = createServerPipeTransport; function createClientSocketTransport(port, encoding = 'utf-8') { let connectResolve; const connected = new Promise((resolve, _reject) => { connectResolve = resolve; }); return new Promise((resolve, reject) => { const server = net_1.createServer((socket) => { server.close(); connectResolve([ new SocketMessageReader(socket, encoding), new SocketMessageWriter(socket, encoding) ]); }); server.on('error', reject); server.listen(port, '127.0.0.1', () => { server.removeListener('error', reject); resolve({ onConnected: () => { return connected; } }); }); }); } exports.createClientSocketTransport = createClientSocketTransport; function createServerSocketTransport(port, encoding = 'utf-8') { const socket = net_1.createConnection(port, '127.0.0.1'); return [ new SocketMessageReader(socket, encoding), new SocketMessageWriter(socket, encoding) ]; } exports.createServerSocketTransport = createServerSocketTransport; function isReadableStream(value) { const candidate = value; return candidate.read !== undefined && candidate.addListener !== undefined; } function isWritableStream(value) { const candidate = value; return candidate.write !== undefined && candidate.addListener !== undefined; } function createMessageConnection(input, output, logger, options) { if (!logger) { logger = api_1.NullLogger; } const reader = isReadableStream(input) ? new StreamMessageReader(input) : input; const writer = isWritableStream(output) ? new StreamMessageWriter(output) : output; if (api_1.ConnectionStrategy.is(options)) { options = { connectionStrategy: options }; } return api_1.createMessageConnection(reader, writer, logger, options); } exports.createMessageConnection = createMessageConnection; //# sourceMappingURL=main.js.map /***/ }), /***/ 3034: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ Object.defineProperty(exports, "__esModule", ({ value: true })); const ral_1 = __webpack_require__(147); const util_1 = __webpack_require__(3837); const disposable_1 = __webpack_require__(3911); const messageBuffer_1 = __webpack_require__(5530); class MessageBuffer extends messageBuffer_1.AbstractMessageBuffer { constructor(encoding = 'utf-8') { super(encoding); } emptyBuffer() { return MessageBuffer.emptyBuffer; } fromString(value, encoding) { return Buffer.from(value, encoding); } toString(value, encoding) { if (value instanceof Buffer) { return value.toString(encoding); } else { return new util_1.TextDecoder(encoding).decode(value); } } asNative(buffer, length) { if (length === undefined) { return buffer instanceof Buffer ? buffer : Buffer.from(buffer); } else { return buffer instanceof Buffer ? buffer.slice(0, length) : Buffer.from(buffer, 0, length); } } allocNative(length) { return Buffer.allocUnsafe(length); } } MessageBuffer.emptyBuffer = Buffer.allocUnsafe(0); class ReadableStreamWrapper { constructor(stream) { this.stream = stream; } onClose(listener) { this.stream.on('close', listener); return disposable_1.Disposable.create(() => this.stream.off('close', listener)); } onError(listener) { this.stream.on('error', listener); return disposable_1.Disposable.create(() => this.stream.off('error', listener)); } onEnd(listener) { this.stream.on('end', listener); return disposable_1.Disposable.create(() => this.stream.off('end', listener)); } onData(listener) { this.stream.on('data', listener); return disposable_1.Disposable.create(() => this.stream.off('data', listener)); } } class WritableStreamWrapper { constructor(stream) { this.stream = stream; } onClose(listener) { this.stream.on('close', listener); return disposable_1.Disposable.create(() => this.stream.off('close', listener)); } onError(listener) { this.stream.on('error', listener); return disposable_1.Disposable.create(() => this.stream.off('error', listener)); } onEnd(listener) { this.stream.on('end', listener); return disposable_1.Disposable.create(() => this.stream.off('end', listener)); } write(data, encoding) { return new Promise((resolve, reject) => { const callback = (error) => { if (error === undefined || error === null) { resolve(); } else { reject(error); } }; if (typeof data === 'string') { this.stream.write(data, encoding, callback); } else { this.stream.write(data, callback); } }); } end() { this.stream.end(); } } const _ril = Object.freeze({ messageBuffer: Object.freeze({ create: (encoding) => new MessageBuffer(encoding) }), applicationJson: Object.freeze({ encoder: Object.freeze({ name: 'application/json', encode: (msg, options) => { try { return Promise.resolve(Buffer.from(JSON.stringify(msg, undefined, 0), options.charset)); } catch (err) { return Promise.reject(err); } } }), decoder: Object.freeze({ name: 'application/json', decode: (buffer, options) => { try { if (buffer instanceof Buffer) { return Promise.resolve(JSON.parse(buffer.toString(options.charset))); } else { return Promise.resolve(JSON.parse(new util_1.TextDecoder(options.charset).decode(buffer))); } } catch (err) { return Promise.reject(err); } } }) }), stream: Object.freeze({ asReadableStream: (stream) => new ReadableStreamWrapper(stream), asWritableStream: (stream) => new WritableStreamWrapper(stream) }), console: console, timer: Object.freeze({ setTimeout(callback, ms, ...args) { return setTimeout(callback, ms, ...args); }, clearTimeout(handle) { clearTimeout(handle); }, setImmediate(callback, ...args) { return setImmediate(callback, ...args); }, clearImmediate(handle) { clearImmediate(handle); } }) }); function RIL() { return _ril; } (function (RIL) { function install() { ral_1.default.install(_ril); } RIL.install = install; })(RIL || (RIL = {})); exports["default"] = RIL; //# sourceMappingURL=ril.js.map /***/ }), /***/ 5028: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ----------------------------------------------------------------------------------------- */ module.exports = __webpack_require__(4389); /***/ }), /***/ 5734: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __exportStar = (this && this.__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(__webpack_require__(273), exports); __exportStar(__webpack_require__(4384), exports); __exportStar(__webpack_require__(7225), exports); //# sourceMappingURL=api.js.map /***/ }), /***/ 5578: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CallHierarchyFeature = void 0; const vscode_1 = __webpack_require__(9496); const vscode_languageserver_protocol_1 = __webpack_require__(273); const client_1 = __webpack_require__(4384); function ensure(target, key) { if (target[key] === void 0) { target[key] = {}; } return target[key]; } class CallHierarchyProvider { constructor(client) { this.client = client; this.middleware = client.clientOptions.middleware; } prepareCallHierarchy(document, position, token) { const client = this.client; const middleware = this.middleware; const prepareCallHierarchy = (document, position, token) => { const params = client.code2ProtocolConverter.asTextDocumentPositionParams(document, position); return client.sendRequest(vscode_languageserver_protocol_1.CallHierarchyPrepareRequest.type, params, token).then((result) => { return client.protocol2CodeConverter.asCallHierarchyItems(result); }, (error) => { return client.handleFailedRequest(vscode_languageserver_protocol_1.CallHierarchyPrepareRequest.type, error, null); }); }; return middleware.prepareCallHierarchy ? middleware.prepareCallHierarchy(document, position, token, prepareCallHierarchy) : prepareCallHierarchy(document, position, token); } provideCallHierarchyIncomingCalls(item, token) { const client = this.client; const middleware = this.middleware; const provideCallHierarchyIncomingCalls = (item, token) => { const params = { item: client.code2ProtocolConverter.asCallHierarchyItem(item) }; return client.sendRequest(vscode_languageserver_protocol_1.CallHierarchyIncomingCallsRequest.type, params, token).then((result) => { return client.protocol2CodeConverter.asCallHierarchyIncomingCalls(result); }, (error) => { return client.handleFailedRequest(vscode_languageserver_protocol_1.CallHierarchyIncomingCallsRequest.type, error, null); }); }; return middleware.provideCallHierarchyIncomingCalls ? middleware.provideCallHierarchyIncomingCalls(item, token, provideCallHierarchyIncomingCalls) : provideCallHierarchyIncomingCalls(item, token); } provideCallHierarchyOutgoingCalls(item, token) { const client = this.client; const middleware = this.middleware; const provideCallHierarchyOutgoingCalls = (item, token) => { const params = { item: client.code2ProtocolConverter.asCallHierarchyItem(item) }; return client.sendRequest(vscode_languageserver_protocol_1.CallHierarchyOutgoingCallsRequest.type, params, token).then((result) => { return client.protocol2CodeConverter.asCallHierarchyOutgoingCalls(result); }, (error) => { return client.handleFailedRequest(vscode_languageserver_protocol_1.CallHierarchyOutgoingCallsRequest.type, error, null); }); }; return middleware.provideCallHierarchyOutgoingCalls ? middleware.provideCallHierarchyOutgoingCalls(item, token, provideCallHierarchyOutgoingCalls) : provideCallHierarchyOutgoingCalls(item, token); } } class CallHierarchyFeature extends client_1.TextDocumentFeature { constructor(client) { super(client, vscode_languageserver_protocol_1.CallHierarchyPrepareRequest.type); } fillClientCapabilities(cap) { const capabilities = cap; const capability = ensure(ensure(capabilities, 'textDocument'), 'callHierarchy'); capability.dynamicRegistration = true; } initialize(capabilities, documentSelector) { const [id, options] = this.getRegistration(documentSelector, capabilities.callHierarchyProvider); if (!id || !options) { return; } this.register({ id: id, registerOptions: options }); } registerLanguageProvider(options) { const client = this._client; const provider = new CallHierarchyProvider(client); return [vscode_1.languages.registerCallHierarchyProvider(options.documentSelector, provider), provider]; } } exports.CallHierarchyFeature = CallHierarchyFeature; //# sourceMappingURL=callHierarchy.js.map /***/ }), /***/ 4384: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.BaseLanguageClient = exports.MessageTransports = exports.TextDocumentFeature = exports.State = exports.RevealOutputChannelOn = exports.CloseAction = exports.ErrorAction = void 0; const vscode_1 = __webpack_require__(9496); const vscode_languageserver_protocol_1 = __webpack_require__(273); const configuration_1 = __webpack_require__(6495); const c2p = __webpack_require__(71); const p2c = __webpack_require__(8785); const Is = __webpack_require__(9763); const async_1 = __webpack_require__(4904); const UUID = __webpack_require__(1980); const progressPart_1 = __webpack_require__(8071); class ConsoleLogger { error(message) { vscode_languageserver_protocol_1.RAL().console.error(message); } warn(message) { vscode_languageserver_protocol_1.RAL().console.warn(message); } info(message) { vscode_languageserver_protocol_1.RAL().console.info(message); } log(message) { vscode_languageserver_protocol_1.RAL().console.log(message); } } function createConnection(input, output, errorHandler, closeHandler, options) { let logger = new ConsoleLogger(); let connection = vscode_languageserver_protocol_1.createProtocolConnection(input, output, logger, options); connection.onError((data) => { errorHandler(data[0], data[1], data[2]); }); connection.onClose(closeHandler); let result = { listen: () => connection.listen(), sendRequest: (type, ...params) => connection.sendRequest(Is.string(type) ? type : type.method, ...params), onRequest: (type, handler) => connection.onRequest(Is.string(type) ? type : type.method, handler), sendNotification: (type, params) => connection.sendNotification(Is.string(type) ? type : type.method, params), onNotification: (type, handler) => connection.onNotification(Is.string(type) ? type : type.method, handler), onProgress: connection.onProgress, sendProgress: connection.sendProgress, trace: (value, tracer, sendNotificationOrTraceOptions) => { const defaultTraceOptions = { sendNotification: false, traceFormat: vscode_languageserver_protocol_1.TraceFormat.Text }; if (sendNotificationOrTraceOptions === undefined) { connection.trace(value, tracer, defaultTraceOptions); } else if (Is.boolean(sendNotificationOrTraceOptions)) { connection.trace(value, tracer, sendNotificationOrTraceOptions); } else { connection.trace(value, tracer, sendNotificationOrTraceOptions); } }, initialize: (params) => connection.sendRequest(vscode_languageserver_protocol_1.InitializeRequest.type, params), shutdown: () => connection.sendRequest(vscode_languageserver_protocol_1.ShutdownRequest.type, undefined), exit: () => connection.sendNotification(vscode_languageserver_protocol_1.ExitNotification.type), onLogMessage: (handler) => connection.onNotification(vscode_languageserver_protocol_1.LogMessageNotification.type, handler), onShowMessage: (handler) => connection.onNotification(vscode_languageserver_protocol_1.ShowMessageNotification.type, handler), onTelemetry: (handler) => connection.onNotification(vscode_languageserver_protocol_1.TelemetryEventNotification.type, handler), didChangeConfiguration: (params) => connection.sendNotification(vscode_languageserver_protocol_1.DidChangeConfigurationNotification.type, params), didChangeWatchedFiles: (params) => connection.sendNotification(vscode_languageserver_protocol_1.DidChangeWatchedFilesNotification.type, params), didOpenTextDocument: (params) => connection.sendNotification(vscode_languageserver_protocol_1.DidOpenTextDocumentNotification.type, params), didChangeTextDocument: (params) => connection.sendNotification(vscode_languageserver_protocol_1.DidChangeTextDocumentNotification.type, params), didCloseTextDocument: (params) => connection.sendNotification(vscode_languageserver_protocol_1.DidCloseTextDocumentNotification.type, params), didSaveTextDocument: (params) => connection.sendNotification(vscode_languageserver_protocol_1.DidSaveTextDocumentNotification.type, params), onDiagnostics: (handler) => connection.onNotification(vscode_languageserver_protocol_1.PublishDiagnosticsNotification.type, handler), end: () => connection.end(), dispose: () => connection.dispose() }; return result; } /** * An action to be performed when the connection is producing errors. */ var ErrorAction; (function (ErrorAction) { /** * Continue running the server. */ ErrorAction[ErrorAction["Continue"] = 1] = "Continue"; /** * Shutdown the server. */ ErrorAction[ErrorAction["Shutdown"] = 2] = "Shutdown"; })(ErrorAction = exports.ErrorAction || (exports.ErrorAction = {})); /** * An action to be performed when the connection to a server got closed. */ var CloseAction; (function (CloseAction) { /** * Don't restart the server. The connection stays closed. */ CloseAction[CloseAction["DoNotRestart"] = 1] = "DoNotRestart"; /** * Restart the server. */ CloseAction[CloseAction["Restart"] = 2] = "Restart"; })(CloseAction = exports.CloseAction || (exports.CloseAction = {})); class DefaultErrorHandler { constructor(name, maxRestartCount) { this.name = name; this.maxRestartCount = maxRestartCount; this.restarts = []; } error(_error, _message, count) { if (count && count <= 3) { return ErrorAction.Continue; } return ErrorAction.Shutdown; } closed() { this.restarts.push(Date.now()); if (this.restarts.length <= this.maxRestartCount) { return CloseAction.Restart; } else { let diff = this.restarts[this.restarts.length - 1] - this.restarts[0]; if (diff <= 3 * 60 * 1000) { vscode_1.window.showErrorMessage(`The ${this.name} server crashed ${this.maxRestartCount + 1} times in the last 3 minutes. The server will not be restarted.`); return CloseAction.DoNotRestart; } else { this.restarts.shift(); return CloseAction.Restart; } } } } var RevealOutputChannelOn; (function (RevealOutputChannelOn) { RevealOutputChannelOn[RevealOutputChannelOn["Info"] = 1] = "Info"; RevealOutputChannelOn[RevealOutputChannelOn["Warn"] = 2] = "Warn"; RevealOutputChannelOn[RevealOutputChannelOn["Error"] = 3] = "Error"; RevealOutputChannelOn[RevealOutputChannelOn["Never"] = 4] = "Never"; })(RevealOutputChannelOn = exports.RevealOutputChannelOn || (exports.RevealOutputChannelOn = {})); var State; (function (State) { State[State["Stopped"] = 1] = "Stopped"; State[State["Starting"] = 3] = "Starting"; State[State["Running"] = 2] = "Running"; })(State = exports.State || (exports.State = {})); var ClientState; (function (ClientState) { ClientState[ClientState["Initial"] = 0] = "Initial"; ClientState[ClientState["Starting"] = 1] = "Starting"; ClientState[ClientState["StartFailed"] = 2] = "StartFailed"; ClientState[ClientState["Running"] = 3] = "Running"; ClientState[ClientState["Stopping"] = 4] = "Stopping"; ClientState[ClientState["Stopped"] = 5] = "Stopped"; })(ClientState || (ClientState = {})); const SupportedSymbolKinds = [ vscode_languageserver_protocol_1.SymbolKind.File, vscode_languageserver_protocol_1.SymbolKind.Module, vscode_languageserver_protocol_1.SymbolKind.Namespace, vscode_languageserver_protocol_1.SymbolKind.Package, vscode_languageserver_protocol_1.SymbolKind.Class, vscode_languageserver_protocol_1.SymbolKind.Method, vscode_languageserver_protocol_1.SymbolKind.Property, vscode_languageserver_protocol_1.SymbolKind.Field, vscode_languageserver_protocol_1.SymbolKind.Constructor, vscode_languageserver_protocol_1.SymbolKind.Enum, vscode_languageserver_protocol_1.SymbolKind.Interface, vscode_languageserver_protocol_1.SymbolKind.Function, vscode_languageserver_protocol_1.SymbolKind.Variable, vscode_languageserver_protocol_1.SymbolKind.Constant, vscode_languageserver_protocol_1.SymbolKind.String, vscode_languageserver_protocol_1.SymbolKind.Number, vscode_languageserver_protocol_1.SymbolKind.Boolean, vscode_languageserver_protocol_1.SymbolKind.Array, vscode_languageserver_protocol_1.SymbolKind.Object, vscode_languageserver_protocol_1.SymbolKind.Key, vscode_languageserver_protocol_1.SymbolKind.Null, vscode_languageserver_protocol_1.SymbolKind.EnumMember, vscode_languageserver_protocol_1.SymbolKind.Struct, vscode_languageserver_protocol_1.SymbolKind.Event, vscode_languageserver_protocol_1.SymbolKind.Operator, vscode_languageserver_protocol_1.SymbolKind.TypeParameter ]; const SupportedCompletionItemKinds = [ vscode_languageserver_protocol_1.CompletionItemKind.Text, vscode_languageserver_protocol_1.CompletionItemKind.Method, vscode_languageserver_protocol_1.CompletionItemKind.Function, vscode_languageserver_protocol_1.CompletionItemKind.Constructor, vscode_languageserver_protocol_1.CompletionItemKind.Field, vscode_languageserver_protocol_1.CompletionItemKind.Variable, vscode_languageserver_protocol_1.CompletionItemKind.Class, vscode_languageserver_protocol_1.CompletionItemKind.Interface, vscode_languageserver_protocol_1.CompletionItemKind.Module, vscode_languageserver_protocol_1.CompletionItemKind.Property, vscode_languageserver_protocol_1.CompletionItemKind.Unit, vscode_languageserver_protocol_1.CompletionItemKind.Value, vscode_languageserver_protocol_1.CompletionItemKind.Enum, vscode_languageserver_protocol_1.CompletionItemKind.Keyword, vscode_languageserver_protocol_1.CompletionItemKind.Snippet, vscode_languageserver_protocol_1.CompletionItemKind.Color, vscode_languageserver_protocol_1.CompletionItemKind.File, vscode_languageserver_protocol_1.CompletionItemKind.Reference, vscode_languageserver_protocol_1.CompletionItemKind.Folder, vscode_languageserver_protocol_1.CompletionItemKind.EnumMember, vscode_languageserver_protocol_1.CompletionItemKind.Constant, vscode_languageserver_protocol_1.CompletionItemKind.Struct, vscode_languageserver_protocol_1.CompletionItemKind.Event, vscode_languageserver_protocol_1.CompletionItemKind.Operator, vscode_languageserver_protocol_1.CompletionItemKind.TypeParameter ]; const SupportedSymbolTags = [ vscode_languageserver_protocol_1.SymbolTag.Deprecated ]; function ensure(target, key) { if (target[key] === undefined) { target[key] = {}; } return target[key]; } var FileFormattingOptions; (function (FileFormattingOptions) { function fromConfiguration(document) { const filesConfig = vscode_1.workspace.getConfiguration('files', document); return { trimTrailingWhitespace: filesConfig.get('trimTrailingWhitespace'), trimFinalNewlines: filesConfig.get('trimFinalNewlines'), insertFinalNewline: filesConfig.get('insertFinalNewline'), }; } FileFormattingOptions.fromConfiguration = fromConfiguration; })(FileFormattingOptions || (FileFormattingOptions = {})); var DynamicFeature; (function (DynamicFeature) { function is(value) { let candidate = value; return candidate && Is.func(candidate.register) && Is.func(candidate.unregister) && Is.func(candidate.dispose) && candidate.registrationType !== undefined; } DynamicFeature.is = is; })(DynamicFeature || (DynamicFeature = {})); class DocumentNotifications { constructor(_client, _event, _type, _middleware, _createParams, _selectorFilter) { this._client = _client; this._event = _event; this._type = _type; this._middleware = _middleware; this._createParams = _createParams; this._selectorFilter = _selectorFilter; this._selectors = new Map(); } static textDocumentFilter(selectors, textDocument) { for (const selector of selectors) { if (vscode_1.languages.match(selector, textDocument)) { return true; } } return false; } register(data) { if (!data.registerOptions.documentSelector) { return; } if (!this._listener) { this._listener = this._event(this.callback, this); } this._selectors.set(data.id, data.registerOptions.documentSelector); } callback(data) { if (!this._selectorFilter || this._selectorFilter(this._selectors.values(), data)) { if (this._middleware) { this._middleware(data, (data) => this._client.sendNotification(this._type, this._createParams(data))); } else { this._client.sendNotification(this._type, this._createParams(data)); } this.notificationSent(data); } } notificationSent(_data) { } unregister(id) { this._selectors.delete(id); if (this._selectors.size === 0 && this._listener) { this._listener.dispose(); this._listener = undefined; } } dispose() { this._selectors.clear(); if (this._listener) { this._listener.dispose(); this._listener = undefined; } } getProvider(document) { for (const selector of this._selectors.values()) { if (vscode_1.languages.match(selector, document)) { return { send: (data) => { this.callback(data); } }; } } return undefined; } } class DidOpenTextDocumentFeature extends DocumentNotifications { constructor(client, _syncedDocuments) { super(client, vscode_1.workspace.onDidOpenTextDocument, vscode_languageserver_protocol_1.DidOpenTextDocumentNotification.type, client.clientOptions.middleware.didOpen, (textDocument) => client.code2ProtocolConverter.asOpenTextDocumentParams(textDocument), DocumentNotifications.textDocumentFilter); this._syncedDocuments = _syncedDocuments; } fillClientCapabilities(capabilities) { ensure(ensure(capabilities, 'textDocument'), 'synchronization').dynamicRegistration = true; } initialize(capabilities, documentSelector) { let textDocumentSyncOptions = capabilities.resolvedTextDocumentSync; if (documentSelector && textDocumentSyncOptions && textDocumentSyncOptions.openClose) { this.register({ id: UUID.generateUuid(), registerOptions: { documentSelector: documentSelector } }); } } get registrationType() { return vscode_languageserver_protocol_1.DidOpenTextDocumentNotification.type; } register(data) { super.register(data); if (!data.registerOptions.documentSelector) { return; } let documentSelector = data.registerOptions.documentSelector; vscode_1.workspace.textDocuments.forEach((textDocument) => { let uri = textDocument.uri.toString(); if (this._syncedDocuments.has(uri)) { return; } if (vscode_1.languages.match(documentSelector, textDocument)) { let middleware = this._client.clientOptions.middleware; let didOpen = (textDocument) => { this._client.sendNotification(this._type, this._createParams(textDocument)); }; if (middleware.didOpen) { middleware.didOpen(textDocument, didOpen); } else { didOpen(textDocument); } this._syncedDocuments.set(uri, textDocument); } }); } notificationSent(textDocument) { super.notificationSent(textDocument); this._syncedDocuments.set(textDocument.uri.toString(), textDocument); } } class DidCloseTextDocumentFeature extends DocumentNotifications { constructor(client, _syncedDocuments) { super(client, vscode_1.workspace.onDidCloseTextDocument, vscode_languageserver_protocol_1.DidCloseTextDocumentNotification.type, client.clientOptions.middleware.didClose, (textDocument) => client.code2ProtocolConverter.asCloseTextDocumentParams(textDocument), DocumentNotifications.textDocumentFilter); this._syncedDocuments = _syncedDocuments; } get registrationType() { return vscode_languageserver_protocol_1.DidCloseTextDocumentNotification.type; } fillClientCapabilities(capabilities) { ensure(ensure(capabilities, 'textDocument'), 'synchronization').dynamicRegistration = true; } initialize(capabilities, documentSelector) { let textDocumentSyncOptions = capabilities.resolvedTextDocumentSync; if (documentSelector && textDocumentSyncOptions && textDocumentSyncOptions.openClose) { this.register({ id: UUID.generateUuid(), registerOptions: { documentSelector: documentSelector } }); } } notificationSent(textDocument) { super.notificationSent(textDocument); this._syncedDocuments.delete(textDocument.uri.toString()); } unregister(id) { let selector = this._selectors.get(id); // The super call removed the selector from the map // of selectors. super.unregister(id); let selectors = this._selectors.values(); this._syncedDocuments.forEach((textDocument) => { if (vscode_1.languages.match(selector, textDocument) && !this._selectorFilter(selectors, textDocument)) { let middleware = this._client.clientOptions.middleware; let didClose = (textDocument) => { this._client.sendNotification(this._type, this._createParams(textDocument)); }; this._syncedDocuments.delete(textDocument.uri.toString()); if (middleware.didClose) { middleware.didClose(textDocument, didClose); } else { didClose(textDocument); } } }); } } class DidChangeTextDocumentFeature { constructor(_client) { this._client = _client; this._changeData = new Map(); this._forcingDelivery = false; } get registrationType() { return vscode_languageserver_protocol_1.DidChangeTextDocumentNotification.type; } fillClientCapabilities(capabilities) { ensure(ensure(capabilities, 'textDocument'), 'synchronization').dynamicRegistration = true; } initialize(capabilities, documentSelector) { let textDocumentSyncOptions = capabilities.resolvedTextDocumentSync; if (documentSelector && textDocumentSyncOptions && textDocumentSyncOptions.change !== undefined && textDocumentSyncOptions.change !== vscode_languageserver_protocol_1.TextDocumentSyncKind.None) { this.register({ id: UUID.generateUuid(), registerOptions: Object.assign({}, { documentSelector: documentSelector }, { syncKind: textDocumentSyncOptions.change }) }); } } register(data) { if (!data.registerOptions.documentSelector) { return; } if (!this._listener) { this._listener = vscode_1.workspace.onDidChangeTextDocument(this.callback, this); } this._changeData.set(data.id, { documentSelector: data.registerOptions.documentSelector, syncKind: data.registerOptions.syncKind }); } callback(event) { // Text document changes are send for dirty changes as well. We don't // have dirty / un-dirty events in the LSP so we ignore content changes // with length zero. if (event.contentChanges.length === 0) { return; } for (const changeData of this._changeData.values()) { if (vscode_1.languages.match(changeData.documentSelector, event.document)) { let middleware = this._client.clientOptions.middleware; if (changeData.syncKind === vscode_languageserver_protocol_1.TextDocumentSyncKind.Incremental) { let params = this._client.code2ProtocolConverter.asChangeTextDocumentParams(event); if (middleware.didChange) { middleware.didChange(event, () => this._client.sendNotification(vscode_languageserver_protocol_1.DidChangeTextDocumentNotification.type, params)); } else { this._client.sendNotification(vscode_languageserver_protocol_1.DidChangeTextDocumentNotification.type, params); } } else if (changeData.syncKind === vscode_languageserver_protocol_1.TextDocumentSyncKind.Full) { let didChange = (event) => { if (this._changeDelayer) { if (this._changeDelayer.uri !== event.document.uri.toString()) { // Use this force delivery to track boolean state. Otherwise we might call two times. this.forceDelivery(); this._changeDelayer.uri = event.document.uri.toString(); } this._changeDelayer.delayer.trigger(() => { this._client.sendNotification(vscode_languageserver_protocol_1.DidChangeTextDocumentNotification.type, this._client.code2ProtocolConverter.asChangeTextDocumentParams(event.document)); }); } else { this._changeDelayer = { uri: event.document.uri.toString(), delayer: new async_1.Delayer(200) }; this._changeDelayer.delayer.trigger(() => { this._client.sendNotification(vscode_languageserver_protocol_1.DidChangeTextDocumentNotification.type, this._client.code2ProtocolConverter.asChangeTextDocumentParams(event.document)); }, -1); } }; if (middleware.didChange) { middleware.didChange(event, didChange); } else { didChange(event); } } } } } unregister(id) { this._changeData.delete(id); if (this._changeData.size === 0 && this._listener) { this._listener.dispose(); this._listener = undefined; } } dispose() { this._changeDelayer = undefined; this._forcingDelivery = false; this._changeData.clear(); if (this._listener) { this._listener.dispose(); this._listener = undefined; } } forceDelivery() { if (this._forcingDelivery || !this._changeDelayer) { return; } try { this._forcingDelivery = true; this._changeDelayer.delayer.forceDelivery(); } finally { this._forcingDelivery = false; } } getProvider(document) { for (const changeData of this._changeData.values()) { if (vscode_1.languages.match(changeData.documentSelector, document)) { return { send: (event) => { this.callback(event); } }; } } return undefined; } } class WillSaveFeature extends DocumentNotifications { constructor(client) { super(client, vscode_1.workspace.onWillSaveTextDocument, vscode_languageserver_protocol_1.WillSaveTextDocumentNotification.type, client.clientOptions.middleware.willSave, (willSaveEvent) => client.code2ProtocolConverter.asWillSaveTextDocumentParams(willSaveEvent), (selectors, willSaveEvent) => DocumentNotifications.textDocumentFilter(selectors, willSaveEvent.document)); } get registrationType() { return vscode_languageserver_protocol_1.WillSaveTextDocumentNotification.type; } fillClientCapabilities(capabilities) { let value = ensure(ensure(capabilities, 'textDocument'), 'synchronization'); value.willSave = true; } initialize(capabilities, documentSelector) { let textDocumentSyncOptions = capabilities.resolvedTextDocumentSync; if (documentSelector && textDocumentSyncOptions && textDocumentSyncOptions.willSave) { this.register({ id: UUID.generateUuid(), registerOptions: { documentSelector: documentSelector } }); } } } class WillSaveWaitUntilFeature { constructor(_client) { this._client = _client; this._selectors = new Map(); } get registrationType() { return vscode_languageserver_protocol_1.WillSaveTextDocumentWaitUntilRequest.type; } fillClientCapabilities(capabilities) { let value = ensure(ensure(capabilities, 'textDocument'), 'synchronization'); value.willSaveWaitUntil = true; } initialize(capabilities, documentSelector) { let textDocumentSyncOptions = capabilities.resolvedTextDocumentSync; if (documentSelector && textDocumentSyncOptions && textDocumentSyncOptions.willSaveWaitUntil) { this.register({ id: UUID.generateUuid(), registerOptions: { documentSelector: documentSelector } }); } } register(data) { if (!data.registerOptions.documentSelector) { return; } if (!this._listener) { this._listener = vscode_1.workspace.onWillSaveTextDocument(this.callback, this); } this._selectors.set(data.id, data.registerOptions.documentSelector); } callback(event) { if (DocumentNotifications.textDocumentFilter(this._selectors.values(), event.document)) { let middleware = this._client.clientOptions.middleware; let willSaveWaitUntil = (event) => { return this._client.sendRequest(vscode_languageserver_protocol_1.WillSaveTextDocumentWaitUntilRequest.type, this._client.code2ProtocolConverter.asWillSaveTextDocumentParams(event)).then((edits) => { let vEdits = this._client.protocol2CodeConverter.asTextEdits(edits); return vEdits === undefined ? [] : vEdits; }); }; event.waitUntil(middleware.willSaveWaitUntil ? middleware.willSaveWaitUntil(event, willSaveWaitUntil) : willSaveWaitUntil(event)); } } unregister(id) { this._selectors.delete(id); if (this._selectors.size === 0 && this._listener) { this._listener.dispose(); this._listener = undefined; } } dispose() { this._selectors.clear(); if (this._listener) { this._listener.dispose(); this._listener = undefined; } } } class DidSaveTextDocumentFeature extends DocumentNotifications { constructor(client) { super(client, vscode_1.workspace.onDidSaveTextDocument, vscode_languageserver_protocol_1.DidSaveTextDocumentNotification.type, client.clientOptions.middleware.didSave, (textDocument) => client.code2ProtocolConverter.asSaveTextDocumentParams(textDocument, this._includeText), DocumentNotifications.textDocumentFilter); this._includeText = false; } get registrationType() { return vscode_languageserver_protocol_1.DidSaveTextDocumentNotification.type; } fillClientCapabilities(capabilities) { ensure(ensure(capabilities, 'textDocument'), 'synchronization').didSave = true; } initialize(capabilities, documentSelector) { const textDocumentSyncOptions = capabilities.resolvedTextDocumentSync; if (documentSelector && textDocumentSyncOptions && textDocumentSyncOptions.save) { const saveOptions = typeof textDocumentSyncOptions.save === 'boolean' ? { includeText: false } : { includeText: !!textDocumentSyncOptions.save.includeText }; this.register({ id: UUID.generateUuid(), registerOptions: Object.assign({}, { documentSelector: documentSelector }, saveOptions) }); } } register(data) { this._includeText = !!data.registerOptions.includeText; super.register(data); } } class FileSystemWatcherFeature { constructor(_client, _notifyFileEvent) { this._client = _client; this._notifyFileEvent = _notifyFileEvent; this._watchers = new Map(); } get registrationType() { return vscode_languageserver_protocol_1.DidChangeWatchedFilesNotification.type; } fillClientCapabilities(capabilities) { ensure(ensure(capabilities, 'workspace'), 'didChangeWatchedFiles').dynamicRegistration = true; } initialize(_capabilities, _documentSelector) { } register(data) { if (!Array.isArray(data.registerOptions.watchers)) { return; } let disposables = []; for (let watcher of data.registerOptions.watchers) { if (!Is.string(watcher.globPattern)) { continue; } let watchCreate = true, watchChange = true, watchDelete = true; if (watcher.kind !== undefined && watcher.kind !== null) { watchCreate = (watcher.kind & vscode_languageserver_protocol_1.WatchKind.Create) !== 0; watchChange = (watcher.kind & vscode_languageserver_protocol_1.WatchKind.Change) !== 0; watchDelete = (watcher.kind & vscode_languageserver_protocol_1.WatchKind.Delete) !== 0; } let fileSystemWatcher = vscode_1.workspace.createFileSystemWatcher(watcher.globPattern, !watchCreate, !watchChange, !watchDelete); this.hookListeners(fileSystemWatcher, watchCreate, watchChange, watchDelete); disposables.push(fileSystemWatcher); } this._watchers.set(data.id, disposables); } registerRaw(id, fileSystemWatchers) { let disposables = []; for (let fileSystemWatcher of fileSystemWatchers) { this.hookListeners(fileSystemWatcher, true, true, true, disposables); } this._watchers.set(id, disposables); } hookListeners(fileSystemWatcher, watchCreate, watchChange, watchDelete, listeners) { if (watchCreate) { fileSystemWatcher.onDidCreate((resource) => this._notifyFileEvent({ uri: this._client.code2ProtocolConverter.asUri(resource), type: vscode_languageserver_protocol_1.FileChangeType.Created }), null, listeners); } if (watchChange) { fileSystemWatcher.onDidChange((resource) => this._notifyFileEvent({ uri: this._client.code2ProtocolConverter.asUri(resource), type: vscode_languageserver_protocol_1.FileChangeType.Changed }), null, listeners); } if (watchDelete) { fileSystemWatcher.onDidDelete((resource) => this._notifyFileEvent({ uri: this._client.code2ProtocolConverter.asUri(resource), type: vscode_languageserver_protocol_1.FileChangeType.Deleted }), null, listeners); } } unregister(id) { let disposables = this._watchers.get(id); if (disposables) { for (let disposable of disposables) { disposable.dispose(); } } } dispose() { this._watchers.forEach((disposables) => { for (let disposable of disposables) { disposable.dispose(); } }); this._watchers.clear(); } } class TextDocumentFeature { constructor(_client, _registrationType) { this._client = _client; this._registrationType = _registrationType; this._registrations = new Map(); } get registrationType() { return this._registrationType; } register(data) { if (!data.registerOptions.documentSelector) { return; } let registration = this.registerLanguageProvider(data.registerOptions); this._registrations.set(data.id, { disposable: registration[0], data, provider: registration[1] }); } unregister(id) { let registration = this._registrations.get(id); if (registration !== undefined) { registration.disposable.dispose(); } } dispose() { this._registrations.forEach((value) => { value.disposable.dispose(); }); this._registrations.clear(); } getRegistration(documentSelector, capability) { if (!capability) { return [undefined, undefined]; } else if (vscode_languageserver_protocol_1.TextDocumentRegistrationOptions.is(capability)) { const id = vscode_languageserver_protocol_1.StaticRegistrationOptions.hasId(capability) ? capability.id : UUID.generateUuid(); const selector = capability.documentSelector || documentSelector; if (selector) { return [id, Object.assign({}, capability, { documentSelector: selector })]; } } else if (Is.boolean(capability) && capability === true || vscode_languageserver_protocol_1.WorkDoneProgressOptions.is(capability)) { if (!documentSelector) { return [undefined, undefined]; } let options = (Is.boolean(capability) && capability === true ? { documentSelector } : Object.assign({}, capability, { documentSelector })); return [UUID.generateUuid(), options]; } return [undefined, undefined]; } getRegistrationOptions(documentSelector, capability) { if (!documentSelector || !capability) { return undefined; } return (Is.boolean(capability) && capability === true ? { documentSelector } : Object.assign({}, capability, { documentSelector })); } getProvider(textDocument) { for (const registration of this._registrations.values()) { let selector = registration.data.registerOptions.documentSelector; if (selector !== null && vscode_1.languages.match(selector, textDocument)) { return registration.provider; } } return undefined; } getAllProviders() { const result = []; for (const item of this._registrations.values()) { result.push(item.provider); } return result; } } exports.TextDocumentFeature = TextDocumentFeature; class WorkspaceFeature { constructor(_client, _registrationType) { this._client = _client; this._registrationType = _registrationType; this._registrations = new Map(); } get registrationType() { return this._registrationType; } register(data) { const registration = this.registerLanguageProvider(data.registerOptions); this._registrations.set(data.id, { disposable: registration[0], provider: registration[1] }); } unregister(id) { let registration = this._registrations.get(id); if (registration !== undefined) { registration.disposable.dispose(); } } dispose() { this._registrations.forEach((registration) => { registration.disposable.dispose(); }); this._registrations.clear(); } getProviders() { const result = []; for (const registration of this._registrations.values()) { result.push(registration.provider); } return result; } } class CompletionItemFeature extends TextDocumentFeature { constructor(client) { super(client, vscode_languageserver_protocol_1.CompletionRequest.type); } fillClientCapabilities(capabilities) { let completion = ensure(ensure(capabilities, 'textDocument'), 'completion'); completion.dynamicRegistration = true; completion.contextSupport = true; completion.completionItem = { snippetSupport: true, commitCharactersSupport: true, documentationFormat: [vscode_languageserver_protocol_1.MarkupKind.Markdown, vscode_languageserver_protocol_1.MarkupKind.PlainText], deprecatedSupport: true, preselectSupport: true, tagSupport: { valueSet: [vscode_languageserver_protocol_1.CompletionItemTag.Deprecated] }, insertReplaceSupport: true, resolveSupport: { properties: ['documentation', 'detail', 'additionalTextEdits'] }, insertTextModeSupport: { valueSet: [vscode_languageserver_protocol_1.InsertTextMode.asIs, vscode_languageserver_protocol_1.InsertTextMode.adjustIndentation] } }; completion.completionItemKind = { valueSet: SupportedCompletionItemKinds }; } initialize(capabilities, documentSelector) { const options = this.getRegistrationOptions(documentSelector, capabilities.completionProvider); if (!options) { return; } this.register({ id: UUID.generateUuid(), registerOptions: options }); } registerLanguageProvider(options) { const triggerCharacters = options.triggerCharacters || []; const provider = { provideCompletionItems: (document, position, token, context) => { const client = this._client; const middleware = this._client.clientOptions.middleware; const provideCompletionItems = (document, position, context, token) => { return client.sendRequest(vscode_languageserver_protocol_1.CompletionRequest.type, client.code2ProtocolConverter.asCompletionParams(document, position, context), token).then(client.protocol2CodeConverter.asCompletionResult, (error) => { return client.handleFailedRequest(vscode_languageserver_protocol_1.CompletionRequest.type, error, null); }); }; return middleware.provideCompletionItem ? middleware.provideCompletionItem(document, position, context, token, provideCompletionItems) : provideCompletionItems(document, position, context, token); }, resolveCompletionItem: options.resolveProvider ? (item, token) => { const client = this._client; const middleware = this._client.clientOptions.middleware; const resolveCompletionItem = (item, token) => { return client.sendRequest(vscode_languageserver_protocol_1.CompletionResolveRequest.type, client.code2ProtocolConverter.asCompletionItem(item), token).then(client.protocol2CodeConverter.asCompletionItem, (error) => { return client.handleFailedRequest(vscode_languageserver_protocol_1.CompletionResolveRequest.type, error, item); }); }; return middleware.resolveCompletionItem ? middleware.resolveCompletionItem(item, token, resolveCompletionItem) : resolveCompletionItem(item, token); } : undefined }; return [vscode_1.languages.registerCompletionItemProvider(options.documentSelector, provider, ...triggerCharacters), provider]; } } class HoverFeature extends TextDocumentFeature { constructor(client) { super(client, vscode_languageserver_protocol_1.HoverRequest.type); } fillClientCapabilities(capabilities) { const hoverCapability = (ensure(ensure(capabilities, 'textDocument'), 'hover')); hoverCapability.dynamicRegistration = true; hoverCapability.contentFormat = [vscode_languageserver_protocol_1.MarkupKind.Markdown, vscode_languageserver_protocol_1.MarkupKind.PlainText]; } initialize(capabilities, documentSelector) { const options = this.getRegistrationOptions(documentSelector, capabilities.hoverProvider); if (!options) { return; } this.register({ id: UUID.generateUuid(), registerOptions: options }); } registerLanguageProvider(options) { const provider = { provideHover: (document, position, token) => { const client = this._client; const provideHover = (document, position, token) => { return client.sendRequest(vscode_languageserver_protocol_1.HoverRequest.type, client.code2ProtocolConverter.asTextDocumentPositionParams(document, position), token).then(client.protocol2CodeConverter.asHover, (error) => { return client.handleFailedRequest(vscode_languageserver_protocol_1.HoverRequest.type, error, null); }); }; const middleware = client.clientOptions.middleware; return middleware.provideHover ? middleware.provideHover(document, position, token, provideHover) : provideHover(document, position, token); } }; return [vscode_1.languages.registerHoverProvider(options.documentSelector, provider), provider]; } } class SignatureHelpFeature extends TextDocumentFeature { constructor(client) { super(client, vscode_languageserver_protocol_1.SignatureHelpRequest.type); } fillClientCapabilities(capabilities) { let config = ensure(ensure(capabilities, 'textDocument'), 'signatureHelp'); config.dynamicRegistration = true; config.signatureInformation = { documentationFormat: [vscode_languageserver_protocol_1.MarkupKind.Markdown, vscode_languageserver_protocol_1.MarkupKind.PlainText] }; config.signatureInformation.parameterInformation = { labelOffsetSupport: true }; config.signatureInformation.activeParameterSupport = true; config.contextSupport = true; } initialize(capabilities, documentSelector) { const options = this.getRegistrationOptions(documentSelector, capabilities.signatureHelpProvider); if (!options) { return; } this.register({ id: UUID.generateUuid(), registerOptions: options }); } registerLanguageProvider(options) { const provider = { provideSignatureHelp: (document, position, token, context) => { const client = this._client; const providerSignatureHelp = (document, position, context, token) => { return client.sendRequest(vscode_languageserver_protocol_1.SignatureHelpRequest.type, client.code2ProtocolConverter.asSignatureHelpParams(document, position, context), token).then(client.protocol2CodeConverter.asSignatureHelp, (error) => { return client.handleFailedRequest(vscode_languageserver_protocol_1.SignatureHelpRequest.type, error, null); }); }; const middleware = client.clientOptions.middleware; return middleware.provideSignatureHelp ? middleware.provideSignatureHelp(document, position, context, token, providerSignatureHelp) : providerSignatureHelp(document, position, context, token); } }; let disposable; if (options.retriggerCharacters === undefined) { const triggerCharacters = options.triggerCharacters || []; disposable = vscode_1.languages.registerSignatureHelpProvider(options.documentSelector, provider, ...triggerCharacters); } else { const metaData = { triggerCharacters: options.triggerCharacters || [], retriggerCharacters: options.retriggerCharacters || [] }; disposable = vscode_1.languages.registerSignatureHelpProvider(options.documentSelector, provider, metaData); } return [disposable, provider]; } } class DefinitionFeature extends TextDocumentFeature { constructor(client) { super(client, vscode_languageserver_protocol_1.DefinitionRequest.type); } fillClientCapabilities(capabilities) { let definitionSupport = ensure(ensure(capabilities, 'textDocument'), 'definition'); definitionSupport.dynamicRegistration = true; definitionSupport.linkSupport = true; } initialize(capabilities, documentSelector) { const options = this.getRegistrationOptions(documentSelector, capabilities.definitionProvider); if (!options) { return; } this.register({ id: UUID.generateUuid(), registerOptions: options }); } registerLanguageProvider(options) { const provider = { provideDefinition: (document, position, token) => { const client = this._client; const provideDefinition = (document, position, token) => { return client.sendRequest(vscode_languageserver_protocol_1.DefinitionRequest.type, client.code2ProtocolConverter.asTextDocumentPositionParams(document, position), token).then(client.protocol2CodeConverter.asDefinitionResult, (error) => { return client.handleFailedRequest(vscode_languageserver_protocol_1.DefinitionRequest.type, error, null); }); }; const middleware = client.clientOptions.middleware; return middleware.provideDefinition ? middleware.provideDefinition(document, position, token, provideDefinition) : provideDefinition(document, position, token); } }; return [vscode_1.languages.registerDefinitionProvider(options.documentSelector, provider), provider]; } } class ReferencesFeature extends TextDocumentFeature { constructor(client) { super(client, vscode_languageserver_protocol_1.ReferencesRequest.type); } fillClientCapabilities(capabilities) { ensure(ensure(capabilities, 'textDocument'), 'references').dynamicRegistration = true; } initialize(capabilities, documentSelector) { const options = this.getRegistrationOptions(documentSelector, capabilities.referencesProvider); if (!options) { return; } this.register({ id: UUID.generateUuid(), registerOptions: options }); } registerLanguageProvider(options) { const provider = { provideReferences: (document, position, options, token) => { const client = this._client; const _providerReferences = (document, position, options, token) => { return client.sendRequest(vscode_languageserver_protocol_1.ReferencesRequest.type, client.code2ProtocolConverter.asReferenceParams(document, position, options), token).then(client.protocol2CodeConverter.asReferences, (error) => { return client.handleFailedRequest(vscode_languageserver_protocol_1.ReferencesRequest.type, error, null); }); }; const middleware = client.clientOptions.middleware; return middleware.provideReferences ? middleware.provideReferences(document, position, options, token, _providerReferences) : _providerReferences(document, position, options, token); } }; return [vscode_1.languages.registerReferenceProvider(options.documentSelector, provider), provider]; } } class DocumentHighlightFeature extends TextDocumentFeature { constructor(client) { super(client, vscode_languageserver_protocol_1.DocumentHighlightRequest.type); } fillClientCapabilities(capabilities) { ensure(ensure(capabilities, 'textDocument'), 'documentHighlight').dynamicRegistration = true; } initialize(capabilities, documentSelector) { const options = this.getRegistrationOptions(documentSelector, capabilities.documentHighlightProvider); if (!options) { return; } this.register({ id: UUID.generateUuid(), registerOptions: options }); } registerLanguageProvider(options) { const provider = { provideDocumentHighlights: (document, position, token) => { const client = this._client; const _provideDocumentHighlights = (document, position, token) => { return client.sendRequest(vscode_languageserver_protocol_1.DocumentHighlightRequest.type, client.code2ProtocolConverter.asTextDocumentPositionParams(document, position), token).then(client.protocol2CodeConverter.asDocumentHighlights, (error) => { return client.handleFailedRequest(vscode_languageserver_protocol_1.DocumentHighlightRequest.type, error, null); }); }; const middleware = client.clientOptions.middleware; return middleware.provideDocumentHighlights ? middleware.provideDocumentHighlights(document, position, token, _provideDocumentHighlights) : _provideDocumentHighlights(document, position, token); } }; return [vscode_1.languages.registerDocumentHighlightProvider(options.documentSelector, provider), provider]; } } class DocumentSymbolFeature extends TextDocumentFeature { constructor(client) { super(client, vscode_languageserver_protocol_1.DocumentSymbolRequest.type); } fillClientCapabilities(capabilities) { let symbolCapabilities = ensure(ensure(capabilities, 'textDocument'), 'documentSymbol'); symbolCapabilities.dynamicRegistration = true; symbolCapabilities.symbolKind = { valueSet: SupportedSymbolKinds }; symbolCapabilities.hierarchicalDocumentSymbolSupport = true; symbolCapabilities.tagSupport = { valueSet: SupportedSymbolTags }; symbolCapabilities.labelSupport = true; } initialize(capabilities, documentSelector) { const options = this.getRegistrationOptions(documentSelector, capabilities.documentSymbolProvider); if (!options) { return; } this.register({ id: UUID.generateUuid(), registerOptions: options }); } registerLanguageProvider(options) { const provider = { provideDocumentSymbols: (document, token) => { const client = this._client; const _provideDocumentSymbols = (document, token) => { return client.sendRequest(vscode_languageserver_protocol_1.DocumentSymbolRequest.type, client.code2ProtocolConverter.asDocumentSymbolParams(document), token).then((data) => { if (data === null) { return undefined; } if (data.length === 0) { return []; } else { let element = data[0]; if (vscode_languageserver_protocol_1.DocumentSymbol.is(element)) { return client.protocol2CodeConverter.asDocumentSymbols(data); } else { return client.protocol2CodeConverter.asSymbolInformations(data); } } }, (error) => { return client.handleFailedRequest(vscode_languageserver_protocol_1.DocumentSymbolRequest.type, error, null); }); }; const middleware = client.clientOptions.middleware; return middleware.provideDocumentSymbols ? middleware.provideDocumentSymbols(document, token, _provideDocumentSymbols) : _provideDocumentSymbols(document, token); } }; const metaData = options.label !== undefined ? { label: options.label } : undefined; return [vscode_1.languages.registerDocumentSymbolProvider(options.documentSelector, provider, metaData), provider]; } } class WorkspaceSymbolFeature extends WorkspaceFeature { constructor(client) { super(client, vscode_languageserver_protocol_1.WorkspaceSymbolRequest.type); } fillClientCapabilities(capabilities) { let symbolCapabilities = ensure(ensure(capabilities, 'workspace'), 'symbol'); symbolCapabilities.dynamicRegistration = true; symbolCapabilities.symbolKind = { valueSet: SupportedSymbolKinds }; symbolCapabilities.tagSupport = { valueSet: SupportedSymbolTags }; } initialize(capabilities) { if (!capabilities.workspaceSymbolProvider) { return; } this.register({ id: UUID.generateUuid(), registerOptions: capabilities.workspaceSymbolProvider === true ? { workDoneProgress: false } : capabilities.workspaceSymbolProvider }); } registerLanguageProvider(_options) { const provider = { provideWorkspaceSymbols: (query, token) => { const client = this._client; const provideWorkspaceSymbols = (query, token) => { return client.sendRequest(vscode_languageserver_protocol_1.WorkspaceSymbolRequest.type, { query }, token).then(client.protocol2CodeConverter.asSymbolInformations, (error) => { return client.handleFailedRequest(vscode_languageserver_protocol_1.WorkspaceSymbolRequest.type, error, null); }); }; const middleware = client.clientOptions.middleware; return middleware.provideWorkspaceSymbols ? middleware.provideWorkspaceSymbols(query, token, provideWorkspaceSymbols) : provideWorkspaceSymbols(query, token); } }; return [vscode_1.languages.registerWorkspaceSymbolProvider(provider), provider]; } } class CodeActionFeature extends TextDocumentFeature { constructor(client) { super(client, vscode_languageserver_protocol_1.CodeActionRequest.type); } fillClientCapabilities(capabilities) { const cap = ensure(ensure(capabilities, 'textDocument'), 'codeAction'); cap.dynamicRegistration = true; cap.isPreferredSupport = true; cap.disabledSupport = true; cap.dataSupport = true; // We can only resolve the edit property. cap.resolveSupport = { properties: ['edit'] }; cap.codeActionLiteralSupport = { codeActionKind: { valueSet: [ vscode_languageserver_protocol_1.CodeActionKind.Empty, vscode_languageserver_protocol_1.CodeActionKind.QuickFix, vscode_languageserver_protocol_1.CodeActionKind.Refactor, vscode_languageserver_protocol_1.CodeActionKind.RefactorExtract, vscode_languageserver_protocol_1.CodeActionKind.RefactorInline, vscode_languageserver_protocol_1.CodeActionKind.RefactorRewrite, vscode_languageserver_protocol_1.CodeActionKind.Source, vscode_languageserver_protocol_1.CodeActionKind.SourceOrganizeImports ] } }; cap.honorsChangeAnnotations = false; } initialize(capabilities, documentSelector) { const options = this.getRegistrationOptions(documentSelector, capabilities.codeActionProvider); if (!options) { return; } this.register({ id: UUID.generateUuid(), registerOptions: options }); } registerLanguageProvider(options) { const provider = { provideCodeActions: (document, range, context, token) => { const client = this._client; const _provideCodeActions = (document, range, context, token) => { const params = { textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document), range: client.code2ProtocolConverter.asRange(range), context: client.code2ProtocolConverter.asCodeActionContext(context) }; return client.sendRequest(vscode_languageserver_protocol_1.CodeActionRequest.type, params, token).then((values) => { if (values === null) { return undefined; } const result = []; for (let item of values) { if (vscode_languageserver_protocol_1.Command.is(item)) { result.push(client.protocol2CodeConverter.asCommand(item)); } else { result.push(client.protocol2CodeConverter.asCodeAction(item)); } } return result; }, (error) => { return client.handleFailedRequest(vscode_languageserver_protocol_1.CodeActionRequest.type, error, null); }); }; const middleware = client.clientOptions.middleware; return middleware.provideCodeActions ? middleware.provideCodeActions(document, range, context, token, _provideCodeActions) : _provideCodeActions(document, range, context, token); }, resolveCodeAction: options.resolveProvider ? (item, token) => { const client = this._client; const middleware = this._client.clientOptions.middleware; const resolveCodeAction = (item, token) => { return client.sendRequest(vscode_languageserver_protocol_1.CodeActionResolveRequest.type, client.code2ProtocolConverter.asCodeAction(item), token).then(client.protocol2CodeConverter.asCodeAction, (error) => { return client.handleFailedRequest(vscode_languageserver_protocol_1.CodeActionResolveRequest.type, error, item); }); }; return middleware.resolveCodeAction ? middleware.resolveCodeAction(item, token, resolveCodeAction) : resolveCodeAction(item, token); } : undefined }; return [vscode_1.languages.registerCodeActionsProvider(options.documentSelector, provider, (options.codeActionKinds ? { providedCodeActionKinds: this._client.protocol2CodeConverter.asCodeActionKinds(options.codeActionKinds) } : undefined)), provider]; } } class CodeLensFeature extends TextDocumentFeature { constructor(client) { super(client, vscode_languageserver_protocol_1.CodeLensRequest.type); } fillClientCapabilities(capabilities) { ensure(ensure(capabilities, 'textDocument'), 'codeLens').dynamicRegistration = true; ensure(ensure(capabilities, 'workspace'), 'codeLens').refreshSupport = true; } initialize(capabilities, documentSelector) { const client = this._client; client.onRequest(vscode_languageserver_protocol_1.CodeLensRefreshRequest.type, async () => { for (const provider of this.getAllProviders()) { provider.onDidChangeCodeLensEmitter.fire(); } }); const options = this.getRegistrationOptions(documentSelector, capabilities.codeLensProvider); if (!options) { return; } this.register({ id: UUID.generateUuid(), registerOptions: options }); } registerLanguageProvider(options) { const eventEmitter = new vscode_1.EventEmitter(); const provider = { onDidChangeCodeLenses: eventEmitter.event, provideCodeLenses: (document, token) => { const client = this._client; const provideCodeLenses = (document, token) => { return client.sendRequest(vscode_languageserver_protocol_1.CodeLensRequest.type, client.code2ProtocolConverter.asCodeLensParams(document), token).then(client.protocol2CodeConverter.asCodeLenses, (error) => { return client.handleFailedRequest(vscode_languageserver_protocol_1.CodeLensRequest.type, error, null); }); }; const middleware = client.clientOptions.middleware; return middleware.provideCodeLenses ? middleware.provideCodeLenses(document, token, provideCodeLenses) : provideCodeLenses(document, token); }, resolveCodeLens: (options.resolveProvider) ? (codeLens, token) => { const client = this._client; const resolveCodeLens = (codeLens, token) => { return client.sendRequest(vscode_languageserver_protocol_1.CodeLensResolveRequest.type, client.code2ProtocolConverter.asCodeLens(codeLens), token).then(client.protocol2CodeConverter.asCodeLens, (error) => { return client.handleFailedRequest(vscode_languageserver_protocol_1.CodeLensResolveRequest.type, error, codeLens); }); }; const middleware = client.clientOptions.middleware; return middleware.resolveCodeLens ? middleware.resolveCodeLens(codeLens, token, resolveCodeLens) : resolveCodeLens(codeLens, token); } : undefined }; return [vscode_1.languages.registerCodeLensProvider(options.documentSelector, provider), { provider, onDidChangeCodeLensEmitter: eventEmitter }]; } } class DocumentFormattingFeature extends TextDocumentFeature { constructor(client) { super(client, vscode_languageserver_protocol_1.DocumentFormattingRequest.type); } fillClientCapabilities(capabilities) { ensure(ensure(capabilities, 'textDocument'), 'formatting').dynamicRegistration = true; } initialize(capabilities, documentSelector) { const options = this.getRegistrationOptions(documentSelector, capabilities.documentFormattingProvider); if (!options) { return; } this.register({ id: UUID.generateUuid(), registerOptions: options }); } registerLanguageProvider(options) { const provider = { provideDocumentFormattingEdits: (document, options, token) => { const client = this._client; const provideDocumentFormattingEdits = (document, options, token) => { const params = { textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document), options: client.code2ProtocolConverter.asFormattingOptions(options, FileFormattingOptions.fromConfiguration(document)) }; return client.sendRequest(vscode_languageserver_protocol_1.DocumentFormattingRequest.type, params, token).then(client.protocol2CodeConverter.asTextEdits, (error) => { return client.handleFailedRequest(vscode_languageserver_protocol_1.DocumentFormattingRequest.type, error, null); }); }; const middleware = client.clientOptions.middleware; return middleware.provideDocumentFormattingEdits ? middleware.provideDocumentFormattingEdits(document, options, token, provideDocumentFormattingEdits) : provideDocumentFormattingEdits(document, options, token); } }; return [vscode_1.languages.registerDocumentFormattingEditProvider(options.documentSelector, provider), provider]; } } class DocumentRangeFormattingFeature extends TextDocumentFeature { constructor(client) { super(client, vscode_languageserver_protocol_1.DocumentRangeFormattingRequest.type); } fillClientCapabilities(capabilities) { ensure(ensure(capabilities, 'textDocument'), 'rangeFormatting').dynamicRegistration = true; } initialize(capabilities, documentSelector) { const options = this.getRegistrationOptions(documentSelector, capabilities.documentRangeFormattingProvider); if (!options) { return; } this.register({ id: UUID.generateUuid(), registerOptions: options }); } registerLanguageProvider(options) { const provider = { provideDocumentRangeFormattingEdits: (document, range, options, token) => { const client = this._client; const provideDocumentRangeFormattingEdits = (document, range, options, token) => { const params = { textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document), range: client.code2ProtocolConverter.asRange(range), options: client.code2ProtocolConverter.asFormattingOptions(options, FileFormattingOptions.fromConfiguration(document)) }; return client.sendRequest(vscode_languageserver_protocol_1.DocumentRangeFormattingRequest.type, params, token).then(client.protocol2CodeConverter.asTextEdits, (error) => { return client.handleFailedRequest(vscode_languageserver_protocol_1.DocumentRangeFormattingRequest.type, error, null); }); }; const middleware = client.clientOptions.middleware; return middleware.provideDocumentRangeFormattingEdits ? middleware.provideDocumentRangeFormattingEdits(document, range, options, token, provideDocumentRangeFormattingEdits) : provideDocumentRangeFormattingEdits(document, range, options, token); } }; return [vscode_1.languages.registerDocumentRangeFormattingEditProvider(options.documentSelector, provider), provider]; } } class DocumentOnTypeFormattingFeature extends TextDocumentFeature { constructor(client) { super(client, vscode_languageserver_protocol_1.DocumentOnTypeFormattingRequest.type); } fillClientCapabilities(capabilities) { ensure(ensure(capabilities, 'textDocument'), 'onTypeFormatting').dynamicRegistration = true; } initialize(capabilities, documentSelector) { const options = this.getRegistrationOptions(documentSelector, capabilities.documentOnTypeFormattingProvider); if (!options) { return; } this.register({ id: UUID.generateUuid(), registerOptions: options }); } registerLanguageProvider(options) { const provider = { provideOnTypeFormattingEdits: (document, position, ch, options, token) => { const client = this._client; const provideOnTypeFormattingEdits = (document, position, ch, options, token) => { let params = { textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document), position: client.code2ProtocolConverter.asPosition(position), ch: ch, options: client.code2ProtocolConverter.asFormattingOptions(options, FileFormattingOptions.fromConfiguration(document)) }; return client.sendRequest(vscode_languageserver_protocol_1.DocumentOnTypeFormattingRequest.type, params, token).then(client.protocol2CodeConverter.asTextEdits, (error) => { return client.handleFailedRequest(vscode_languageserver_protocol_1.DocumentOnTypeFormattingRequest.type, error, null); }); }; const middleware = client.clientOptions.middleware; return middleware.provideOnTypeFormattingEdits ? middleware.provideOnTypeFormattingEdits(document, position, ch, options, token, provideOnTypeFormattingEdits) : provideOnTypeFormattingEdits(document, position, ch, options, token); } }; const moreTriggerCharacter = options.moreTriggerCharacter || []; return [vscode_1.languages.registerOnTypeFormattingEditProvider(options.documentSelector, provider, options.firstTriggerCharacter, ...moreTriggerCharacter), provider]; } } class RenameFeature extends TextDocumentFeature { constructor(client) { super(client, vscode_languageserver_protocol_1.RenameRequest.type); } fillClientCapabilities(capabilities) { let rename = ensure(ensure(capabilities, 'textDocument'), 'rename'); rename.dynamicRegistration = true; rename.prepareSupport = true; rename.prepareSupportDefaultBehavior = vscode_languageserver_protocol_1.PrepareSupportDefaultBehavior.Identifier; rename.honorsChangeAnnotations = true; } initialize(capabilities, documentSelector) { const options = this.getRegistrationOptions(documentSelector, capabilities.renameProvider); if (!options) { return; } if (Is.boolean(capabilities.renameProvider)) { options.prepareProvider = false; } this.register({ id: UUID.generateUuid(), registerOptions: options }); } registerLanguageProvider(options) { const provider = { provideRenameEdits: (document, position, newName, token) => { const client = this._client; const provideRenameEdits = (document, position, newName, token) => { let params = { textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document), position: client.code2ProtocolConverter.asPosition(position), newName: newName }; return client.sendRequest(vscode_languageserver_protocol_1.RenameRequest.type, params, token).then(client.protocol2CodeConverter.asWorkspaceEdit, (error) => { return client.handleFailedRequest(vscode_languageserver_protocol_1.RenameRequest.type, error, null); }); }; const middleware = client.clientOptions.middleware; return middleware.provideRenameEdits ? middleware.provideRenameEdits(document, position, newName, token, provideRenameEdits) : provideRenameEdits(document, position, newName, token); }, prepareRename: options.prepareProvider ? (document, position, token) => { const client = this._client; const prepareRename = (document, position, token) => { let params = { textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document), position: client.code2ProtocolConverter.asPosition(position), }; return client.sendRequest(vscode_languageserver_protocol_1.PrepareRenameRequest.type, params, token).then((result) => { if (vscode_languageserver_protocol_1.Range.is(result)) { return client.protocol2CodeConverter.asRange(result); } else if (this.isDefaultBehavior(result)) { return result.defaultBehavior === true ? null : Promise.reject(new Error(`The element can't be renamed.`)); } else if (result && vscode_languageserver_protocol_1.Range.is(result.range)) { return { range: client.protocol2CodeConverter.asRange(result.range), placeholder: result.placeholder }; } // To cancel the rename vscode API expects a rejected promise. return Promise.reject(new Error(`The element can't be renamed.`)); }, (error) => { return client.handleFailedRequest(vscode_languageserver_protocol_1.PrepareRenameRequest.type, error, undefined); }); }; const middleware = client.clientOptions.middleware; return middleware.prepareRename ? middleware.prepareRename(document, position, token, prepareRename) : prepareRename(document, position, token); } : undefined }; return [vscode_1.languages.registerRenameProvider(options.documentSelector, provider), provider]; } isDefaultBehavior(value) { const candidate = value; return candidate && Is.boolean(candidate.defaultBehavior); } } class DocumentLinkFeature extends TextDocumentFeature { constructor(client) { super(client, vscode_languageserver_protocol_1.DocumentLinkRequest.type); } fillClientCapabilities(capabilities) { const documentLinkCapabilities = ensure(ensure(capabilities, 'textDocument'), 'documentLink'); documentLinkCapabilities.dynamicRegistration = true; documentLinkCapabilities.tooltipSupport = true; } initialize(capabilities, documentSelector) { const options = this.getRegistrationOptions(documentSelector, capabilities.documentLinkProvider); if (!options) { return; } this.register({ id: UUID.generateUuid(), registerOptions: options }); } registerLanguageProvider(options) { const provider = { provideDocumentLinks: (document, token) => { const client = this._client; const provideDocumentLinks = (document, token) => { return client.sendRequest(vscode_languageserver_protocol_1.DocumentLinkRequest.type, client.code2ProtocolConverter.asDocumentLinkParams(document), token).then(client.protocol2CodeConverter.asDocumentLinks, (error) => { return client.handleFailedRequest(vscode_languageserver_protocol_1.DocumentLinkRequest.type, error, null); }); }; const middleware = client.clientOptions.middleware; return middleware.provideDocumentLinks ? middleware.provideDocumentLinks(document, token, provideDocumentLinks) : provideDocumentLinks(document, token); }, resolveDocumentLink: options.resolveProvider ? (link, token) => { const client = this._client; let resolveDocumentLink = (link, token) => { return client.sendRequest(vscode_languageserver_protocol_1.DocumentLinkResolveRequest.type, client.code2ProtocolConverter.asDocumentLink(link), token).then(client.protocol2CodeConverter.asDocumentLink, (error) => { return client.handleFailedRequest(vscode_languageserver_protocol_1.DocumentLinkResolveRequest.type, error, link); }); }; const middleware = client.clientOptions.middleware; return middleware.resolveDocumentLink ? middleware.resolveDocumentLink(link, token, resolveDocumentLink) : resolveDocumentLink(link, token); } : undefined }; return [vscode_1.languages.registerDocumentLinkProvider(options.documentSelector, provider), provider]; } } class ConfigurationFeature { constructor(_client) { this._client = _client; this._listeners = new Map(); } get registrationType() { return vscode_languageserver_protocol_1.DidChangeConfigurationNotification.type; } fillClientCapabilities(capabilities) { ensure(ensure(capabilities, 'workspace'), 'didChangeConfiguration').dynamicRegistration = true; } initialize() { let section = this._client.clientOptions.synchronize.configurationSection; if (section !== undefined) { this.register({ id: UUID.generateUuid(), registerOptions: { section: section } }); } } register(data) { let disposable = vscode_1.workspace.onDidChangeConfiguration((event) => { this.onDidChangeConfiguration(data.registerOptions.section, event); }); this._listeners.set(data.id, disposable); if (data.registerOptions.section !== undefined) { this.onDidChangeConfiguration(data.registerOptions.section, undefined); } } unregister(id) { let disposable = this._listeners.get(id); if (disposable) { this._listeners.delete(id); disposable.dispose(); } } dispose() { for (let disposable of this._listeners.values()) { disposable.dispose(); } this._listeners.clear(); } onDidChangeConfiguration(configurationSection, event) { let sections; if (Is.string(configurationSection)) { sections = [configurationSection]; } else { sections = configurationSection; } if (sections !== undefined && event !== undefined) { let affected = sections.some((section) => event.affectsConfiguration(section)); if (!affected) { return; } } let didChangeConfiguration = (sections) => { if (sections === undefined) { this._client.sendNotification(vscode_languageserver_protocol_1.DidChangeConfigurationNotification.type, { settings: null }); return; } this._client.sendNotification(vscode_languageserver_protocol_1.DidChangeConfigurationNotification.type, { settings: this.extractSettingsInformation(sections) }); }; let middleware = this.getMiddleware(); middleware ? middleware(sections, didChangeConfiguration) : didChangeConfiguration(sections); } extractSettingsInformation(keys) { function ensurePath(config, path) { let current = config; for (let i = 0; i < path.length - 1; i++) { let obj = current[path[i]]; if (!obj) { obj = Object.create(null); current[path[i]] = obj; } current = obj; } return current; } let resource = this._client.clientOptions.workspaceFolder ? this._client.clientOptions.workspaceFolder.uri : undefined; let result = Object.create(null); for (let i = 0; i < keys.length; i++) { let key = keys[i]; let index = key.indexOf('.'); let config = null; if (index >= 0) { config = vscode_1.workspace.getConfiguration(key.substr(0, index), resource).get(key.substr(index + 1)); } else { config = vscode_1.workspace.getConfiguration(undefined, resource).get(key); } if (config) { let path = keys[i].split('.'); ensurePath(result, path)[path[path.length - 1]] = configuration_1.toJSONObject(config); } } return result; } getMiddleware() { let middleware = this._client.clientOptions.middleware; if (middleware.workspace && middleware.workspace.didChangeConfiguration) { return middleware.workspace.didChangeConfiguration; } else { return undefined; } } } class ExecuteCommandFeature { constructor(_client) { this._client = _client; this._commands = new Map(); } get registrationType() { return vscode_languageserver_protocol_1.ExecuteCommandRequest.type; } fillClientCapabilities(capabilities) { ensure(ensure(capabilities, 'workspace'), 'executeCommand').dynamicRegistration = true; } initialize(capabilities) { if (!capabilities.executeCommandProvider) { return; } this.register({ id: UUID.generateUuid(), registerOptions: Object.assign({}, capabilities.executeCommandProvider) }); } register(data) { const client = this._client; const middleware = client.clientOptions.middleware; const executeCommand = (command, args) => { let params = { command, arguments: args }; return client.sendRequest(vscode_languageserver_protocol_1.ExecuteCommandRequest.type, params).then(undefined, (error) => { return client.handleFailedRequest(vscode_languageserver_protocol_1.ExecuteCommandRequest.type, error, undefined); }); }; if (data.registerOptions.commands) { const disposables = []; for (const command of data.registerOptions.commands) { disposables.push(vscode_1.commands.registerCommand(command, (...args) => { return middleware.executeCommand ? middleware.executeCommand(command, args, executeCommand) : executeCommand(command, args); })); } this._commands.set(data.id, disposables); } } unregister(id) { let disposables = this._commands.get(id); if (disposables) { disposables.forEach(disposable => disposable.dispose()); } } dispose() { this._commands.forEach((value) => { value.forEach(disposable => disposable.dispose()); }); this._commands.clear(); } } var MessageTransports; (function (MessageTransports) { function is(value) { let candidate = value; return candidate && vscode_languageserver_protocol_1.MessageReader.is(value.reader) && vscode_languageserver_protocol_1.MessageWriter.is(value.writer); } MessageTransports.is = is; })(MessageTransports = exports.MessageTransports || (exports.MessageTransports = {})); class OnReady { constructor(_resolve, _reject) { this._resolve = _resolve; this._reject = _reject; this._used = false; } get isUsed() { return this._used; } resolve() { this._used = true; this._resolve(); } reject(error) { this._used = true; this._reject(error); } } class BaseLanguageClient { constructor(id, name, clientOptions) { var _a; this._traceFormat = vscode_languageserver_protocol_1.TraceFormat.Text; this._features = []; this._dynamicFeatures = new Map(); this._id = id; this._name = name; clientOptions = clientOptions || {}; const markdown = { isTrusted: false }; if (clientOptions.markdown !== undefined && clientOptions.markdown.isTrusted === true) { markdown.isTrusted = true; } this._clientOptions = { documentSelector: clientOptions.documentSelector || [], synchronize: clientOptions.synchronize || {}, diagnosticCollectionName: clientOptions.diagnosticCollectionName, outputChannelName: clientOptions.outputChannelName || this._name, revealOutputChannelOn: clientOptions.revealOutputChannelOn || RevealOutputChannelOn.Error, stdioEncoding: clientOptions.stdioEncoding || 'utf8', initializationOptions: clientOptions.initializationOptions, initializationFailedHandler: clientOptions.initializationFailedHandler, progressOnInitialization: !!clientOptions.progressOnInitialization, errorHandler: clientOptions.errorHandler || this.createDefaultErrorHandler((_a = clientOptions.connectionOptions) === null || _a === void 0 ? void 0 : _a.maxRestartCount), middleware: clientOptions.middleware || {}, uriConverters: clientOptions.uriConverters, workspaceFolder: clientOptions.workspaceFolder, connectionOptions: clientOptions.connectionOptions, markdown }; this._clientOptions.synchronize = this._clientOptions.synchronize || {}; this._state = ClientState.Initial; this._connectionPromise = undefined; this._resolvedConnection = undefined; this._initializeResult = undefined; if (clientOptions.outputChannel) { this._outputChannel = clientOptions.outputChannel; this._disposeOutputChannel = false; } else { this._outputChannel = undefined; this._disposeOutputChannel = true; } this._traceOutputChannel = clientOptions.traceOutputChannel; this._listeners = undefined; this._providers = undefined; this._diagnostics = undefined; this._fileEvents = []; this._fileEventDelayer = new async_1.Delayer(250); this._onReady = new Promise((resolve, reject) => { this._onReadyCallbacks = new OnReady(resolve, reject); }); this._onStop = undefined; this._telemetryEmitter = new vscode_languageserver_protocol_1.Emitter(); this._stateChangeEmitter = new vscode_languageserver_protocol_1.Emitter(); this._trace = vscode_languageserver_protocol_1.Trace.Off; this._tracer = { log: (messageOrDataObject, data) => { if (Is.string(messageOrDataObject)) { this.logTrace(messageOrDataObject, data); } else { this.logObjectTrace(messageOrDataObject); } }, }; this._c2p = c2p.createConverter(clientOptions.uriConverters ? clientOptions.uriConverters.code2Protocol : undefined); this._p2c = p2c.createConverter(clientOptions.uriConverters ? clientOptions.uriConverters.protocol2Code : undefined, this._clientOptions.markdown.isTrusted); this._syncedDocuments = new Map(); this.registerBuiltinFeatures(); } get state() { return this._state; } set state(value) { let oldState = this.getPublicState(); this._state = value; let newState = this.getPublicState(); if (newState !== oldState) { this._stateChangeEmitter.fire({ oldState, newState }); } } getPublicState() { if (this.state === ClientState.Running) { return State.Running; } else if (this.state === ClientState.Starting) { return State.Starting; } else { return State.Stopped; } } get initializeResult() { return this._initializeResult; } sendRequest(type, ...params) { if (!this.isConnectionActive()) { throw new Error('Language client is not ready yet'); } this.forceDocumentSync(); try { return this._resolvedConnection.sendRequest(type, ...params); } catch (error) { this.error(`Sending request ${Is.string(type) ? type : type.method} failed.`, error); throw error; } } onRequest(type, handler) { if (!this.isConnectionActive()) { throw new Error('Language client is not ready yet'); } try { return this._resolvedConnection.onRequest(type, handler); } catch (error) { this.error(`Registering request handler ${Is.string(type) ? type : type.method} failed.`, error); throw error; } } sendNotification(type, params) { if (!this.isConnectionActive()) { throw new Error('Language client is not ready yet'); } this.forceDocumentSync(); try { this._resolvedConnection.sendNotification(type, params); } catch (error) { this.error(`Sending notification ${Is.string(type) ? type : type.method} failed.`, error); throw error; } } onNotification(type, handler) { if (!this.isConnectionActive()) { throw new Error('Language client is not ready yet'); } try { return this._resolvedConnection.onNotification(type, handler); } catch (error) { this.error(`Registering notification handler ${Is.string(type) ? type : type.method} failed.`, error); throw error; } } onProgress(type, token, handler) { if (!this.isConnectionActive()) { throw new Error('Language client is not ready yet'); } try { if (vscode_languageserver_protocol_1.WorkDoneProgress.is(type)) { const handleWorkDoneProgress = this._clientOptions.middleware.handleWorkDoneProgress; if (handleWorkDoneProgress !== undefined) { return this._resolvedConnection.onProgress(type, token, (params) => { handleWorkDoneProgress(token, params, () => handler(params)); }); } } return this._resolvedConnection.onProgress(type, token, handler); } catch (error) { this.error(`Registering progress handler for token ${token} failed.`, error); throw error; } } sendProgress(type, token, value) { if (!this.isConnectionActive()) { throw new Error('Language client is not ready yet'); } this.forceDocumentSync(); try { this._resolvedConnection.sendProgress(type, token, value); } catch (error) { this.error(`Sending progress for token ${token} failed.`, error); throw error; } } get clientOptions() { return this._clientOptions; } get protocol2CodeConverter() { return this._p2c; } get code2ProtocolConverter() { return this._c2p; } get onTelemetry() { return this._telemetryEmitter.event; } get onDidChangeState() { return this._stateChangeEmitter.event; } get outputChannel() { if (!this._outputChannel) { this._outputChannel = vscode_1.window.createOutputChannel(this._clientOptions.outputChannelName ? this._clientOptions.outputChannelName : this._name); } return this._outputChannel; } get traceOutputChannel() { if (this._traceOutputChannel) { return this._traceOutputChannel; } return this.outputChannel; } get diagnostics() { return this._diagnostics; } createDefaultErrorHandler(maxRestartCount) { if (maxRestartCount !== undefined && maxRestartCount < 0) { throw new Error(`Invalid maxRestartCount: ${maxRestartCount}`); } return new DefaultErrorHandler(this._name, maxRestartCount !== null && maxRestartCount !== void 0 ? maxRestartCount : 4); } set trace(value) { this._trace = value; this.onReady().then(() => { this.resolveConnection().then((connection) => { connection.trace(this._trace, this._tracer, { sendNotification: false, traceFormat: this._traceFormat }); }); }, () => { }); } data2String(data) { if (data instanceof vscode_languageserver_protocol_1.ResponseError) { const responseError = data; return ` Message: ${responseError.message}\n Code: ${responseError.code} ${responseError.data ? '\n' + responseError.data.toString() : ''}`; } if (data instanceof Error) { if (Is.string(data.stack)) { return data.stack; } return data.message; } if (Is.string(data)) { return data; } return data.toString(); } info(message, data, showNotification = true) { this.outputChannel.appendLine(`[Info - ${(new Date().toLocaleTimeString())}] ${message}`); if (data) { this.outputChannel.appendLine(this.data2String(data)); } if (showNotification && this._clientOptions.revealOutputChannelOn <= RevealOutputChannelOn.Info) { this.showNotificationMessage(); } } warn(message, data, showNotification = true) { this.outputChannel.appendLine(`[Warn - ${(new Date().toLocaleTimeString())}] ${message}`); if (data) { this.outputChannel.appendLine(this.data2String(data)); } if (showNotification && this._clientOptions.revealOutputChannelOn <= RevealOutputChannelOn.Warn) { this.showNotificationMessage(); } } error(message, data, showNotification = true) { this.outputChannel.appendLine(`[Error - ${(new Date().toLocaleTimeString())}] ${message}`); if (data) { this.outputChannel.appendLine(this.data2String(data)); } if (showNotification && this._clientOptions.revealOutputChannelOn <= RevealOutputChannelOn.Error) { this.showNotificationMessage(); } } showNotificationMessage() { vscode_1.window.showInformationMessage('A request has failed. See the output for more information.', 'Go to output').then(() => { this.outputChannel.show(true); }); } logTrace(message, data) { this.traceOutputChannel.appendLine(`[Trace - ${(new Date().toLocaleTimeString())}] ${message}`); if (data) { this.traceOutputChannel.appendLine(this.data2String(data)); } } logObjectTrace(data) { if (data.isLSPMessage && data.type) { this.traceOutputChannel.append(`[LSP - ${(new Date().toLocaleTimeString())}] `); } else { this.traceOutputChannel.append(`[Trace - ${(new Date().toLocaleTimeString())}] `); } if (data) { this.traceOutputChannel.appendLine(`${JSON.stringify(data)}`); } } needsStart() { return this.state === ClientState.Initial || this.state === ClientState.Stopping || this.state === ClientState.Stopped; } needsStop() { return this.state === ClientState.Starting || this.state === ClientState.Running; } onReady() { return this._onReady; } isConnectionActive() { return this.state === ClientState.Running && !!this._resolvedConnection; } start() { if (this._onReadyCallbacks.isUsed) { this._onReady = new Promise((resolve, reject) => { this._onReadyCallbacks = new OnReady(resolve, reject); }); } this._listeners = []; this._providers = []; // If we restart then the diagnostics collection is reused. if (!this._diagnostics) { this._diagnostics = this._clientOptions.diagnosticCollectionName ? vscode_1.languages.createDiagnosticCollection(this._clientOptions.diagnosticCollectionName) : vscode_1.languages.createDiagnosticCollection(); } this.state = ClientState.Starting; this.resolveConnection().then((connection) => { connection.onLogMessage((message) => { switch (message.type) { case vscode_languageserver_protocol_1.MessageType.Error: this.error(message.message, undefined, false); break; case vscode_languageserver_protocol_1.MessageType.Warning: this.warn(message.message, undefined, false); break; case vscode_languageserver_protocol_1.MessageType.Info: this.info(message.message, undefined, false); break; default: this.outputChannel.appendLine(message.message); } }); connection.onShowMessage((message) => { switch (message.type) { case vscode_languageserver_protocol_1.MessageType.Error: vscode_1.window.showErrorMessage(message.message); break; case vscode_languageserver_protocol_1.MessageType.Warning: vscode_1.window.showWarningMessage(message.message); break; case vscode_languageserver_protocol_1.MessageType.Info: vscode_1.window.showInformationMessage(message.message); break; default: vscode_1.window.showInformationMessage(message.message); } }); connection.onRequest(vscode_languageserver_protocol_1.ShowMessageRequest.type, (params) => { let messageFunc; switch (params.type) { case vscode_languageserver_protocol_1.MessageType.Error: messageFunc = vscode_1.window.showErrorMessage; break; case vscode_languageserver_protocol_1.MessageType.Warning: messageFunc = vscode_1.window.showWarningMessage; break; case vscode_languageserver_protocol_1.MessageType.Info: messageFunc = vscode_1.window.showInformationMessage; break; default: messageFunc = vscode_1.window.showInformationMessage; } let actions = params.actions || []; return messageFunc(params.message, ...actions); }); connection.onTelemetry((data) => { this._telemetryEmitter.fire(data); }); connection.onRequest(vscode_languageserver_protocol_1.ShowDocumentRequest.type, async (params) => { var _a; const showDocument = async (params) => { const uri = this.protocol2CodeConverter.asUri(params.uri); try { if (params.external === true) { const success = await vscode_1.env.openExternal(uri); return { success }; } else { const options = {}; if (params.selection !== undefined) { options.selection = this.protocol2CodeConverter.asRange(params.selection); } if (params.takeFocus === undefined || params.takeFocus === false) { options.preserveFocus = true; } else if (params.takeFocus === true) { options.preserveFocus = false; } await vscode_1.window.showTextDocument(uri, options); return { success: true }; } } catch (error) { return { success: true }; } }; const middleware = (_a = this._clientOptions.middleware.window) === null || _a === void 0 ? void 0 : _a.showDocument; if (middleware !== undefined) { return middleware(params, showDocument); } else { return showDocument(params); } }); connection.listen(); // Error is handled in the initialize call. return this.initialize(connection); }).then(undefined, (error) => { this.state = ClientState.StartFailed; this._onReadyCallbacks.reject(error); this.error('Starting client failed', error); vscode_1.window.showErrorMessage(`Couldn't start client ${this._name}`); }); return new vscode_1.Disposable(() => { if (this.needsStop()) { this.stop(); } }); } resolveConnection() { if (!this._connectionPromise) { this._connectionPromise = this.createConnection(); } return this._connectionPromise; } initialize(connection) { this.refreshTrace(connection, false); let initOption = this._clientOptions.initializationOptions; let rootPath = this._clientOptions.workspaceFolder ? this._clientOptions.workspaceFolder.uri.fsPath : this._clientGetRootPath(); let initParams = { processId: null, clientInfo: { name: vscode_1.env.appName, version: vscode_1.version }, locale: this.getLocale(), rootPath: rootPath ? rootPath : null, rootUri: rootPath ? this._c2p.asUri(vscode_1.Uri.file(rootPath)) : null, capabilities: this.computeClientCapabilities(), initializationOptions: Is.func(initOption) ? initOption() : initOption, trace: vscode_languageserver_protocol_1.Trace.toString(this._trace), workspaceFolders: null }; this.fillInitializeParams(initParams); if (this._clientOptions.progressOnInitialization) { const token = UUID.generateUuid(); const part = new progressPart_1.ProgressPart(connection, token); initParams.workDoneToken = token; return this.doInitialize(connection, initParams).then((result) => { part.done(); return result; }, (error) => { part.cancel(); throw error; }); } else { return this.doInitialize(connection, initParams); } } doInitialize(connection, initParams) { return connection.initialize(initParams).then((result) => { this._resolvedConnection = connection; this._initializeResult = result; this.state = ClientState.Running; let textDocumentSyncOptions = undefined; if (Is.number(result.capabilities.textDocumentSync)) { if (result.capabilities.textDocumentSync === vscode_languageserver_protocol_1.TextDocumentSyncKind.None) { textDocumentSyncOptions = { openClose: false, change: vscode_languageserver_protocol_1.TextDocumentSyncKind.None, save: undefined }; } else { textDocumentSyncOptions = { openClose: true, change: result.capabilities.textDocumentSync, save: { includeText: false } }; } } else if (result.capabilities.textDocumentSync !== undefined && result.capabilities.textDocumentSync !== null) { textDocumentSyncOptions = result.capabilities.textDocumentSync; } this._capabilities = Object.assign({}, result.capabilities, { resolvedTextDocumentSync: textDocumentSyncOptions }); connection.onDiagnostics(params => this.handleDiagnostics(params)); connection.onRequest(vscode_languageserver_protocol_1.RegistrationRequest.type, params => this.handleRegistrationRequest(params)); // See https://github.com/Microsoft/vscode-languageserver-node/issues/199 connection.onRequest('client/registerFeature', params => this.handleRegistrationRequest(params)); connection.onRequest(vscode_languageserver_protocol_1.UnregistrationRequest.type, params => this.handleUnregistrationRequest(params)); // See https://github.com/Microsoft/vscode-languageserver-node/issues/199 connection.onRequest('client/unregisterFeature', params => this.handleUnregistrationRequest(params)); connection.onRequest(vscode_languageserver_protocol_1.ApplyWorkspaceEditRequest.type, params => this.handleApplyWorkspaceEdit(params)); connection.sendNotification(vscode_languageserver_protocol_1.InitializedNotification.type, {}); this.hookFileEvents(connection); this.hookConfigurationChanged(connection); this.initializeFeatures(connection); this._onReadyCallbacks.resolve(); return result; }).then(undefined, (error) => { if (this._clientOptions.initializationFailedHandler) { if (this._clientOptions.initializationFailedHandler(error)) { this.initialize(connection); } else { this.stop(); this._onReadyCallbacks.reject(error); } } else if (error instanceof vscode_languageserver_protocol_1.ResponseError && error.data && error.data.retry) { vscode_1.window.showErrorMessage(error.message, { title: 'Retry', id: 'retry' }).then(item => { if (item && item.id === 'retry') { this.initialize(connection); } else { this.stop(); this._onReadyCallbacks.reject(error); } }); } else { if (error && error.message) { vscode_1.window.showErrorMessage(error.message); } this.error('Server initialization failed.', error); this.stop(); this._onReadyCallbacks.reject(error); } throw error; }); } _clientGetRootPath() { let folders = vscode_1.workspace.workspaceFolders; if (!folders || folders.length === 0) { return undefined; } let folder = folders[0]; if (folder.uri.scheme === 'file') { return folder.uri.fsPath; } return undefined; } stop() { this._initializeResult = undefined; if (!this._connectionPromise) { this.state = ClientState.Stopped; return Promise.resolve(); } if (this.state === ClientState.Stopping && this._onStop) { return this._onStop; } this.state = ClientState.Stopping; this.cleanUp(false); // unhook listeners return this._onStop = this.resolveConnection().then(connection => { return connection.shutdown().then(() => { connection.exit(); connection.end(); connection.dispose(); this.state = ClientState.Stopped; this.cleanUpChannel(); this._onStop = undefined; this._connectionPromise = undefined; this._resolvedConnection = undefined; }); }); } cleanUp(channel = true, diagnostics = true) { if (this._listeners) { this._listeners.forEach(listener => listener.dispose()); this._listeners = undefined; } if (this._providers) { this._providers.forEach(provider => provider.dispose()); this._providers = undefined; } if (this._syncedDocuments) { this._syncedDocuments.clear(); } for (const feature of this._features.values()) { feature.dispose(); } if (channel) { this.cleanUpChannel(); } if (diagnostics && this._diagnostics) { this._diagnostics.dispose(); this._diagnostics = undefined; } } cleanUpChannel() { if (this._outputChannel && this._disposeOutputChannel) { this._outputChannel.dispose(); this._outputChannel = undefined; } } notifyFileEvent(event) { var _a; const client = this; function didChangeWatchedFile(event) { client._fileEvents.push(event); client._fileEventDelayer.trigger(() => { client.onReady().then(() => { client.resolveConnection().then(connection => { if (client.isConnectionActive()) { client.forceDocumentSync(); connection.didChangeWatchedFiles({ changes: client._fileEvents }); } client._fileEvents = []; }); }, (error) => { client.error(`Notify file events failed.`, error); }); }); } const workSpaceMiddleware = (_a = this.clientOptions.middleware) === null || _a === void 0 ? void 0 : _a.workspace; (workSpaceMiddleware === null || workSpaceMiddleware === void 0 ? void 0 : workSpaceMiddleware.didChangeWatchedFile) ? workSpaceMiddleware.didChangeWatchedFile(event, didChangeWatchedFile) : didChangeWatchedFile(event); } forceDocumentSync() { if (this._didChangeTextDocumentFeature === undefined) { this._didChangeTextDocumentFeature = this._dynamicFeatures.get(vscode_languageserver_protocol_1.DidChangeTextDocumentNotification.type.method); } this._didChangeTextDocumentFeature.forceDelivery(); } handleDiagnostics(params) { if (!this._diagnostics) { return; } let uri = this._p2c.asUri(params.uri); let diagnostics = this._p2c.asDiagnostics(params.diagnostics); let middleware = this.clientOptions.middleware; if (middleware.handleDiagnostics) { middleware.handleDiagnostics(uri, diagnostics, (uri, diagnostics) => this.setDiagnostics(uri, diagnostics)); } else { this.setDiagnostics(uri, diagnostics); } } setDiagnostics(uri, diagnostics) { if (!this._diagnostics) { return; } this._diagnostics.set(uri, diagnostics); } createConnection() { let errorHandler = (error, message, count) => { this.handleConnectionError(error, message, count); }; let closeHandler = () => { this.handleConnectionClosed(); }; return this.createMessageTransports(this._clientOptions.stdioEncoding || 'utf8').then((transports) => { return createConnection(transports.reader, transports.writer, errorHandler, closeHandler, this._clientOptions.connectionOptions); }); } handleConnectionClosed() { // Check whether this is a normal shutdown in progress or the client stopped normally. if (this.state === ClientState.Stopping || this.state === ClientState.Stopped) { return; } try { if (this._resolvedConnection) { this._resolvedConnection.dispose(); } } catch (error) { // Disposing a connection could fail if error cases. } let action = CloseAction.DoNotRestart; try { action = this._clientOptions.errorHandler.closed(); } catch (error) { // Ignore errors coming from the error handler. } this._connectionPromise = undefined; this._resolvedConnection = undefined; if (action === CloseAction.DoNotRestart) { this.error('Connection to server got closed. Server will not be restarted.'); if (this.state === ClientState.Starting) { this._onReadyCallbacks.reject(new Error(`Connection to server got closed. Server will not be restarted.`)); this.state = ClientState.StartFailed; } else { this.state = ClientState.Stopped; } this.cleanUp(false, true); } else if (action === CloseAction.Restart) { this.info('Connection to server got closed. Server will restart.'); this.cleanUp(false, false); this.state = ClientState.Initial; this.start(); } } handleConnectionError(error, message, count) { let action = this._clientOptions.errorHandler.error(error, message, count); if (action === ErrorAction.Shutdown) { this.error('Connection to server is erroring. Shutting down server.'); this.stop(); } } hookConfigurationChanged(connection) { vscode_1.workspace.onDidChangeConfiguration(() => { this.refreshTrace(connection, true); }); } refreshTrace(connection, sendNotification = false) { let config = vscode_1.workspace.getConfiguration(this._id); let trace = vscode_languageserver_protocol_1.Trace.Off; let traceFormat = vscode_languageserver_protocol_1.TraceFormat.Text; if (config) { const traceConfig = config.get('trace.server', 'off'); if (typeof traceConfig === 'string') { trace = vscode_languageserver_protocol_1.Trace.fromString(traceConfig); } else { trace = vscode_languageserver_protocol_1.Trace.fromString(config.get('trace.server.verbosity', 'off')); traceFormat = vscode_languageserver_protocol_1.TraceFormat.fromString(config.get('trace.server.format', 'text')); } } this._trace = trace; this._traceFormat = traceFormat; connection.trace(this._trace, this._tracer, { sendNotification, traceFormat: this._traceFormat }); } hookFileEvents(_connection) { let fileEvents = this._clientOptions.synchronize.fileEvents; if (!fileEvents) { return; } let watchers; if (Is.array(fileEvents)) { watchers = fileEvents; } else { watchers = [fileEvents]; } if (!watchers) { return; } this._dynamicFeatures.get(vscode_languageserver_protocol_1.DidChangeWatchedFilesNotification.type.method).registerRaw(UUID.generateUuid(), watchers); } registerFeatures(features) { for (let feature of features) { this.registerFeature(feature); } } registerFeature(feature) { this._features.push(feature); if (DynamicFeature.is(feature)) { const registrationType = feature.registrationType; this._dynamicFeatures.set(registrationType.method, feature); } } getFeature(request) { return this._dynamicFeatures.get(request); } registerBuiltinFeatures() { this.registerFeature(new ConfigurationFeature(this)); this.registerFeature(new DidOpenTextDocumentFeature(this, this._syncedDocuments)); this.registerFeature(new DidChangeTextDocumentFeature(this)); this.registerFeature(new WillSaveFeature(this)); this.registerFeature(new WillSaveWaitUntilFeature(this)); this.registerFeature(new DidSaveTextDocumentFeature(this)); this.registerFeature(new DidCloseTextDocumentFeature(this, this._syncedDocuments)); this.registerFeature(new FileSystemWatcherFeature(this, (event) => this.notifyFileEvent(event))); this.registerFeature(new CompletionItemFeature(this)); this.registerFeature(new HoverFeature(this)); this.registerFeature(new SignatureHelpFeature(this)); this.registerFeature(new DefinitionFeature(this)); this.registerFeature(new ReferencesFeature(this)); this.registerFeature(new DocumentHighlightFeature(this)); this.registerFeature(new DocumentSymbolFeature(this)); this.registerFeature(new WorkspaceSymbolFeature(this)); this.registerFeature(new CodeActionFeature(this)); this.registerFeature(new CodeLensFeature(this)); this.registerFeature(new DocumentFormattingFeature(this)); this.registerFeature(new DocumentRangeFormattingFeature(this)); this.registerFeature(new DocumentOnTypeFormattingFeature(this)); this.registerFeature(new RenameFeature(this)); this.registerFeature(new DocumentLinkFeature(this)); this.registerFeature(new ExecuteCommandFeature(this)); } fillInitializeParams(params) { for (let feature of this._features) { if (Is.func(feature.fillInitializeParams)) { feature.fillInitializeParams(params); } } } computeClientCapabilities() { const result = {}; ensure(result, 'workspace').applyEdit = true; const workspaceEdit = ensure(ensure(result, 'workspace'), 'workspaceEdit'); workspaceEdit.documentChanges = true; workspaceEdit.resourceOperations = [vscode_languageserver_protocol_1.ResourceOperationKind.Create, vscode_languageserver_protocol_1.ResourceOperationKind.Rename, vscode_languageserver_protocol_1.ResourceOperationKind.Delete]; workspaceEdit.failureHandling = vscode_languageserver_protocol_1.FailureHandlingKind.TextOnlyTransactional; workspaceEdit.normalizesLineEndings = true; workspaceEdit.changeAnnotationSupport = { groupsOnLabel: true }; const diagnostics = ensure(ensure(result, 'textDocument'), 'publishDiagnostics'); diagnostics.relatedInformation = true; diagnostics.versionSupport = false; diagnostics.tagSupport = { valueSet: [vscode_languageserver_protocol_1.DiagnosticTag.Unnecessary, vscode_languageserver_protocol_1.DiagnosticTag.Deprecated] }; diagnostics.codeDescriptionSupport = true; diagnostics.dataSupport = true; const windowCapabilities = ensure(result, 'window'); const showMessage = ensure(windowCapabilities, 'showMessage'); showMessage.messageActionItem = { additionalPropertiesSupport: true }; const showDocument = ensure(windowCapabilities, 'showDocument'); showDocument.support = true; const generalCapabilities = ensure(result, 'general'); generalCapabilities.regularExpressions = { engine: 'ECMAScript', version: 'ES2020' }; generalCapabilities.markdown = { parser: 'marked', version: '1.1.0' }; for (let feature of this._features) { feature.fillClientCapabilities(result); } return result; } initializeFeatures(_connection) { let documentSelector = this._clientOptions.documentSelector; for (let feature of this._features) { feature.initialize(this._capabilities, documentSelector); } } handleRegistrationRequest(params) { return new Promise((resolve, reject) => { for (const registration of params.registrations) { const feature = this._dynamicFeatures.get(registration.method); if (feature === undefined) { reject(new Error(`No feature implementation for ${registration.method} found. Registration failed.`)); return; } const options = registration.registerOptions || {}; options.documentSelector = options.documentSelector || this._clientOptions.documentSelector; const data = { id: registration.id, registerOptions: options }; try { feature.register(data); } catch (err) { reject(err); return; } } resolve(); }); } handleUnregistrationRequest(params) { return new Promise((resolve, reject) => { for (let unregistration of params.unregisterations) { const feature = this._dynamicFeatures.get(unregistration.method); if (!feature) { reject(new Error(`No feature implementation for ${unregistration.method} found. Unregistration failed.`)); return; } feature.unregister(unregistration.id); } resolve(); }); } handleApplyWorkspaceEdit(params) { // This is some sort of workaround since the version check should be done by VS Code in the Workspace.applyEdit. // However doing it here adds some safety since the server can lag more behind then an extension. let workspaceEdit = params.edit; let openTextDocuments = new Map(); vscode_1.workspace.textDocuments.forEach((document) => openTextDocuments.set(document.uri.toString(), document)); let versionMismatch = false; if (workspaceEdit.documentChanges) { for (const change of workspaceEdit.documentChanges) { if (vscode_languageserver_protocol_1.TextDocumentEdit.is(change) && change.textDocument.version && change.textDocument.version >= 0) { let textDocument = openTextDocuments.get(change.textDocument.uri); if (textDocument && textDocument.version !== change.textDocument.version) { versionMismatch = true; break; } } } } if (versionMismatch) { return Promise.resolve({ applied: false }); } return Is.asPromise(vscode_1.workspace.applyEdit(this._p2c.asWorkspaceEdit(params.edit)).then((value) => { return { applied: value }; })); } handleFailedRequest(type, error, defaultValue) { // If we get a request cancel or a content modified don't log anything. if (error instanceof vscode_languageserver_protocol_1.ResponseError) { if (error.code === vscode_languageserver_protocol_1.LSPErrorCodes.RequestCancelled) { throw this.makeCancelError(); } else if (error.code === vscode_languageserver_protocol_1.LSPErrorCodes.ContentModified) { return defaultValue; } } this.error(`Request ${type.method} failed.`, error); throw error; } makeCancelError() { const result = new Error(BaseLanguageClient.Canceled); result.name = BaseLanguageClient.Canceled; return result; } } exports.BaseLanguageClient = BaseLanguageClient; BaseLanguageClient.Canceled = 'Canceled'; //# sourceMappingURL=client.js.map /***/ }), /***/ 71: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createConverter = void 0; const code = __webpack_require__(9496); const proto = __webpack_require__(273); const Is = __webpack_require__(9763); const protocolCompletionItem_1 = __webpack_require__(1807); const protocolCodeLens_1 = __webpack_require__(583); const protocolDocumentLink_1 = __webpack_require__(8705); const protocolCodeAction_1 = __webpack_require__(6434); const protocolDiagnostic_1 = __webpack_require__(6640); const protocolCallHierarchyItem_1 = __webpack_require__(8714); const vscode_languageserver_protocol_1 = __webpack_require__(273); var InsertReplaceRange; (function (InsertReplaceRange) { function is(value) { const candidate = value; return candidate && !!candidate.inserting && !!candidate.replacing; } InsertReplaceRange.is = is; })(InsertReplaceRange || (InsertReplaceRange = {})); function createConverter(uriConverter) { const nullConverter = (value) => value.toString(); const _uriConverter = uriConverter || nullConverter; function asUri(value) { return _uriConverter(value); } function asTextDocumentIdentifier(textDocument) { return { uri: _uriConverter(textDocument.uri) }; } function asVersionedTextDocumentIdentifier(textDocument) { return { uri: _uriConverter(textDocument.uri), version: textDocument.version }; } function asOpenTextDocumentParams(textDocument) { return { textDocument: { uri: _uriConverter(textDocument.uri), languageId: textDocument.languageId, version: textDocument.version, text: textDocument.getText() } }; } function isTextDocumentChangeEvent(value) { let candidate = value; return !!candidate.document && !!candidate.contentChanges; } function isTextDocument(value) { let candidate = value; return !!candidate.uri && !!candidate.version; } function asChangeTextDocumentParams(arg) { if (isTextDocument(arg)) { let result = { textDocument: { uri: _uriConverter(arg.uri), version: arg.version }, contentChanges: [{ text: arg.getText() }] }; return result; } else if (isTextDocumentChangeEvent(arg)) { let document = arg.document; let result = { textDocument: { uri: _uriConverter(document.uri), version: document.version }, contentChanges: arg.contentChanges.map((change) => { let range = change.range; return { range: { start: { line: range.start.line, character: range.start.character }, end: { line: range.end.line, character: range.end.character } }, rangeLength: change.rangeLength, text: change.text }; }) }; return result; } else { throw Error('Unsupported text document change parameter'); } } function asCloseTextDocumentParams(textDocument) { return { textDocument: asTextDocumentIdentifier(textDocument) }; } function asSaveTextDocumentParams(textDocument, includeContent = false) { let result = { textDocument: asTextDocumentIdentifier(textDocument) }; if (includeContent) { result.text = textDocument.getText(); } return result; } function asTextDocumentSaveReason(reason) { switch (reason) { case code.TextDocumentSaveReason.Manual: return proto.TextDocumentSaveReason.Manual; case code.TextDocumentSaveReason.AfterDelay: return proto.TextDocumentSaveReason.AfterDelay; case code.TextDocumentSaveReason.FocusOut: return proto.TextDocumentSaveReason.FocusOut; } return proto.TextDocumentSaveReason.Manual; } function asWillSaveTextDocumentParams(event) { return { textDocument: asTextDocumentIdentifier(event.document), reason: asTextDocumentSaveReason(event.reason) }; } function asDidCreateFilesParams(event) { return { files: event.files.map((fileUri) => ({ uri: _uriConverter(fileUri), })), }; } function asDidRenameFilesParams(event) { return { files: event.files.map((file) => ({ oldUri: _uriConverter(file.oldUri), newUri: _uriConverter(file.newUri), })), }; } function asDidDeleteFilesParams(event) { return { files: event.files.map((fileUri) => ({ uri: _uriConverter(fileUri), })), }; } function asWillCreateFilesParams(event) { return { files: event.files.map((fileUri) => ({ uri: _uriConverter(fileUri), })), }; } function asWillRenameFilesParams(event) { return { files: event.files.map((file) => ({ oldUri: _uriConverter(file.oldUri), newUri: _uriConverter(file.newUri), })), }; } function asWillDeleteFilesParams(event) { return { files: event.files.map((fileUri) => ({ uri: _uriConverter(fileUri), })), }; } function asTextDocumentPositionParams(textDocument, position) { return { textDocument: asTextDocumentIdentifier(textDocument), position: asWorkerPosition(position) }; } function asCompletionTriggerKind(triggerKind) { switch (triggerKind) { case code.CompletionTriggerKind.TriggerCharacter: return proto.CompletionTriggerKind.TriggerCharacter; case code.CompletionTriggerKind.TriggerForIncompleteCompletions: return proto.CompletionTriggerKind.TriggerForIncompleteCompletions; default: return proto.CompletionTriggerKind.Invoked; } } function asCompletionParams(textDocument, position, context) { return { textDocument: asTextDocumentIdentifier(textDocument), position: asWorkerPosition(position), context: { triggerKind: asCompletionTriggerKind(context.triggerKind), triggerCharacter: context.triggerCharacter } }; } function asSignatureHelpTriggerKind(triggerKind) { switch (triggerKind) { case code.SignatureHelpTriggerKind.Invoke: return proto.SignatureHelpTriggerKind.Invoked; case code.SignatureHelpTriggerKind.TriggerCharacter: return proto.SignatureHelpTriggerKind.TriggerCharacter; case code.SignatureHelpTriggerKind.ContentChange: return proto.SignatureHelpTriggerKind.ContentChange; } } function asParameterInformation(value) { // We leave the documentation out on purpose since it usually adds no // value for the server. return { label: value.label }; } function asParameterInformations(values) { return values.map(asParameterInformation); } function asSignatureInformation(value) { // We leave the documentation out on purpose since it usually adds no // value for the server. return { label: value.label, parameters: asParameterInformations(value.parameters) }; } function asSignatureInformations(values) { return values.map(asSignatureInformation); } function asSignatureHelp(value) { if (value === undefined) { return value; } return { signatures: asSignatureInformations(value.signatures), activeSignature: value.activeSignature, activeParameter: value.activeParameter }; } function asSignatureHelpParams(textDocument, position, context) { return { textDocument: asTextDocumentIdentifier(textDocument), position: asWorkerPosition(position), context: { isRetrigger: context.isRetrigger, triggerCharacter: context.triggerCharacter, triggerKind: asSignatureHelpTriggerKind(context.triggerKind), activeSignatureHelp: asSignatureHelp(context.activeSignatureHelp) } }; } function asWorkerPosition(position) { return { line: position.line, character: position.character }; } function asPosition(value) { if (value === undefined || value === null) { return value; } return { line: value.line, character: value.character }; } function asPositions(value) { let result = []; for (let elem of value) { result.push(asPosition(elem)); } return result; } function asRange(value) { if (value === undefined || value === null) { return value; } return { start: asPosition(value.start), end: asPosition(value.end) }; } function asLocation(value) { if (value === undefined || value === null) { return value; } return proto.Location.create(asUri(value.uri), asRange(value.range)); } function asDiagnosticSeverity(value) { switch (value) { case code.DiagnosticSeverity.Error: return proto.DiagnosticSeverity.Error; case code.DiagnosticSeverity.Warning: return proto.DiagnosticSeverity.Warning; case code.DiagnosticSeverity.Information: return proto.DiagnosticSeverity.Information; case code.DiagnosticSeverity.Hint: return proto.DiagnosticSeverity.Hint; } } function asDiagnosticTags(tags) { if (!tags) { return undefined; } let result = []; for (let tag of tags) { let converted = asDiagnosticTag(tag); if (converted !== undefined) { result.push(converted); } } return result.length > 0 ? result : undefined; } function asDiagnosticTag(tag) { switch (tag) { case code.DiagnosticTag.Unnecessary: return proto.DiagnosticTag.Unnecessary; case code.DiagnosticTag.Deprecated: return proto.DiagnosticTag.Deprecated; default: return undefined; } } function asRelatedInformation(item) { return { message: item.message, location: asLocation(item.location) }; } function asRelatedInformations(items) { return items.map(asRelatedInformation); } function asDiagnosticCode(value) { if (value === undefined || value === null) { return undefined; } if (Is.number(value) || Is.string(value)) { return value; } return { value: value.value, target: asUri(value.target) }; } function asDiagnostic(item) { const result = proto.Diagnostic.create(asRange(item.range), item.message); const protocolDiagnostic = item instanceof protocolDiagnostic_1.ProtocolDiagnostic ? item : undefined; if (protocolDiagnostic !== undefined && protocolDiagnostic.data !== undefined) { result.data = protocolDiagnostic.data; } const code = asDiagnosticCode(item.code); if (protocolDiagnostic_1.DiagnosticCode.is(code)) { if (protocolDiagnostic !== undefined && protocolDiagnostic.hasDiagnosticCode) { result.code = code; } else { result.code = code.value; result.codeDescription = { href: code.target }; } } else { result.code = code; } if (Is.number(item.severity)) { result.severity = asDiagnosticSeverity(item.severity); } if (Array.isArray(item.tags)) { result.tags = asDiagnosticTags(item.tags); } if (item.relatedInformation) { result.relatedInformation = asRelatedInformations(item.relatedInformation); } if (item.source) { result.source = item.source; } return result; } function asDiagnostics(items) { if (items === undefined || items === null) { return items; } return items.map(asDiagnostic); } function asDocumentation(format, documentation) { switch (format) { case '$string': return documentation; case proto.MarkupKind.PlainText: return { kind: format, value: documentation }; case proto.MarkupKind.Markdown: return { kind: format, value: documentation.value }; default: return `Unsupported Markup content received. Kind is: ${format}`; } } function asCompletionItemTag(tag) { switch (tag) { case code.CompletionItemTag.Deprecated: return proto.CompletionItemTag.Deprecated; } return undefined; } function asCompletionItemTags(tags) { if (tags === undefined) { return tags; } const result = []; for (let tag of tags) { const converted = asCompletionItemTag(tag); if (converted !== undefined) { result.push(converted); } } return result; } function asCompletionItemKind(value, original) { if (original !== undefined) { return original; } return value + 1; } function asCompletionItem(item) { let result = { label: item.label }; let protocolItem = item instanceof protocolCompletionItem_1.default ? item : undefined; if (item.detail) { result.detail = item.detail; } // We only send items back we created. So this can't be something else than // a string right now. if (item.documentation) { if (!protocolItem || protocolItem.documentationFormat === '$string') { result.documentation = item.documentation; } else { result.documentation = asDocumentation(protocolItem.documentationFormat, item.documentation); } } if (item.filterText) { result.filterText = item.filterText; } fillPrimaryInsertText(result, item); if (Is.number(item.kind)) { result.kind = asCompletionItemKind(item.kind, protocolItem && protocolItem.originalItemKind); } if (item.sortText) { result.sortText = item.sortText; } if (item.additionalTextEdits) { result.additionalTextEdits = asTextEdits(item.additionalTextEdits); } if (item.commitCharacters) { result.commitCharacters = item.commitCharacters.slice(); } if (item.command) { result.command = asCommand(item.command); } if (item.preselect === true || item.preselect === false) { result.preselect = item.preselect; } const tags = asCompletionItemTags(item.tags); if (protocolItem) { if (protocolItem.data !== undefined) { result.data = protocolItem.data; } if (protocolItem.deprecated === true || protocolItem.deprecated === false) { if (protocolItem.deprecated === true && tags !== undefined && tags.length > 0) { const index = tags.indexOf(code.CompletionItemTag.Deprecated); if (index !== -1) { tags.splice(index, 1); } } result.deprecated = protocolItem.deprecated; } if (protocolItem.insertTextMode !== undefined) { result.insertTextMode = protocolItem.insertTextMode; } } if (tags !== undefined && tags.length > 0) { result.tags = tags; } if (result.insertTextMode === undefined && item.keepWhitespace === true) { result.insertTextMode = vscode_languageserver_protocol_1.InsertTextMode.adjustIndentation; } return result; } function fillPrimaryInsertText(target, source) { let format = proto.InsertTextFormat.PlainText; let text = undefined; let range = undefined; if (source.textEdit) { text = source.textEdit.newText; range = source.textEdit.range; } else if (source.insertText instanceof code.SnippetString) { format = proto.InsertTextFormat.Snippet; text = source.insertText.value; } else { text = source.insertText; } if (source.range) { range = source.range; } target.insertTextFormat = format; if (source.fromEdit && text !== undefined && range !== undefined) { target.textEdit = asCompletionTextEdit(text, range); } else { target.insertText = text; } } function asCompletionTextEdit(newText, range) { if (InsertReplaceRange.is(range)) { return proto.InsertReplaceEdit.create(newText, asRange(range.inserting), asRange(range.replacing)); } else { return { newText, range: asRange(range) }; } } function asTextEdit(edit) { return { range: asRange(edit.range), newText: edit.newText }; } function asTextEdits(edits) { if (edits === undefined || edits === null) { return edits; } return edits.map(asTextEdit); } function asSymbolKind(item) { if (item <= code.SymbolKind.TypeParameter) { // Symbol kind is one based in the protocol and zero based in code. return (item + 1); } return proto.SymbolKind.Property; } function asSymbolTag(item) { return item; } function asSymbolTags(items) { return items.map(asSymbolTag); } function asReferenceParams(textDocument, position, options) { return { textDocument: asTextDocumentIdentifier(textDocument), position: asWorkerPosition(position), context: { includeDeclaration: options.includeDeclaration } }; } function asCodeAction(item) { let result = proto.CodeAction.create(item.title); if (item instanceof protocolCodeAction_1.default && item.data !== undefined) { result.data = item.data; } if (item.kind !== undefined) { result.kind = asCodeActionKind(item.kind); } if (item.diagnostics !== undefined) { result.diagnostics = asDiagnostics(item.diagnostics); } if (item.edit !== undefined) { throw new Error(`VS Code code actions can only be converted to a protocol code action without an edit.`); } if (item.command !== undefined) { result.command = asCommand(item.command); } if (item.isPreferred !== undefined) { result.isPreferred = item.isPreferred; } if (item.disabled !== undefined) { result.disabled = { reason: item.disabled.reason }; } return result; } function asCodeActionContext(context) { if (context === undefined || context === null) { return context; } let only; if (context.only && Is.string(context.only.value)) { only = [context.only.value]; } return proto.CodeActionContext.create(asDiagnostics(context.diagnostics), only); } function asCodeActionKind(item) { if (item === undefined || item === null) { return undefined; } return item.value; } function asCommand(item) { let result = proto.Command.create(item.title, item.command); if (item.arguments) { result.arguments = item.arguments; } return result; } function asCodeLens(item) { let result = proto.CodeLens.create(asRange(item.range)); if (item.command) { result.command = asCommand(item.command); } if (item instanceof protocolCodeLens_1.default) { if (item.data) { result.data = item.data; } } return result; } function asFormattingOptions(options, fileOptions) { const result = { tabSize: options.tabSize, insertSpaces: options.insertSpaces }; if (fileOptions.trimTrailingWhitespace) { result.trimTrailingWhitespace = true; } if (fileOptions.trimFinalNewlines) { result.trimFinalNewlines = true; } if (fileOptions.insertFinalNewline) { result.insertFinalNewline = true; } return result; } function asDocumentSymbolParams(textDocument) { return { textDocument: asTextDocumentIdentifier(textDocument) }; } function asCodeLensParams(textDocument) { return { textDocument: asTextDocumentIdentifier(textDocument) }; } function asDocumentLink(item) { let result = proto.DocumentLink.create(asRange(item.range)); if (item.target) { result.target = asUri(item.target); } if (item.tooltip !== undefined) { result.tooltip = item.tooltip; } let protocolItem = item instanceof protocolDocumentLink_1.default ? item : undefined; if (protocolItem && protocolItem.data) { result.data = protocolItem.data; } return result; } function asDocumentLinkParams(textDocument) { return { textDocument: asTextDocumentIdentifier(textDocument) }; } function asCallHierarchyItem(value) { const result = { name: value.name, kind: asSymbolKind(value.kind), uri: asUri(value.uri), range: asRange(value.range), selectionRange: asRange(value.selectionRange) }; if (value.detail !== undefined && value.detail.length > 0) { result.detail = value.detail; } if (value.tags !== undefined) { result.tags = asSymbolTags(value.tags); } if (value instanceof protocolCallHierarchyItem_1.default && value.data !== undefined) { result.data = value.data; } return result; } return { asUri, asTextDocumentIdentifier, asVersionedTextDocumentIdentifier, asOpenTextDocumentParams, asChangeTextDocumentParams, asCloseTextDocumentParams, asSaveTextDocumentParams, asWillSaveTextDocumentParams, asDidCreateFilesParams, asDidRenameFilesParams, asDidDeleteFilesParams, asWillCreateFilesParams, asWillRenameFilesParams, asWillDeleteFilesParams, asTextDocumentPositionParams, asCompletionParams, asSignatureHelpParams, asWorkerPosition, asRange, asPosition, asPositions, asLocation, asDiagnosticSeverity, asDiagnosticTag, asDiagnostic, asDiagnostics, asCompletionItem, asTextEdit, asSymbolKind, asSymbolTag, asSymbolTags, asReferenceParams, asCodeAction, asCodeActionContext, asCommand, asCodeLens, asFormattingOptions, asDocumentSymbolParams, asCodeLensParams, asDocumentLink, asDocumentLinkParams, asCallHierarchyItem }; } exports.createConverter = createConverter; //# sourceMappingURL=codeConverter.js.map /***/ }), /***/ 3069: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ColorProviderFeature = void 0; const vscode_1 = __webpack_require__(9496); const vscode_languageserver_protocol_1 = __webpack_require__(273); const client_1 = __webpack_require__(4384); function ensure(target, key) { if (target[key] === void 0) { target[key] = {}; } return target[key]; } class ColorProviderFeature extends client_1.TextDocumentFeature { constructor(client) { super(client, vscode_languageserver_protocol_1.DocumentColorRequest.type); } fillClientCapabilities(capabilities) { ensure(ensure(capabilities, 'textDocument'), 'colorProvider').dynamicRegistration = true; } initialize(capabilities, documentSelector) { let [id, options] = this.getRegistration(documentSelector, capabilities.colorProvider); if (!id || !options) { return; } this.register({ id: id, registerOptions: options }); } registerLanguageProvider(options) { const provider = { provideColorPresentations: (color, context, token) => { const client = this._client; const provideColorPresentations = (color, context, token) => { const requestParams = { color, textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(context.document), range: client.code2ProtocolConverter.asRange(context.range) }; return client.sendRequest(vscode_languageserver_protocol_1.ColorPresentationRequest.type, requestParams, token).then(this.asColorPresentations.bind(this), (error) => { return client.handleFailedRequest(vscode_languageserver_protocol_1.ColorPresentationRequest.type, error, null); }); }; const middleware = client.clientOptions.middleware; return middleware.provideColorPresentations ? middleware.provideColorPresentations(color, context, token, provideColorPresentations) : provideColorPresentations(color, context, token); }, provideDocumentColors: (document, token) => { const client = this._client; const provideDocumentColors = (document, token) => { const requestParams = { textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document) }; return client.sendRequest(vscode_languageserver_protocol_1.DocumentColorRequest.type, requestParams, token).then(this.asColorInformations.bind(this), (error) => { return client.handleFailedRequest(vscode_languageserver_protocol_1.ColorPresentationRequest.type, error, null); }); }; const middleware = client.clientOptions.middleware; return middleware.provideDocumentColors ? middleware.provideDocumentColors(document, token, provideDocumentColors) : provideDocumentColors(document, token); } }; return [vscode_1.languages.registerColorProvider(options.documentSelector, provider), provider]; } asColor(color) { return new vscode_1.Color(color.red, color.green, color.blue, color.alpha); } asColorInformations(colorInformation) { if (Array.isArray(colorInformation)) { return colorInformation.map(ci => { return new vscode_1.ColorInformation(this._client.protocol2CodeConverter.asRange(ci.range), this.asColor(ci.color)); }); } return []; } asColorPresentations(colorPresentations) { if (Array.isArray(colorPresentations)) { return colorPresentations.map(cp => { let presentation = new vscode_1.ColorPresentation(cp.label); presentation.additionalTextEdits = this._client.protocol2CodeConverter.asTextEdits(cp.additionalTextEdits); presentation.textEdit = this._client.protocol2CodeConverter.asTextEdit(cp.textEdit); return presentation; }); } return []; } } exports.ColorProviderFeature = ColorProviderFeature; //# sourceMappingURL=colorProvider.js.map /***/ }), /***/ 7225: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ProposedFeatures = exports.CommonLanguageClient = void 0; const client_1 = __webpack_require__(4384); const colorProvider_1 = __webpack_require__(3069); const configuration_1 = __webpack_require__(6495); const implementation_1 = __webpack_require__(9889); const typeDefinition_1 = __webpack_require__(328); const workspaceFolders_1 = __webpack_require__(9565); const foldingRange_1 = __webpack_require__(6454); const declaration_1 = __webpack_require__(707); const selectionRange_1 = __webpack_require__(750); const progress_1 = __webpack_require__(3603); const callHierarchy_1 = __webpack_require__(5578); const semanticTokens_1 = __webpack_require__(9957); const fileOperations_1 = __webpack_require__(8406); const linkedEditingRange_1 = __webpack_require__(3483); class CommonLanguageClient extends client_1.BaseLanguageClient { constructor(id, name, clientOptions) { super(id, name, clientOptions); } registerProposedFeatures() { this.registerFeatures(ProposedFeatures.createAll(this)); } registerBuiltinFeatures() { super.registerBuiltinFeatures(); this.registerFeature(new configuration_1.ConfigurationFeature(this)); this.registerFeature(new typeDefinition_1.TypeDefinitionFeature(this)); this.registerFeature(new implementation_1.ImplementationFeature(this)); this.registerFeature(new colorProvider_1.ColorProviderFeature(this)); this.registerFeature(new workspaceFolders_1.WorkspaceFoldersFeature(this)); this.registerFeature(new foldingRange_1.FoldingRangeFeature(this)); this.registerFeature(new declaration_1.DeclarationFeature(this)); this.registerFeature(new selectionRange_1.SelectionRangeFeature(this)); this.registerFeature(new progress_1.ProgressFeature(this)); this.registerFeature(new callHierarchy_1.CallHierarchyFeature(this)); this.registerFeature(new semanticTokens_1.SemanticTokensFeature(this)); this.registerFeature(new linkedEditingRange_1.LinkedEditingFeature(this)); this.registerFeature(new fileOperations_1.DidCreateFilesFeature(this)); this.registerFeature(new fileOperations_1.DidRenameFilesFeature(this)); this.registerFeature(new fileOperations_1.DidDeleteFilesFeature(this)); this.registerFeature(new fileOperations_1.WillCreateFilesFeature(this)); this.registerFeature(new fileOperations_1.WillRenameFilesFeature(this)); this.registerFeature(new fileOperations_1.WillDeleteFilesFeature(this)); } } exports.CommonLanguageClient = CommonLanguageClient; // Exporting proposed protocol. var ProposedFeatures; (function (ProposedFeatures) { function createAll(_client) { let result = []; return result; } ProposedFeatures.createAll = createAll; })(ProposedFeatures = exports.ProposedFeatures || (exports.ProposedFeatures = {})); //# sourceMappingURL=commonClient.js.map /***/ }), /***/ 6495: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.toJSONObject = exports.ConfigurationFeature = void 0; const vscode_1 = __webpack_require__(9496); const vscode_languageserver_protocol_1 = __webpack_require__(273); class ConfigurationFeature { constructor(_client) { this._client = _client; } fillClientCapabilities(capabilities) { capabilities.workspace = capabilities.workspace || {}; capabilities.workspace.configuration = true; } initialize() { let client = this._client; client.onRequest(vscode_languageserver_protocol_1.ConfigurationRequest.type, (params, token) => { let configuration = (params) => { let result = []; for (let item of params.items) { let resource = item.scopeUri !== void 0 && item.scopeUri !== null ? this._client.protocol2CodeConverter.asUri(item.scopeUri) : undefined; result.push(this.getConfiguration(resource, item.section !== null ? item.section : undefined)); } return result; }; let middleware = client.clientOptions.middleware.workspace; return middleware && middleware.configuration ? middleware.configuration(params, token, configuration) : configuration(params, token); }); } getConfiguration(resource, section) { let result = null; if (section) { let index = section.lastIndexOf('.'); if (index === -1) { result = toJSONObject(vscode_1.workspace.getConfiguration(undefined, resource).get(section)); } else { let config = vscode_1.workspace.getConfiguration(section.substr(0, index), resource); if (config) { result = toJSONObject(config.get(section.substr(index + 1))); } } } else { let config = vscode_1.workspace.getConfiguration(undefined, resource); result = {}; for (let key of Object.keys(config)) { if (config.has(key)) { result[key] = toJSONObject(config.get(key)); } } } if (result === undefined) { result = null; } return result; } dispose() { } } exports.ConfigurationFeature = ConfigurationFeature; function toJSONObject(obj) { if (obj) { if (Array.isArray(obj)) { return obj.map(toJSONObject); } else if (typeof obj === 'object') { const res = Object.create(null); for (const key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { res[key] = toJSONObject(obj[key]); } } return res; } } return obj; } exports.toJSONObject = toJSONObject; //# sourceMappingURL=configuration.js.map /***/ }), /***/ 707: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DeclarationFeature = void 0; const vscode_1 = __webpack_require__(9496); const vscode_languageserver_protocol_1 = __webpack_require__(273); const client_1 = __webpack_require__(4384); function ensure(target, key) { if (target[key] === void 0) { target[key] = {}; } return target[key]; } class DeclarationFeature extends client_1.TextDocumentFeature { constructor(client) { super(client, vscode_languageserver_protocol_1.DeclarationRequest.type); } fillClientCapabilities(capabilities) { const declarationSupport = ensure(ensure(capabilities, 'textDocument'), 'declaration'); declarationSupport.dynamicRegistration = true; declarationSupport.linkSupport = true; } initialize(capabilities, documentSelector) { const [id, options] = this.getRegistration(documentSelector, capabilities.declarationProvider); if (!id || !options) { return; } this.register({ id: id, registerOptions: options }); } registerLanguageProvider(options) { const provider = { provideDeclaration: (document, position, token) => { const client = this._client; const provideDeclaration = (document, position, token) => { return client.sendRequest(vscode_languageserver_protocol_1.DeclarationRequest.type, client.code2ProtocolConverter.asTextDocumentPositionParams(document, position), token).then(client.protocol2CodeConverter.asDeclarationResult, (error) => { return client.handleFailedRequest(vscode_languageserver_protocol_1.DeclarationRequest.type, error, null); }); }; const middleware = client.clientOptions.middleware; return middleware.provideDeclaration ? middleware.provideDeclaration(document, position, token, provideDeclaration) : provideDeclaration(document, position, token); } }; return [vscode_1.languages.registerDeclarationProvider(options.documentSelector, provider), provider]; } } exports.DeclarationFeature = DeclarationFeature; //# sourceMappingURL=declaration.js.map /***/ }), /***/ 8406: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.WillDeleteFilesFeature = exports.WillRenameFilesFeature = exports.WillCreateFilesFeature = exports.DidDeleteFilesFeature = exports.DidRenameFilesFeature = exports.DidCreateFilesFeature = void 0; const code = __webpack_require__(9496); const minimatch = __webpack_require__(1171); const proto = __webpack_require__(273); const UUID = __webpack_require__(1980); function ensure(target, key) { if (target[key] === void 0) { target[key] = {}; } return target[key]; } function access(target, key) { return target[key]; } function assign(target, key, value) { target[key] = value; } class FileOperationFeature { constructor(client, event, registrationType, clientCapability, serverCapability) { this._filters = new Map(); this._client = client; this._event = event; this._registrationType = registrationType; this._clientCapability = clientCapability; this._serverCapability = serverCapability; } get registrationType() { return this._registrationType; } fillClientCapabilities(capabilities) { const value = ensure(ensure(capabilities, 'workspace'), 'fileOperations'); // this happens n times but it is the same value so we tolerate this. assign(value, 'dynamicRegistration', true); assign(value, this._clientCapability, true); } initialize(capabilities) { var _a; const options = (_a = capabilities.workspace) === null || _a === void 0 ? void 0 : _a.fileOperations; const capability = options !== undefined ? access(options, this._serverCapability) : undefined; if ((capability === null || capability === void 0 ? void 0 : capability.filters) !== undefined) { try { this.register({ id: UUID.generateUuid(), registerOptions: { filters: capability.filters } }); } catch (e) { this._client.warn(`Ignoring invalid glob pattern for ${this._serverCapability} registration: ${e}`); } } } register(data) { if (!this._listener) { this._listener = this._event(this.send, this); } const minimatchFilter = data.registerOptions.filters.map((filter) => { const matcher = new minimatch.Minimatch(filter.pattern.glob, FileOperationFeature.asMinimatchOptions(filter.pattern.options)); if (!matcher.makeRe()) { throw new Error(`Invalid pattern ${filter.pattern.glob}!`); } return { scheme: filter.scheme, matcher, kind: filter.pattern.matches }; }); this._filters.set(data.id, minimatchFilter); } unregister(id) { this._filters.delete(id); if (this._filters.size === 0 && this._listener) { this._listener.dispose(); this._listener = undefined; } } dispose() { this._filters.clear(); if (this._listener) { this._listener.dispose(); this._listener = undefined; } } async filter(event, prop) { // (Asynchronously) map each file onto a boolean of whether it matches // any of the globs. const fileMatches = await Promise.all(event.files.map(async (item) => { const uri = prop(item); // Use fsPath to make this consistent with file system watchers but help // minimatch to use '/' instead of `\\` if present. const path = uri.fsPath.replace(/\\/g, '/'); for (const filters of this._filters.values()) { for (const filter of filters) { if (filter.scheme !== undefined && filter.scheme !== uri.scheme) { continue; } if (filter.matcher.match(path)) { // The pattern matches. If kind is undefined then everything is ok if (filter.kind === undefined) { return true; } const fileType = await FileOperationFeature.getFileType(uri); // If we can't determine the file type than we treat it as a match. // Dropping it would be another alternative. if (fileType === undefined) { this._client.error(`Failed to determine file type for ${uri.toString()}.`); return true; } if ((fileType === code.FileType.File && filter.kind === proto.FileOperationPatternKind.file) || (fileType === code.FileType.Directory && filter.kind === proto.FileOperationPatternKind.folder)) { return true; } } else if (filter.kind === proto.FileOperationPatternKind.folder) { const fileType = await FileOperationFeature.getFileType(uri); if (fileType === code.FileType.Directory && filter.matcher.match(`${path}/`)) { return true; } } } } return false; })); // Filter the files to those that matched. const files = event.files.filter((_, index) => fileMatches[index]); return Object.assign(Object.assign({}, event), { files }); } static async getFileType(uri) { try { return (await code.workspace.fs.stat(uri)).type; } catch (e) { return undefined; } } static asMinimatchOptions(options) { if (options === undefined) { return undefined; } if (options.ignoreCase === true) { return { nocase: true }; } return undefined; } } class NotificationFileOperationFeature extends FileOperationFeature { constructor(client, event, notificationType, clientCapability, serverCapability, accessUri, createParams) { super(client, event, notificationType, clientCapability, serverCapability); this._notificationType = notificationType; this._accessUri = accessUri; this._createParams = createParams; } async send(originalEvent) { // Create a copy of the event that has the files filtered to match what the // server wants. const filteredEvent = await this.filter(originalEvent, this._accessUri); if (filteredEvent.files.length) { const next = async (event) => { this._client.sendNotification(this._notificationType, this._createParams(event)); }; this.doSend(filteredEvent, next); } } } class DidCreateFilesFeature extends NotificationFileOperationFeature { constructor(client) { super(client, code.workspace.onDidCreateFiles, proto.DidCreateFilesNotification.type, 'didCreate', 'didCreate', (i) => i, client.code2ProtocolConverter.asDidCreateFilesParams); } doSend(event, next) { var _a; const middleware = (_a = this._client.clientOptions.middleware) === null || _a === void 0 ? void 0 : _a.workspace; return (middleware === null || middleware === void 0 ? void 0 : middleware.didCreateFiles) ? middleware.didCreateFiles(event, next) : next(event); } } exports.DidCreateFilesFeature = DidCreateFilesFeature; class DidRenameFilesFeature extends NotificationFileOperationFeature { constructor(client) { super(client, code.workspace.onDidRenameFiles, proto.DidRenameFilesNotification.type, 'didRename', 'didRename', (i) => i.oldUri, client.code2ProtocolConverter.asDidRenameFilesParams); } doSend(event, next) { var _a; const middleware = (_a = this._client.clientOptions.middleware) === null || _a === void 0 ? void 0 : _a.workspace; return (middleware === null || middleware === void 0 ? void 0 : middleware.didRenameFiles) ? middleware.didRenameFiles(event, next) : next(event); } } exports.DidRenameFilesFeature = DidRenameFilesFeature; class DidDeleteFilesFeature extends NotificationFileOperationFeature { constructor(client) { super(client, code.workspace.onDidDeleteFiles, proto.DidDeleteFilesNotification.type, 'didDelete', 'didDelete', (i) => i, client.code2ProtocolConverter.asDidDeleteFilesParams); } doSend(event, next) { var _a; const middleware = (_a = this._client.clientOptions.middleware) === null || _a === void 0 ? void 0 : _a.workspace; return (middleware === null || middleware === void 0 ? void 0 : middleware.didDeleteFiles) ? middleware.didDeleteFiles(event, next) : next(event); } } exports.DidDeleteFilesFeature = DidDeleteFilesFeature; class RequestFileOperationFeature extends FileOperationFeature { constructor(client, event, requestType, clientCapability, serverCapability, accessUri, createParams) { super(client, event, requestType, clientCapability, serverCapability); this._requestType = requestType; this._accessUri = accessUri; this._createParams = createParams; } async send(originalEvent) { const waitUntil = this.waitUntil(originalEvent); originalEvent.waitUntil(waitUntil); } async waitUntil(originalEvent) { // Create a copy of the event that has the files filtered to match what the // server wants. const filteredEvent = await this.filter(originalEvent, this._accessUri); if (filteredEvent.files.length) { const next = (event) => { return this._client.sendRequest(this._requestType, this._createParams(event)) .then(this._client.protocol2CodeConverter.asWorkspaceEdit); }; return this.doSend(filteredEvent, next); } else { return undefined; } } } class WillCreateFilesFeature extends RequestFileOperationFeature { constructor(client) { super(client, code.workspace.onWillCreateFiles, proto.WillCreateFilesRequest.type, 'willCreate', 'willCreate', (i) => i, client.code2ProtocolConverter.asWillCreateFilesParams); } doSend(event, next) { var _a; const middleware = (_a = this._client.clientOptions.middleware) === null || _a === void 0 ? void 0 : _a.workspace; return (middleware === null || middleware === void 0 ? void 0 : middleware.willCreateFiles) ? middleware.willCreateFiles(event, next) : next(event); } } exports.WillCreateFilesFeature = WillCreateFilesFeature; class WillRenameFilesFeature extends RequestFileOperationFeature { constructor(client) { super(client, code.workspace.onWillRenameFiles, proto.WillRenameFilesRequest.type, 'willRename', 'willRename', (i) => i.oldUri, client.code2ProtocolConverter.asWillRenameFilesParams); } doSend(event, next) { var _a; const middleware = (_a = this._client.clientOptions.middleware) === null || _a === void 0 ? void 0 : _a.workspace; return (middleware === null || middleware === void 0 ? void 0 : middleware.willRenameFiles) ? middleware.willRenameFiles(event, next) : next(event); } } exports.WillRenameFilesFeature = WillRenameFilesFeature; class WillDeleteFilesFeature extends RequestFileOperationFeature { constructor(client) { super(client, code.workspace.onWillDeleteFiles, proto.WillDeleteFilesRequest.type, 'willDelete', 'willDelete', (i) => i, client.code2ProtocolConverter.asWillDeleteFilesParams); } doSend(event, next) { var _a; const middleware = (_a = this._client.clientOptions.middleware) === null || _a === void 0 ? void 0 : _a.workspace; return (middleware === null || middleware === void 0 ? void 0 : middleware.willDeleteFiles) ? middleware.willDeleteFiles(event, next) : next(event); } } exports.WillDeleteFilesFeature = WillDeleteFilesFeature; //# sourceMappingURL=fileOperations.js.map /***/ }), /***/ 6454: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.FoldingRangeFeature = void 0; const vscode_1 = __webpack_require__(9496); const vscode_languageserver_protocol_1 = __webpack_require__(273); const client_1 = __webpack_require__(4384); function ensure(target, key) { if (target[key] === void 0) { target[key] = {}; } return target[key]; } class FoldingRangeFeature extends client_1.TextDocumentFeature { constructor(client) { super(client, vscode_languageserver_protocol_1.FoldingRangeRequest.type); } fillClientCapabilities(capabilities) { let capability = ensure(ensure(capabilities, 'textDocument'), 'foldingRange'); capability.dynamicRegistration = true; capability.rangeLimit = 5000; capability.lineFoldingOnly = true; } initialize(capabilities, documentSelector) { let [id, options] = this.getRegistration(documentSelector, capabilities.foldingRangeProvider); if (!id || !options) { return; } this.register({ id: id, registerOptions: options }); } registerLanguageProvider(options) { const provider = { provideFoldingRanges: (document, context, token) => { const client = this._client; const provideFoldingRanges = (document, _, token) => { const requestParams = { textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document) }; return client.sendRequest(vscode_languageserver_protocol_1.FoldingRangeRequest.type, requestParams, token).then(FoldingRangeFeature.asFoldingRanges, (error) => { return client.handleFailedRequest(vscode_languageserver_protocol_1.FoldingRangeRequest.type, error, null); }); }; const middleware = client.clientOptions.middleware; return middleware.provideFoldingRanges ? middleware.provideFoldingRanges(document, context, token, provideFoldingRanges) : provideFoldingRanges(document, context, token); } }; return [vscode_1.languages.registerFoldingRangeProvider(options.documentSelector, provider), provider]; } static asFoldingRangeKind(kind) { if (kind) { switch (kind) { case vscode_languageserver_protocol_1.FoldingRangeKind.Comment: return vscode_1.FoldingRangeKind.Comment; case vscode_languageserver_protocol_1.FoldingRangeKind.Imports: return vscode_1.FoldingRangeKind.Imports; case vscode_languageserver_protocol_1.FoldingRangeKind.Region: return vscode_1.FoldingRangeKind.Region; } } return void 0; } static asFoldingRanges(foldingRanges) { if (Array.isArray(foldingRanges)) { return foldingRanges.map(r => { return new vscode_1.FoldingRange(r.startLine, r.endLine, FoldingRangeFeature.asFoldingRangeKind(r.kind)); }); } return []; } } exports.FoldingRangeFeature = FoldingRangeFeature; //# sourceMappingURL=foldingRange.js.map /***/ }), /***/ 9889: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ImplementationFeature = void 0; const vscode_1 = __webpack_require__(9496); const vscode_languageserver_protocol_1 = __webpack_require__(273); const client_1 = __webpack_require__(4384); function ensure(target, key) { if (target[key] === void 0) { target[key] = {}; } return target[key]; } class ImplementationFeature extends client_1.TextDocumentFeature { constructor(client) { super(client, vscode_languageserver_protocol_1.ImplementationRequest.type); } fillClientCapabilities(capabilities) { let implementationSupport = ensure(ensure(capabilities, 'textDocument'), 'implementation'); implementationSupport.dynamicRegistration = true; implementationSupport.linkSupport = true; } initialize(capabilities, documentSelector) { let [id, options] = this.getRegistration(documentSelector, capabilities.implementationProvider); if (!id || !options) { return; } this.register({ id: id, registerOptions: options }); } registerLanguageProvider(options) { const provider = { provideImplementation: (document, position, token) => { const client = this._client; const provideImplementation = (document, position, token) => { return client.sendRequest(vscode_languageserver_protocol_1.ImplementationRequest.type, client.code2ProtocolConverter.asTextDocumentPositionParams(document, position), token).then(client.protocol2CodeConverter.asDefinitionResult, (error) => { return client.handleFailedRequest(vscode_languageserver_protocol_1.ImplementationRequest.type, error, null); }); }; const middleware = client.clientOptions.middleware; return middleware.provideImplementation ? middleware.provideImplementation(document, position, token, provideImplementation) : provideImplementation(document, position, token); } }; return [vscode_1.languages.registerImplementationProvider(options.documentSelector, provider), provider]; } } exports.ImplementationFeature = ImplementationFeature; //# sourceMappingURL=implementation.js.map /***/ }), /***/ 3483: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ /// Object.defineProperty(exports, "__esModule", ({ value: true })); exports.LinkedEditingFeature = void 0; const code = __webpack_require__(9496); const proto = __webpack_require__(273); const client_1 = __webpack_require__(4384); function ensure(target, key) { if (target[key] === void 0) { target[key] = {}; } return target[key]; } class LinkedEditingFeature extends client_1.TextDocumentFeature { constructor(client) { super(client, proto.LinkedEditingRangeRequest.type); } fillClientCapabilities(capabilities) { const linkedEditingSupport = ensure(ensure(capabilities, 'textDocument'), 'linkedEditingRange'); linkedEditingSupport.dynamicRegistration = true; } initialize(capabilities, documentSelector) { let [id, options] = this.getRegistration(documentSelector, capabilities.linkedEditingRangeProvider); if (!id || !options) { return; } this.register({ id: id, registerOptions: options }); } registerLanguageProvider(options) { const provider = { provideLinkedEditingRanges: (document, position, token) => { const client = this._client; const provideLinkedEditing = (document, position, token) => { return client.sendRequest(proto.LinkedEditingRangeRequest.type, client.code2ProtocolConverter.asTextDocumentPositionParams(document, position), token).then(client.protocol2CodeConverter.asLinkedEditingRanges, (error) => { return client.handleFailedRequest(proto.LinkedEditingRangeRequest.type, error, null); }); }; const middleware = client.clientOptions.middleware; return middleware.provideLinkedEditingRange ? middleware.provideLinkedEditingRange(document, position, token, provideLinkedEditing) : provideLinkedEditing(document, position, token); } }; return [code.languages.registerLinkedEditingRangeProvider(options.documentSelector, provider), provider]; } } exports.LinkedEditingFeature = LinkedEditingFeature; //# sourceMappingURL=linkedEditingRange.js.map /***/ }), /***/ 3603: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ProgressFeature = void 0; const vscode_languageserver_protocol_1 = __webpack_require__(273); const progressPart_1 = __webpack_require__(8071); function ensure(target, key) { if (target[key] === void 0) { target[key] = Object.create(null); } return target[key]; } class ProgressFeature { constructor(_client) { this._client = _client; this.activeParts = new Set(); } fillClientCapabilities(capabilities) { ensure(capabilities, 'window').workDoneProgress = true; } initialize() { const client = this._client; const deleteHandler = (part) => { this.activeParts.delete(part); }; const createHandler = (params) => { this.activeParts.add(new progressPart_1.ProgressPart(this._client, params.token, deleteHandler)); }; client.onRequest(vscode_languageserver_protocol_1.WorkDoneProgressCreateRequest.type, createHandler); } dispose() { for (const part of this.activeParts) { part.done(); } this.activeParts.clear(); } } exports.ProgressFeature = ProgressFeature; //# sourceMappingURL=progress.js.map /***/ }), /***/ 8071: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ProgressPart = void 0; const vscode_1 = __webpack_require__(9496); const vscode_languageserver_protocol_1 = __webpack_require__(273); const Is = __webpack_require__(9763); class ProgressPart { constructor(_client, _token, done) { this._client = _client; this._token = _token; this._reported = 0; this._disposable = this._client.onProgress(vscode_languageserver_protocol_1.WorkDoneProgress.type, this._token, (value) => { switch (value.kind) { case 'begin': this.begin(value); break; case 'report': this.report(value); break; case 'end': this.done(); done && done(this); break; } }); } begin(params) { // Since we don't use commands this will be a silent window progress with a hidden notification. vscode_1.window.withProgress({ location: vscode_1.ProgressLocation.Window, cancellable: params.cancellable, title: params.title }, async (progress, cancellationToken) => { this._progress = progress; this._infinite = params.percentage === undefined; this._cancellationToken = cancellationToken; this._cancellationToken.onCancellationRequested(() => { this._client.sendNotification(vscode_languageserver_protocol_1.WorkDoneProgressCancelNotification.type, { token: this._token }); }); this.report(params); return new Promise((resolve, reject) => { this._resolve = resolve; this._reject = reject; }); }); } report(params) { if (this._infinite && Is.string(params.message)) { this._progress.report({ message: params.message }); } else if (Is.number(params.percentage)) { let percentage = Math.max(0, Math.min(params.percentage, 100)); let delta = Math.max(0, percentage - this._reported); this._progress.report({ message: params.message, increment: delta }); this._reported += delta; } } cancel() { if (this._disposable) { this._disposable.dispose(); this._disposable = undefined; } if (this._reject) { this._reject(); this._resolve = undefined; this._reject = undefined; } } done() { if (this._disposable) { this._disposable.dispose(); this._disposable = undefined; } if (this._resolve) { this._resolve(); this._resolve = undefined; this._reject = undefined; } } } exports.ProgressPart = ProgressPart; //# sourceMappingURL=progressPart.js.map /***/ }), /***/ 8714: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ Object.defineProperty(exports, "__esModule", ({ value: true })); const code = __webpack_require__(9496); class ProtocolCallHierarchyItem extends code.CallHierarchyItem { constructor(kind, name, detail, uri, range, selectionRange, data) { super(kind, name, detail, uri, range, selectionRange); if (data !== undefined) { this.data = data; } } } exports["default"] = ProtocolCallHierarchyItem; //# sourceMappingURL=protocolCallHierarchyItem.js.map /***/ }), /***/ 6434: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ Object.defineProperty(exports, "__esModule", ({ value: true })); const vscode = __webpack_require__(9496); class ProtocolCodeAction extends vscode.CodeAction { constructor(title, data) { super(title); this.data = data; } } exports["default"] = ProtocolCodeAction; //# sourceMappingURL=protocolCodeAction.js.map /***/ }), /***/ 583: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ Object.defineProperty(exports, "__esModule", ({ value: true })); const code = __webpack_require__(9496); class ProtocolCodeLens extends code.CodeLens { constructor(range) { super(range); } } exports["default"] = ProtocolCodeLens; //# sourceMappingURL=protocolCodeLens.js.map /***/ }), /***/ 1807: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ Object.defineProperty(exports, "__esModule", ({ value: true })); const code = __webpack_require__(9496); class ProtocolCompletionItem extends code.CompletionItem { constructor(label) { super(label); } } exports["default"] = ProtocolCompletionItem; //# sourceMappingURL=protocolCompletionItem.js.map /***/ }), /***/ 8785: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ /// Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createConverter = void 0; const code = __webpack_require__(9496); const ls = __webpack_require__(273); const Is = __webpack_require__(9763); const protocolCompletionItem_1 = __webpack_require__(1807); const protocolCodeLens_1 = __webpack_require__(583); const protocolDocumentLink_1 = __webpack_require__(8705); const protocolCodeAction_1 = __webpack_require__(6434); const protocolDiagnostic_1 = __webpack_require__(6640); const protocolCallHierarchyItem_1 = __webpack_require__(8714); const vscode_languageserver_protocol_1 = __webpack_require__(273); var CodeBlock; (function (CodeBlock) { function is(value) { let candidate = value; return candidate && Is.string(candidate.language) && Is.string(candidate.value); } CodeBlock.is = is; })(CodeBlock || (CodeBlock = {})); function createConverter(uriConverter, trustMarkdown) { const nullConverter = (value) => code.Uri.parse(value); const _uriConverter = uriConverter || nullConverter; function asUri(value) { return _uriConverter(value); } function asDiagnostics(diagnostics) { return diagnostics.map(asDiagnostic); } function asDiagnostic(diagnostic) { let result = new protocolDiagnostic_1.ProtocolDiagnostic(asRange(diagnostic.range), diagnostic.message, asDiagnosticSeverity(diagnostic.severity), diagnostic.data); if (diagnostic.code !== undefined) { if (ls.CodeDescription.is(diagnostic.codeDescription)) { result.code = { value: diagnostic.code, target: asUri(diagnostic.codeDescription.href) }; } else if (protocolDiagnostic_1.DiagnosticCode.is(diagnostic.code)) { result.hasDiagnosticCode = true; result.code = { value: diagnostic.code.value, target: asUri(diagnostic.code.target) }; } else { result.code = diagnostic.code; } } if (diagnostic.source) { result.source = diagnostic.source; } if (diagnostic.relatedInformation) { result.relatedInformation = asRelatedInformation(diagnostic.relatedInformation); } if (Array.isArray(diagnostic.tags)) { result.tags = asDiagnosticTags(diagnostic.tags); } return result; } function asRelatedInformation(relatedInformation) { return relatedInformation.map(asDiagnosticRelatedInformation); } function asDiagnosticRelatedInformation(information) { return new code.DiagnosticRelatedInformation(asLocation(information.location), information.message); } function asDiagnosticTags(tags) { if (!tags) { return undefined; } let result = []; for (let tag of tags) { let converted = asDiagnosticTag(tag); if (converted !== undefined) { result.push(converted); } } return result.length > 0 ? result : undefined; } function asDiagnosticTag(tag) { switch (tag) { case ls.DiagnosticTag.Unnecessary: return code.DiagnosticTag.Unnecessary; case ls.DiagnosticTag.Deprecated: return code.DiagnosticTag.Deprecated; default: return undefined; } } function asPosition(value) { if (!value) { return undefined; } return new code.Position(value.line, value.character); } function asRange(value) { if (!value) { return undefined; } return new code.Range(asPosition(value.start), asPosition(value.end)); } function asRanges(value) { return value.map(value => asRange(value)); } function asDiagnosticSeverity(value) { if (value === undefined || value === null) { return code.DiagnosticSeverity.Error; } switch (value) { case ls.DiagnosticSeverity.Error: return code.DiagnosticSeverity.Error; case ls.DiagnosticSeverity.Warning: return code.DiagnosticSeverity.Warning; case ls.DiagnosticSeverity.Information: return code.DiagnosticSeverity.Information; case ls.DiagnosticSeverity.Hint: return code.DiagnosticSeverity.Hint; } return code.DiagnosticSeverity.Error; } function asHoverContent(value) { if (Is.string(value)) { return asMarkdownString(value); } else if (CodeBlock.is(value)) { let result = asMarkdownString(); return result.appendCodeblock(value.value, value.language); } else if (Array.isArray(value)) { let result = []; for (let element of value) { let item = asMarkdownString(); if (CodeBlock.is(element)) { item.appendCodeblock(element.value, element.language); } else { item.appendMarkdown(element); } result.push(item); } return result; } else { let result; switch (value.kind) { case ls.MarkupKind.Markdown: return asMarkdownString(value.value); case ls.MarkupKind.PlainText: result = asMarkdownString(); result.appendText(value.value); return result; default: result = asMarkdownString(); result.appendText(`Unsupported Markup content received. Kind is: ${value.kind}`); return result; } } } function asDocumentation(value) { if (Is.string(value)) { return value; } else { switch (value.kind) { case ls.MarkupKind.Markdown: return asMarkdownString(value.value); case ls.MarkupKind.PlainText: return value.value; default: return `Unsupported Markup content received. Kind is: ${value.kind}`; } } } function asMarkdownString(value) { const result = new code.MarkdownString(value); if (trustMarkdown === true) { result.isTrusted = trustMarkdown; } return result; } function asHover(hover) { if (!hover) { return undefined; } return new code.Hover(asHoverContent(hover.contents), asRange(hover.range)); } function asCompletionResult(result) { if (!result) { return undefined; } if (Array.isArray(result)) { let items = result; return items.map(asCompletionItem); } let list = result; return new code.CompletionList(list.items.map(asCompletionItem), list.isIncomplete); } function asCompletionItemKind(value) { // Protocol item kind is 1 based, codes item kind is zero based. if (ls.CompletionItemKind.Text <= value && value <= ls.CompletionItemKind.TypeParameter) { return [value - 1, undefined]; } return [code.CompletionItemKind.Text, value]; } function asCompletionItemTag(tag) { switch (tag) { case ls.CompletionItemTag.Deprecated: return code.CompletionItemTag.Deprecated; } return undefined; } function asCompletionItemTags(tags) { if (tags === undefined || tags === null) { return []; } const result = []; for (let tag of tags) { const converted = asCompletionItemTag(tag); if (converted !== undefined) { result.push(converted); } } return result; } function asCompletionItem(item) { let tags = asCompletionItemTags(item.tags); let result = new protocolCompletionItem_1.default(item.label); if (item.detail) { result.detail = item.detail; } if (item.documentation) { result.documentation = asDocumentation(item.documentation); result.documentationFormat = Is.string(item.documentation) ? '$string' : item.documentation.kind; } if (item.filterText) { result.filterText = item.filterText; } let insertText = asCompletionInsertText(item); if (insertText) { result.insertText = insertText.text; result.range = insertText.range; result.fromEdit = insertText.fromEdit; } if (Is.number(item.kind)) { let [itemKind, original] = asCompletionItemKind(item.kind); result.kind = itemKind; if (original) { result.originalItemKind = original; } } if (item.sortText) { result.sortText = item.sortText; } if (item.additionalTextEdits) { result.additionalTextEdits = asTextEdits(item.additionalTextEdits); } if (Is.stringArray(item.commitCharacters)) { result.commitCharacters = item.commitCharacters.slice(); } if (item.command) { result.command = asCommand(item.command); } if (item.deprecated === true || item.deprecated === false) { result.deprecated = item.deprecated; if (item.deprecated === true) { tags.push(code.CompletionItemTag.Deprecated); } } if (item.preselect === true || item.preselect === false) { result.preselect = item.preselect; } if (item.data !== undefined) { result.data = item.data; } if (tags.length > 0) { result.tags = tags; } if (item.insertTextMode !== undefined) { result.insertTextMode = item.insertTextMode; if (item.insertTextMode === vscode_languageserver_protocol_1.InsertTextMode.asIs) { result.keepWhitespace = true; } } return result; } function asCompletionInsertText(item) { if (item.textEdit) { if (item.insertTextFormat === ls.InsertTextFormat.Snippet) { return { text: new code.SnippetString(item.textEdit.newText), range: asCompletionRange(item.textEdit), fromEdit: true }; } else { return { text: item.textEdit.newText, range: asCompletionRange(item.textEdit), fromEdit: true }; } } else if (item.insertText) { if (item.insertTextFormat === ls.InsertTextFormat.Snippet) { return { text: new code.SnippetString(item.insertText), fromEdit: false }; } else { return { text: item.insertText, fromEdit: false }; } } else { return undefined; } } function asCompletionRange(value) { if (ls.InsertReplaceEdit.is(value)) { return { inserting: asRange(value.insert), replacing: asRange(value.replace) }; } else { return asRange(value.range); } } function asTextEdit(edit) { if (!edit) { return undefined; } return new code.TextEdit(asRange(edit.range), edit.newText); } function asTextEdits(items) { if (!items) { return undefined; } return items.map(asTextEdit); } function asSignatureHelp(item) { if (!item) { return undefined; } let result = new code.SignatureHelp(); if (Is.number(item.activeSignature)) { result.activeSignature = item.activeSignature; } else { // activeSignature was optional in the past result.activeSignature = 0; } if (Is.number(item.activeParameter)) { result.activeParameter = item.activeParameter; } else { // activeParameter was optional in the past result.activeParameter = 0; } if (item.signatures) { result.signatures = asSignatureInformations(item.signatures); } return result; } function asSignatureInformations(items) { return items.map(asSignatureInformation); } function asSignatureInformation(item) { let result = new code.SignatureInformation(item.label); if (item.documentation !== undefined) { result.documentation = asDocumentation(item.documentation); } if (item.parameters !== undefined) { result.parameters = asParameterInformations(item.parameters); } if (item.activeParameter !== undefined) { result.activeParameter = item.activeParameter; } { return result; } } function asParameterInformations(item) { return item.map(asParameterInformation); } function asParameterInformation(item) { let result = new code.ParameterInformation(item.label); if (item.documentation) { result.documentation = asDocumentation(item.documentation); } return result; } function asLocation(item) { if (!item) { return undefined; } return new code.Location(_uriConverter(item.uri), asRange(item.range)); } function asDeclarationResult(item) { if (!item) { return undefined; } return asLocationResult(item); } function asDefinitionResult(item) { if (!item) { return undefined; } return asLocationResult(item); } function asLocationLink(item) { if (!item) { return undefined; } let result = { targetUri: _uriConverter(item.targetUri), targetRange: asRange(item.targetRange), originSelectionRange: asRange(item.originSelectionRange), targetSelectionRange: asRange(item.targetSelectionRange) }; if (!result.targetSelectionRange) { throw new Error(`targetSelectionRange must not be undefined or null`); } return result; } function asLocationResult(item) { if (!item) { return undefined; } if (Is.array(item)) { if (item.length === 0) { return []; } else if (ls.LocationLink.is(item[0])) { let links = item; return links.map((link) => asLocationLink(link)); } else { let locations = item; return locations.map((location) => asLocation(location)); } } else if (ls.LocationLink.is(item)) { return [asLocationLink(item)]; } else { return asLocation(item); } } function asReferences(values) { if (!values) { return undefined; } return values.map(location => asLocation(location)); } function asDocumentHighlights(values) { if (!values) { return undefined; } return values.map(asDocumentHighlight); } function asDocumentHighlight(item) { let result = new code.DocumentHighlight(asRange(item.range)); if (Is.number(item.kind)) { result.kind = asDocumentHighlightKind(item.kind); } return result; } function asDocumentHighlightKind(item) { switch (item) { case ls.DocumentHighlightKind.Text: return code.DocumentHighlightKind.Text; case ls.DocumentHighlightKind.Read: return code.DocumentHighlightKind.Read; case ls.DocumentHighlightKind.Write: return code.DocumentHighlightKind.Write; } return code.DocumentHighlightKind.Text; } function asSymbolInformations(values, uri) { if (!values) { return undefined; } return values.map(information => asSymbolInformation(information, uri)); } function asSymbolKind(item) { if (item <= ls.SymbolKind.TypeParameter) { // Symbol kind is one based in the protocol and zero based in code. return item - 1; } return code.SymbolKind.Property; } function asSymbolTag(value) { switch (value) { case ls.SymbolTag.Deprecated: return code.SymbolTag.Deprecated; default: return undefined; } } function asSymbolTags(items) { if (items === undefined || items === null) { return undefined; } const result = []; for (const item of items) { const converted = asSymbolTag(item); if (converted !== undefined) { result.push(converted); } } return result.length === 0 ? undefined : result; } function asSymbolInformation(item, uri) { // Symbol kind is one based in the protocol and zero based in code. let result = new code.SymbolInformation(item.name, asSymbolKind(item.kind), asRange(item.location.range), item.location.uri ? _uriConverter(item.location.uri) : uri); fillTags(result, item); if (item.containerName) { result.containerName = item.containerName; } return result; } function asDocumentSymbols(values) { if (values === undefined || values === null) { return undefined; } return values.map(asDocumentSymbol); } function asDocumentSymbol(value) { let result = new code.DocumentSymbol(value.name, value.detail || '', asSymbolKind(value.kind), asRange(value.range), asRange(value.selectionRange)); fillTags(result, value); if (value.children !== undefined && value.children.length > 0) { let children = []; for (let child of value.children) { children.push(asDocumentSymbol(child)); } result.children = children; } return result; } function fillTags(result, value) { result.tags = asSymbolTags(value.tags); if (value.deprecated) { if (!result.tags) { result.tags = [code.SymbolTag.Deprecated]; } else { if (!result.tags.includes(code.SymbolTag.Deprecated)) { result.tags = result.tags.concat(code.SymbolTag.Deprecated); } } } } function asCommand(item) { let result = { title: item.title, command: item.command }; if (item.arguments) { result.arguments = item.arguments; } return result; } function asCommands(items) { if (!items) { return undefined; } return items.map(asCommand); } const kindMapping = new Map(); kindMapping.set(ls.CodeActionKind.Empty, code.CodeActionKind.Empty); kindMapping.set(ls.CodeActionKind.QuickFix, code.CodeActionKind.QuickFix); kindMapping.set(ls.CodeActionKind.Refactor, code.CodeActionKind.Refactor); kindMapping.set(ls.CodeActionKind.RefactorExtract, code.CodeActionKind.RefactorExtract); kindMapping.set(ls.CodeActionKind.RefactorInline, code.CodeActionKind.RefactorInline); kindMapping.set(ls.CodeActionKind.RefactorRewrite, code.CodeActionKind.RefactorRewrite); kindMapping.set(ls.CodeActionKind.Source, code.CodeActionKind.Source); kindMapping.set(ls.CodeActionKind.SourceOrganizeImports, code.CodeActionKind.SourceOrganizeImports); function asCodeActionKind(item) { if (item === undefined || item === null) { return undefined; } let result = kindMapping.get(item); if (result) { return result; } let parts = item.split('.'); result = code.CodeActionKind.Empty; for (let part of parts) { result = result.append(part); } return result; } function asCodeActionKinds(items) { if (items === undefined || items === null) { return undefined; } return items.map(kind => asCodeActionKind(kind)); } function asCodeAction(item) { if (item === undefined || item === null) { return undefined; } let result = new protocolCodeAction_1.default(item.title, item.data); if (item.kind !== undefined) { result.kind = asCodeActionKind(item.kind); } if (item.diagnostics !== undefined) { result.diagnostics = asDiagnostics(item.diagnostics); } if (item.edit !== undefined) { result.edit = asWorkspaceEdit(item.edit); } if (item.command !== undefined) { result.command = asCommand(item.command); } if (item.isPreferred !== undefined) { result.isPreferred = item.isPreferred; } if (item.disabled !== undefined) { result.disabled = { reason: item.disabled.reason }; } return result; } function asCodeLens(item) { if (!item) { return undefined; } let result = new protocolCodeLens_1.default(asRange(item.range)); if (item.command) { result.command = asCommand(item.command); } if (item.data !== undefined && item.data !== null) { result.data = item.data; } return result; } function asCodeLenses(items) { if (!items) { return undefined; } return items.map((codeLens) => asCodeLens(codeLens)); } function asWorkspaceEdit(item) { if (!item) { return undefined; } const sharedMetadata = new Map(); if (item.changeAnnotations !== undefined) { for (const key of Object.keys(item.changeAnnotations)) { const metaData = asWorkspaceEditEntryMetadata(item.changeAnnotations[key]); sharedMetadata.set(key, metaData); } } const asMetadata = (annotation) => { if (annotation === undefined) { return undefined; } else { return sharedMetadata.get(annotation); } }; const result = new code.WorkspaceEdit(); if (item.documentChanges) { for (const change of item.documentChanges) { if (ls.CreateFile.is(change)) { result.createFile(_uriConverter(change.uri), change.options, asMetadata(change.annotationId)); } else if (ls.RenameFile.is(change)) { result.renameFile(_uriConverter(change.oldUri), _uriConverter(change.newUri), change.options, asMetadata(change.annotationId)); } else if (ls.DeleteFile.is(change)) { result.deleteFile(_uriConverter(change.uri), change.options, asMetadata(change.annotationId)); } else if (ls.TextDocumentEdit.is(change)) { const uri = _uriConverter(change.textDocument.uri); for (const edit of change.edits) { if (vscode_languageserver_protocol_1.AnnotatedTextEdit.is(edit)) { result.replace(uri, asRange(edit.range), edit.newText, asMetadata(edit.annotationId)); } else { result.replace(uri, asRange(edit.range), edit.newText); } } } else { throw new Error(`Unknown workspace edit change received:\n${JSON.stringify(change, undefined, 4)}`); } } } else if (item.changes) { Object.keys(item.changes).forEach(key => { result.set(_uriConverter(key), asTextEdits(item.changes[key])); }); } return result; } function asWorkspaceEditEntryMetadata(annotation) { if (annotation === undefined) { return undefined; } return { label: annotation.label, needsConfirmation: !!annotation.needsConfirmation, description: annotation.description }; } function asDocumentLink(item) { let range = asRange(item.range); let target = item.target ? asUri(item.target) : undefined; // target must be optional in DocumentLink let link = new protocolDocumentLink_1.default(range, target); if (item.tooltip !== undefined) { link.tooltip = item.tooltip; } if (item.data !== undefined && item.data !== null) { link.data = item.data; } return link; } function asDocumentLinks(items) { if (!items) { return undefined; } return items.map(asDocumentLink); } function asColor(color) { return new code.Color(color.red, color.green, color.blue, color.alpha); } function asColorInformation(ci) { return new code.ColorInformation(asRange(ci.range), asColor(ci.color)); } function asColorInformations(colorInformation) { if (Array.isArray(colorInformation)) { return colorInformation.map(asColorInformation); } return undefined; } function asColorPresentation(cp) { let presentation = new code.ColorPresentation(cp.label); presentation.additionalTextEdits = asTextEdits(cp.additionalTextEdits); if (cp.textEdit) { presentation.textEdit = asTextEdit(cp.textEdit); } return presentation; } function asColorPresentations(colorPresentations) { if (Array.isArray(colorPresentations)) { return colorPresentations.map(asColorPresentation); } return undefined; } function asFoldingRangeKind(kind) { if (kind) { switch (kind) { case ls.FoldingRangeKind.Comment: return code.FoldingRangeKind.Comment; case ls.FoldingRangeKind.Imports: return code.FoldingRangeKind.Imports; case ls.FoldingRangeKind.Region: return code.FoldingRangeKind.Region; } } return undefined; } function asFoldingRange(r) { return new code.FoldingRange(r.startLine, r.endLine, asFoldingRangeKind(r.kind)); } function asFoldingRanges(foldingRanges) { if (Array.isArray(foldingRanges)) { return foldingRanges.map(asFoldingRange); } return undefined; } function asSelectionRange(selectionRange) { return new code.SelectionRange(asRange(selectionRange.range), selectionRange.parent ? asSelectionRange(selectionRange.parent) : undefined); } function asSelectionRanges(selectionRanges) { if (!Array.isArray(selectionRanges)) { return []; } let result = []; for (let range of selectionRanges) { result.push(asSelectionRange(range)); } return result; } function asCallHierarchyItem(item) { if (item === null) { return undefined; } let result = new protocolCallHierarchyItem_1.default(asSymbolKind(item.kind), item.name, item.detail || '', asUri(item.uri), asRange(item.range), asRange(item.selectionRange), item.data); if (item.tags !== undefined) { result.tags = asSymbolTags(item.tags); } return result; } function asCallHierarchyItems(items) { if (items === null) { return undefined; } return items.map(item => asCallHierarchyItem(item)); } function asCallHierarchyIncomingCall(item) { return new code.CallHierarchyIncomingCall(asCallHierarchyItem(item.from), asRanges(item.fromRanges)); } function asCallHierarchyIncomingCalls(items) { if (items === null) { return undefined; } return items.map(item => asCallHierarchyIncomingCall(item)); } function asCallHierarchyOutgoingCall(item) { return new code.CallHierarchyOutgoingCall(asCallHierarchyItem(item.to), asRanges(item.fromRanges)); } function asCallHierarchyOutgoingCalls(items) { if (items === null) { return undefined; } return items.map(item => asCallHierarchyOutgoingCall(item)); } function asSemanticTokens(value) { if (value === undefined || value === null) { return undefined; } return new code.SemanticTokens(new Uint32Array(value.data), value.resultId); } function asSemanticTokensEdit(value) { return new code.SemanticTokensEdit(value.start, value.deleteCount, value.data !== undefined ? new Uint32Array(value.data) : undefined); } function asSemanticTokensEdits(value) { if (value === undefined || value === null) { return undefined; } return new code.SemanticTokensEdits(value.edits.map(asSemanticTokensEdit), value.resultId); } function asSemanticTokensLegend(value) { return value; } function asLinkedEditingRanges(value) { if (value === null || value === undefined) { return undefined; } return new code.LinkedEditingRanges(asRanges(value.ranges), asRegularExpression(value.wordPattern)); } function asRegularExpression(value) { if (value === null || value === undefined) { return undefined; } return new RegExp(value); } return { asUri, asDiagnostics, asDiagnostic, asRange, asRanges, asPosition, asDiagnosticSeverity, asDiagnosticTag, asHover, asCompletionResult, asCompletionItem, asTextEdit, asTextEdits, asSignatureHelp, asSignatureInformations, asSignatureInformation, asParameterInformations, asParameterInformation, asDeclarationResult, asDefinitionResult, asLocation, asReferences, asDocumentHighlights, asDocumentHighlight, asDocumentHighlightKind, asSymbolKind, asSymbolTag, asSymbolTags, asSymbolInformations, asSymbolInformation, asDocumentSymbols, asDocumentSymbol, asCommand, asCommands, asCodeAction, asCodeActionKind, asCodeActionKinds, asCodeLens, asCodeLenses, asWorkspaceEdit, asDocumentLink, asDocumentLinks, asFoldingRangeKind, asFoldingRange, asFoldingRanges, asColor, asColorInformation, asColorInformations, asColorPresentation, asColorPresentations, asSelectionRange, asSelectionRanges, asSemanticTokensLegend, asSemanticTokens, asSemanticTokensEdit, asSemanticTokensEdits, asCallHierarchyItem, asCallHierarchyItems, asCallHierarchyIncomingCall, asCallHierarchyIncomingCalls, asCallHierarchyOutgoingCall, asCallHierarchyOutgoingCalls, asLinkedEditingRanges: asLinkedEditingRanges }; } exports.createConverter = createConverter; //# sourceMappingURL=protocolConverter.js.map /***/ }), /***/ 6640: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ProtocolDiagnostic = exports.DiagnosticCode = void 0; const vscode = __webpack_require__(9496); const Is = __webpack_require__(9763); var DiagnosticCode; (function (DiagnosticCode) { function is(value) { const candidate = value; return candidate !== undefined && candidate !== null && (Is.number(candidate.value) || Is.string(candidate.value)) && Is.string(candidate.target); } DiagnosticCode.is = is; })(DiagnosticCode = exports.DiagnosticCode || (exports.DiagnosticCode = {})); class ProtocolDiagnostic extends vscode.Diagnostic { constructor(range, message, severity, data) { super(range, message, severity); this.data = data; this.hasDiagnosticCode = false; } } exports.ProtocolDiagnostic = ProtocolDiagnostic; //# sourceMappingURL=protocolDiagnostic.js.map /***/ }), /***/ 8705: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ Object.defineProperty(exports, "__esModule", ({ value: true })); const code = __webpack_require__(9496); class ProtocolDocumentLink extends code.DocumentLink { constructor(range, target) { super(range, target); } } exports["default"] = ProtocolDocumentLink; //# sourceMappingURL=protocolDocumentLink.js.map /***/ }), /***/ 750: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.SelectionRangeFeature = void 0; const vscode_1 = __webpack_require__(9496); const vscode_languageserver_protocol_1 = __webpack_require__(273); const client_1 = __webpack_require__(4384); function ensure(target, key) { if (target[key] === void 0) { target[key] = Object.create(null); } return target[key]; } class SelectionRangeFeature extends client_1.TextDocumentFeature { constructor(client) { super(client, vscode_languageserver_protocol_1.SelectionRangeRequest.type); } fillClientCapabilities(capabilities) { let capability = ensure(ensure(capabilities, 'textDocument'), 'selectionRange'); capability.dynamicRegistration = true; } initialize(capabilities, documentSelector) { let [id, options] = this.getRegistration(documentSelector, capabilities.selectionRangeProvider); if (!id || !options) { return; } this.register({ id: id, registerOptions: options }); } registerLanguageProvider(options) { const provider = { provideSelectionRanges: (document, positions, token) => { const client = this._client; const provideSelectionRanges = (document, positions, token) => { const requestParams = { textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document), positions: client.code2ProtocolConverter.asPositions(positions) }; return client.sendRequest(vscode_languageserver_protocol_1.SelectionRangeRequest.type, requestParams, token).then((ranges) => client.protocol2CodeConverter.asSelectionRanges(ranges), (error) => { return client.handleFailedRequest(vscode_languageserver_protocol_1.SelectionRangeRequest.type, error, null); }); }; const middleware = client.clientOptions.middleware; return middleware.provideSelectionRanges ? middleware.provideSelectionRanges(document, positions, token, provideSelectionRanges) : provideSelectionRanges(document, positions, token); } }; return [vscode_1.languages.registerSelectionRangeProvider(options.documentSelector, provider), provider]; } } exports.SelectionRangeFeature = SelectionRangeFeature; //# sourceMappingURL=selectionRange.js.map /***/ }), /***/ 9957: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.SemanticTokensFeature = void 0; const vscode = __webpack_require__(9496); const client_1 = __webpack_require__(4384); const vscode_languageserver_protocol_1 = __webpack_require__(273); const Is = __webpack_require__(9763); function ensure(target, key) { if (target[key] === void 0) { target[key] = {}; } return target[key]; } class SemanticTokensFeature extends client_1.TextDocumentFeature { constructor(client) { super(client, vscode_languageserver_protocol_1.SemanticTokensRegistrationType.type); } fillClientCapabilities(capabilities) { const capability = ensure(ensure(capabilities, 'textDocument'), 'semanticTokens'); capability.dynamicRegistration = true; capability.tokenTypes = [ vscode_languageserver_protocol_1.SemanticTokenTypes.namespace, vscode_languageserver_protocol_1.SemanticTokenTypes.type, vscode_languageserver_protocol_1.SemanticTokenTypes.class, vscode_languageserver_protocol_1.SemanticTokenTypes.enum, vscode_languageserver_protocol_1.SemanticTokenTypes.interface, vscode_languageserver_protocol_1.SemanticTokenTypes.struct, vscode_languageserver_protocol_1.SemanticTokenTypes.typeParameter, vscode_languageserver_protocol_1.SemanticTokenTypes.parameter, vscode_languageserver_protocol_1.SemanticTokenTypes.variable, vscode_languageserver_protocol_1.SemanticTokenTypes.property, vscode_languageserver_protocol_1.SemanticTokenTypes.enumMember, vscode_languageserver_protocol_1.SemanticTokenTypes.event, vscode_languageserver_protocol_1.SemanticTokenTypes.function, vscode_languageserver_protocol_1.SemanticTokenTypes.method, vscode_languageserver_protocol_1.SemanticTokenTypes.macro, vscode_languageserver_protocol_1.SemanticTokenTypes.keyword, vscode_languageserver_protocol_1.SemanticTokenTypes.modifier, vscode_languageserver_protocol_1.SemanticTokenTypes.comment, vscode_languageserver_protocol_1.SemanticTokenTypes.string, vscode_languageserver_protocol_1.SemanticTokenTypes.number, vscode_languageserver_protocol_1.SemanticTokenTypes.regexp, vscode_languageserver_protocol_1.SemanticTokenTypes.operator ]; capability.tokenModifiers = [ vscode_languageserver_protocol_1.SemanticTokenModifiers.declaration, vscode_languageserver_protocol_1.SemanticTokenModifiers.definition, vscode_languageserver_protocol_1.SemanticTokenModifiers.readonly, vscode_languageserver_protocol_1.SemanticTokenModifiers.static, vscode_languageserver_protocol_1.SemanticTokenModifiers.deprecated, vscode_languageserver_protocol_1.SemanticTokenModifiers.abstract, vscode_languageserver_protocol_1.SemanticTokenModifiers.async, vscode_languageserver_protocol_1.SemanticTokenModifiers.modification, vscode_languageserver_protocol_1.SemanticTokenModifiers.documentation, vscode_languageserver_protocol_1.SemanticTokenModifiers.defaultLibrary ]; capability.formats = [vscode_languageserver_protocol_1.TokenFormat.Relative]; capability.requests = { range: true, full: { delta: true } }; capability.multilineTokenSupport = false; capability.overlappingTokenSupport = false; ensure(ensure(capabilities, 'workspace'), 'semanticTokens').refreshSupport = true; } initialize(capabilities, documentSelector) { const client = this._client; client.onRequest(vscode_languageserver_protocol_1.SemanticTokensRefreshRequest.type, async () => { for (const provider of this.getAllProviders()) { provider.onDidChangeSemanticTokensEmitter.fire(); } }); const [id, options] = this.getRegistration(documentSelector, capabilities.semanticTokensProvider); if (!id || !options) { return; } this.register({ id: id, registerOptions: options }); } registerLanguageProvider(options) { const fullProvider = Is.boolean(options.full) ? options.full : options.full !== undefined; const hasEditProvider = options.full !== undefined && typeof options.full !== 'boolean' && options.full.delta === true; const eventEmitter = new vscode.EventEmitter(); const documentProvider = fullProvider ? { onDidChangeSemanticTokens: eventEmitter.event, provideDocumentSemanticTokens: (document, token) => { const client = this._client; const middleware = client.clientOptions.middleware; const provideDocumentSemanticTokens = (document, token) => { const params = { textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document) }; return client.sendRequest(vscode_languageserver_protocol_1.SemanticTokensRequest.type, params, token).then((result) => { return client.protocol2CodeConverter.asSemanticTokens(result); }, (error) => { return client.handleFailedRequest(vscode_languageserver_protocol_1.SemanticTokensRequest.type, error, null); }); }; return middleware.provideDocumentSemanticTokens ? middleware.provideDocumentSemanticTokens(document, token, provideDocumentSemanticTokens) : provideDocumentSemanticTokens(document, token); }, provideDocumentSemanticTokensEdits: hasEditProvider ? (document, previousResultId, token) => { const client = this._client; const middleware = client.clientOptions.middleware; const provideDocumentSemanticTokensEdits = (document, previousResultId, token) => { const params = { textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document), previousResultId }; return client.sendRequest(vscode_languageserver_protocol_1.SemanticTokensDeltaRequest.type, params, token).then((result) => { if (vscode_languageserver_protocol_1.SemanticTokens.is(result)) { return client.protocol2CodeConverter.asSemanticTokens(result); } else { return client.protocol2CodeConverter.asSemanticTokensEdits(result); } }, (error) => { return client.handleFailedRequest(vscode_languageserver_protocol_1.SemanticTokensDeltaRequest.type, error, null); }); }; return middleware.provideDocumentSemanticTokensEdits ? middleware.provideDocumentSemanticTokensEdits(document, previousResultId, token, provideDocumentSemanticTokensEdits) : provideDocumentSemanticTokensEdits(document, previousResultId, token); } : undefined } : undefined; const hasRangeProvider = options.range === true; const rangeProvider = hasRangeProvider ? { provideDocumentRangeSemanticTokens: (document, range, token) => { const client = this._client; const middleware = client.clientOptions.middleware; const provideDocumentRangeSemanticTokens = (document, range, token) => { const params = { textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document), range: client.code2ProtocolConverter.asRange(range) }; return client.sendRequest(vscode_languageserver_protocol_1.SemanticTokensRangeRequest.type, params, token).then((result) => { return client.protocol2CodeConverter.asSemanticTokens(result); }, (error) => { return client.handleFailedRequest(vscode_languageserver_protocol_1.SemanticTokensRangeRequest.type, error, null); }); }; return middleware.provideDocumentRangeSemanticTokens ? middleware.provideDocumentRangeSemanticTokens(document, range, token, provideDocumentRangeSemanticTokens) : provideDocumentRangeSemanticTokens(document, range, token); } } : undefined; const disposables = []; const client = this._client; const legend = client.protocol2CodeConverter.asSemanticTokensLegend(options.legend); if (documentProvider !== undefined) { disposables.push(vscode.languages.registerDocumentSemanticTokensProvider(options.documentSelector, documentProvider, legend)); } if (rangeProvider !== undefined) { disposables.push(vscode.languages.registerDocumentRangeSemanticTokensProvider(options.documentSelector, rangeProvider, legend)); } return [new vscode.Disposable(() => disposables.forEach(item => item.dispose())), { range: rangeProvider, full: documentProvider, onDidChangeSemanticTokensEmitter: eventEmitter }]; } } exports.SemanticTokensFeature = SemanticTokensFeature; //# sourceMappingURL=semanticTokens.js.map /***/ }), /***/ 328: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.TypeDefinitionFeature = void 0; const vscode_1 = __webpack_require__(9496); const vscode_languageserver_protocol_1 = __webpack_require__(273); const client_1 = __webpack_require__(4384); function ensure(target, key) { if (target[key] === void 0) { target[key] = {}; } return target[key]; } class TypeDefinitionFeature extends client_1.TextDocumentFeature { constructor(client) { super(client, vscode_languageserver_protocol_1.TypeDefinitionRequest.type); } fillClientCapabilities(capabilities) { ensure(ensure(capabilities, 'textDocument'), 'typeDefinition').dynamicRegistration = true; let typeDefinitionSupport = ensure(ensure(capabilities, 'textDocument'), 'typeDefinition'); typeDefinitionSupport.dynamicRegistration = true; typeDefinitionSupport.linkSupport = true; } initialize(capabilities, documentSelector) { let [id, options] = this.getRegistration(documentSelector, capabilities.typeDefinitionProvider); if (!id || !options) { return; } this.register({ id: id, registerOptions: options }); } registerLanguageProvider(options) { const provider = { provideTypeDefinition: (document, position, token) => { const client = this._client; const provideTypeDefinition = (document, position, token) => { return client.sendRequest(vscode_languageserver_protocol_1.TypeDefinitionRequest.type, client.code2ProtocolConverter.asTextDocumentPositionParams(document, position), token).then(client.protocol2CodeConverter.asDefinitionResult, (error) => { return client.handleFailedRequest(vscode_languageserver_protocol_1.TypeDefinitionRequest.type, error, null); }); }; const middleware = client.clientOptions.middleware; return middleware.provideTypeDefinition ? middleware.provideTypeDefinition(document, position, token, provideTypeDefinition) : provideTypeDefinition(document, position, token); } }; return [vscode_1.languages.registerTypeDefinitionProvider(options.documentSelector, provider), provider]; } } exports.TypeDefinitionFeature = TypeDefinitionFeature; //# sourceMappingURL=typeDefinition.js.map /***/ }), /***/ 4904: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Delayer = void 0; const vscode_languageserver_protocol_1 = __webpack_require__(273); class Delayer { constructor(defaultDelay) { this.defaultDelay = defaultDelay; this.timeout = undefined; this.completionPromise = undefined; this.onSuccess = undefined; this.task = undefined; } trigger(task, delay = this.defaultDelay) { this.task = task; if (delay >= 0) { this.cancelTimeout(); } if (!this.completionPromise) { this.completionPromise = new Promise((resolve) => { this.onSuccess = resolve; }).then(() => { this.completionPromise = undefined; this.onSuccess = undefined; var result = this.task(); this.task = undefined; return result; }); } if (delay >= 0 || this.timeout === void 0) { this.timeout = vscode_languageserver_protocol_1.RAL().timer.setTimeout(() => { this.timeout = undefined; this.onSuccess(undefined); }, delay >= 0 ? delay : this.defaultDelay); } return this.completionPromise; } forceDelivery() { if (!this.completionPromise) { return undefined; } this.cancelTimeout(); let result = this.task(); this.completionPromise = undefined; this.onSuccess = undefined; this.task = undefined; return result; } isTriggered() { return this.timeout !== void 0; } cancel() { this.cancelTimeout(); this.completionPromise = undefined; } cancelTimeout() { if (this.timeout !== void 0) { vscode_languageserver_protocol_1.RAL().timer.clearTimeout(this.timeout); this.timeout = undefined; } } } exports.Delayer = Delayer; //# sourceMappingURL=async.js.map /***/ }), /***/ 9763: /***/ ((__unused_webpack_module, exports) => { "use strict"; /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.asPromise = exports.thenable = exports.typedArray = exports.stringArray = exports.array = exports.func = exports.error = exports.number = exports.string = exports.boolean = void 0; function boolean(value) { return value === true || value === false; } exports.boolean = boolean; function string(value) { return typeof value === 'string' || value instanceof String; } exports.string = string; function number(value) { return typeof value === 'number' || value instanceof Number; } exports.number = number; function error(value) { return value instanceof Error; } exports.error = error; function func(value) { return typeof value === 'function'; } exports.func = func; function array(value) { return Array.isArray(value); } exports.array = array; function stringArray(value) { return array(value) && value.every(elem => string(elem)); } exports.stringArray = stringArray; function typedArray(value, check) { return Array.isArray(value) && value.every(check); } exports.typedArray = typedArray; function thenable(value) { return value && func(value.then); } exports.thenable = thenable; function asPromise(value) { if (value instanceof Promise) { return value; } else if (thenable(value)) { return new Promise((resolve, reject) => { value.then((resolved) => resolve(resolved), (error) => reject(error)); }); } else { return Promise.resolve(value); } } exports.asPromise = asPromise; //# sourceMappingURL=is.js.map /***/ }), /***/ 1980: /***/ ((__unused_webpack_module, exports) => { "use strict"; /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.generateUuid = exports.parse = exports.isUUID = exports.v4 = exports.empty = void 0; class ValueUUID { constructor(_value) { this._value = _value; // empty } asHex() { return this._value; } equals(other) { return this.asHex() === other.asHex(); } } class V4UUID extends ValueUUID { constructor() { super([ V4UUID._randomHex(), V4UUID._randomHex(), V4UUID._randomHex(), V4UUID._randomHex(), V4UUID._randomHex(), V4UUID._randomHex(), V4UUID._randomHex(), V4UUID._randomHex(), '-', V4UUID._randomHex(), V4UUID._randomHex(), V4UUID._randomHex(), V4UUID._randomHex(), '-', '4', V4UUID._randomHex(), V4UUID._randomHex(), V4UUID._randomHex(), '-', V4UUID._oneOf(V4UUID._timeHighBits), V4UUID._randomHex(), V4UUID._randomHex(), V4UUID._randomHex(), '-', V4UUID._randomHex(), V4UUID._randomHex(), V4UUID._randomHex(), V4UUID._randomHex(), V4UUID._randomHex(), V4UUID._randomHex(), V4UUID._randomHex(), V4UUID._randomHex(), V4UUID._randomHex(), V4UUID._randomHex(), V4UUID._randomHex(), V4UUID._randomHex(), ].join('')); } static _oneOf(array) { return array[Math.floor(array.length * Math.random())]; } static _randomHex() { return V4UUID._oneOf(V4UUID._chars); } } V4UUID._chars = ['0', '1', '2', '3', '4', '5', '6', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']; V4UUID._timeHighBits = ['8', '9', 'a', 'b']; /** * An empty UUID that contains only zeros. */ exports.empty = new ValueUUID('00000000-0000-0000-0000-000000000000'); function v4() { return new V4UUID(); } exports.v4 = v4; const _UUIDPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; function isUUID(value) { return _UUIDPattern.test(value); } exports.isUUID = isUUID; /** * Parses a UUID that is of the format xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx. * @param value A uuid string. */ function parse(value) { if (!isUUID(value)) { throw new Error('invalid uuid'); } return new ValueUUID(value); } exports.parse = parse; function generateUuid() { return v4().asHex(); } exports.generateUuid = generateUuid; //# sourceMappingURL=uuid.js.map /***/ }), /***/ 9565: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.WorkspaceFoldersFeature = exports.arrayDiff = void 0; const UUID = __webpack_require__(1980); const vscode_1 = __webpack_require__(9496); const vscode_languageserver_protocol_1 = __webpack_require__(273); function access(target, key) { if (target === void 0) { return undefined; } return target[key]; } function arrayDiff(left, right) { return left.filter(element => right.indexOf(element) < 0); } exports.arrayDiff = arrayDiff; class WorkspaceFoldersFeature { constructor(_client) { this._client = _client; this._listeners = new Map(); } get registrationType() { return vscode_languageserver_protocol_1.DidChangeWorkspaceFoldersNotification.type; } fillInitializeParams(params) { const folders = vscode_1.workspace.workspaceFolders; this.initializeWithFolders(folders); if (folders === void 0) { params.workspaceFolders = null; } else { params.workspaceFolders = folders.map(folder => this.asProtocol(folder)); } } initializeWithFolders(currentWorkspaceFolders) { this._initialFolders = currentWorkspaceFolders; } fillClientCapabilities(capabilities) { capabilities.workspace = capabilities.workspace || {}; capabilities.workspace.workspaceFolders = true; } initialize(capabilities) { const client = this._client; client.onRequest(vscode_languageserver_protocol_1.WorkspaceFoldersRequest.type, (token) => { const workspaceFolders = () => { const folders = vscode_1.workspace.workspaceFolders; if (folders === undefined) { return null; } const result = folders.map((folder) => { return this.asProtocol(folder); }); return result; }; const middleware = client.clientOptions.middleware.workspace; return middleware && middleware.workspaceFolders ? middleware.workspaceFolders(token, workspaceFolders) : workspaceFolders(token); }); const value = access(access(access(capabilities, 'workspace'), 'workspaceFolders'), 'changeNotifications'); let id; if (typeof value === 'string') { id = value; } else if (value === true) { id = UUID.generateUuid(); } if (id) { this.register({ id: id, registerOptions: undefined }); } } sendInitialEvent(currentWorkspaceFolders) { if (this._initialFolders && currentWorkspaceFolders) { const removed = arrayDiff(this._initialFolders, currentWorkspaceFolders); const added = arrayDiff(currentWorkspaceFolders, this._initialFolders); if (added.length > 0 || removed.length > 0) { this.doSendEvent(added, removed); } } else if (this._initialFolders) { this.doSendEvent([], this._initialFolders); } else if (currentWorkspaceFolders) { this.doSendEvent(currentWorkspaceFolders, []); } } doSendEvent(addedFolders, removedFolders) { let params = { event: { added: addedFolders.map(folder => this.asProtocol(folder)), removed: removedFolders.map(folder => this.asProtocol(folder)) } }; this._client.sendNotification(vscode_languageserver_protocol_1.DidChangeWorkspaceFoldersNotification.type, params); } register(data) { let id = data.id; let client = this._client; let disposable = vscode_1.workspace.onDidChangeWorkspaceFolders((event) => { let didChangeWorkspaceFolders = (event) => { this.doSendEvent(event.added, event.removed); }; let middleware = client.clientOptions.middleware.workspace; middleware && middleware.didChangeWorkspaceFolders ? middleware.didChangeWorkspaceFolders(event, didChangeWorkspaceFolders) : didChangeWorkspaceFolders(event); }); this._listeners.set(id, disposable); this.sendInitialEvent(vscode_1.workspace.workspaceFolders); } unregister(id) { let disposable = this._listeners.get(id); if (disposable === void 0) { return; } this._listeners.delete(id); disposable.dispose(); } dispose() { for (let disposable of this._listeners.values()) { disposable.dispose(); } this._listeners.clear(); } asProtocol(workspaceFolder) { if (workspaceFolder === void 0) { return null; } return { uri: this._client.code2ProtocolConverter.asUri(workspaceFolder.uri), name: workspaceFolder.name }; } } exports.WorkspaceFoldersFeature = WorkspaceFoldersFeature; //# sourceMappingURL=workspaceFolders.js.map /***/ }), /***/ 2850: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __exportStar = (this && this.__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.SettingMonitor = exports.LanguageClient = exports.TransportKind = void 0; const cp = __webpack_require__(2081); const fs = __webpack_require__(7147); const path = __webpack_require__(1017); const SemVer = __webpack_require__(1249); const vscode_1 = __webpack_require__(9496); const Is = __webpack_require__(9763); const commonClient_1 = __webpack_require__(7225); const client_1 = __webpack_require__(4384); const processes_1 = __webpack_require__(794); const node_1 = __webpack_require__(6560); __exportStar(__webpack_require__(6560), exports); __exportStar(__webpack_require__(5734), exports); const REQUIRED_VSCODE_VERSION = '^1.52.0'; // do not change format, updated by `updateVSCode` script var Executable; (function (Executable) { function is(value) { return Is.string(value.command); } Executable.is = is; })(Executable || (Executable = {})); var TransportKind; (function (TransportKind) { TransportKind[TransportKind["stdio"] = 0] = "stdio"; TransportKind[TransportKind["ipc"] = 1] = "ipc"; TransportKind[TransportKind["pipe"] = 2] = "pipe"; TransportKind[TransportKind["socket"] = 3] = "socket"; })(TransportKind = exports.TransportKind || (exports.TransportKind = {})); var Transport; (function (Transport) { function isSocket(value) { let candidate = value; return candidate && candidate.kind === TransportKind.socket && Is.number(candidate.port); } Transport.isSocket = isSocket; })(Transport || (Transport = {})); var NodeModule; (function (NodeModule) { function is(value) { return Is.string(value.module); } NodeModule.is = is; })(NodeModule || (NodeModule = {})); var StreamInfo; (function (StreamInfo) { function is(value) { let candidate = value; return candidate && candidate.writer !== void 0 && candidate.reader !== void 0; } StreamInfo.is = is; })(StreamInfo || (StreamInfo = {})); var ChildProcessInfo; (function (ChildProcessInfo) { function is(value) { let candidate = value; return candidate && candidate.process !== void 0 && typeof candidate.detached === 'boolean'; } ChildProcessInfo.is = is; })(ChildProcessInfo || (ChildProcessInfo = {})); class LanguageClient extends commonClient_1.CommonLanguageClient { constructor(arg1, arg2, arg3, arg4, arg5) { let id; let name; let serverOptions; let clientOptions; let forceDebug; if (Is.string(arg2)) { id = arg1; name = arg2; serverOptions = arg3; clientOptions = arg4; forceDebug = !!arg5; } else { id = arg1.toLowerCase(); name = arg1; serverOptions = arg2; clientOptions = arg3; forceDebug = arg4; } if (forceDebug === void 0) { forceDebug = false; } super(id, name, clientOptions); this._serverOptions = serverOptions; this._forceDebug = forceDebug; try { this.checkVersion(); } catch (error) { if (Is.string(error.message)) { this.outputChannel.appendLine(error.message); } throw error; } } checkVersion() { let codeVersion = SemVer.parse(vscode_1.version); if (!codeVersion) { throw new Error(`No valid VS Code version detected. Version string is: ${vscode_1.version}`); } // Remove the insider pre-release since we stay API compatible. if (codeVersion.prerelease && codeVersion.prerelease.length > 0) { codeVersion.prerelease = []; } if (!SemVer.satisfies(codeVersion, REQUIRED_VSCODE_VERSION)) { throw new Error(`The language client requires VS Code version ${REQUIRED_VSCODE_VERSION} but received version ${vscode_1.version}`); } } stop() { return super.stop().then(() => { if (this._serverProcess) { let toCheck = this._serverProcess; this._serverProcess = undefined; if (this._isDetached === void 0 || !this._isDetached) { this.checkProcessDied(toCheck); } this._isDetached = undefined; } }); } checkProcessDied(childProcess) { if (!childProcess) { return; } setTimeout(() => { // Test if the process is still alive. Throws an exception if not try { process.kill(childProcess.pid, 0); processes_1.terminate(childProcess); } catch (error) { // All is fine. } }, 2000); } handleConnectionClosed() { this._serverProcess = undefined; super.handleConnectionClosed(); } fillInitializeParams(params) { super.fillInitializeParams(params); if (params.processId === null) { params.processId = process.pid; } } createMessageTransports(encoding) { function getEnvironment(env, fork) { if (!env && !fork) { return undefined; } let result = Object.create(null); Object.keys(process.env).forEach(key => result[key] = process.env[key]); if (fork) { result['ELECTRON_RUN_AS_NODE'] = '1'; result['ELECTRON_NO_ASAR'] = '1'; } if (env) { Object.keys(env).forEach(key => result[key] = env[key]); } return result; } const debugStartWith = ['--debug=', '--debug-brk=', '--inspect=', '--inspect-brk=']; const debugEquals = ['--debug', '--debug-brk', '--inspect', '--inspect-brk']; function startedInDebugMode() { let args = process.execArgv; if (args) { return args.some((arg) => { return debugStartWith.some(value => arg.startsWith(value)) || debugEquals.some(value => arg === value); }); } return false; } function assertStdio(process) { if (process.stdin === null || process.stdout === null || process.stderr === null) { throw new Error('Process created without stdio streams'); } } let server = this._serverOptions; // We got a function. if (Is.func(server)) { return server().then((result) => { if (client_1.MessageTransports.is(result)) { this._isDetached = !!result.detached; return result; } else if (StreamInfo.is(result)) { this._isDetached = !!result.detached; return { reader: new node_1.StreamMessageReader(result.reader), writer: new node_1.StreamMessageWriter(result.writer) }; } else { let cp; if (ChildProcessInfo.is(result)) { cp = result.process; this._isDetached = result.detached; } else { cp = result; this._isDetached = false; } cp.stderr.on('data', data => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding))); return { reader: new node_1.StreamMessageReader(cp.stdout), writer: new node_1.StreamMessageWriter(cp.stdin) }; } }); } let json; let runDebug = server; if (runDebug.run || runDebug.debug) { if (this._forceDebug || startedInDebugMode()) { json = runDebug.debug; } else { json = runDebug.run; } } else { json = server; } return this._getServerWorkingDir(json.options).then(serverWorkingDir => { if (NodeModule.is(json) && json.module) { let node = json; let transport = node.transport || TransportKind.stdio; if (node.runtime) { let args = []; let options = node.options || Object.create(null); if (options.execArgv) { options.execArgv.forEach(element => args.push(element)); } args.push(node.module); if (node.args) { node.args.forEach(element => args.push(element)); } const execOptions = Object.create(null); execOptions.cwd = serverWorkingDir; execOptions.env = getEnvironment(options.env, false); const runtime = this._getRuntimePath(node.runtime, serverWorkingDir); let pipeName = undefined; if (transport === TransportKind.ipc) { // exec options not correctly typed in lib execOptions.stdio = [null, null, null, 'ipc']; args.push('--node-ipc'); } else if (transport === TransportKind.stdio) { args.push('--stdio'); } else if (transport === TransportKind.pipe) { pipeName = node_1.generateRandomPipeName(); args.push(`--pipe=${pipeName}`); } else if (Transport.isSocket(transport)) { args.push(`--socket=${transport.port}`); } args.push(`--clientProcessId=${process.pid.toString()}`); if (transport === TransportKind.ipc || transport === TransportKind.stdio) { let serverProcess = cp.spawn(runtime, args, execOptions); if (!serverProcess || !serverProcess.pid) { return Promise.reject(`Launching server using runtime ${runtime} failed.`); } this._serverProcess = serverProcess; serverProcess.stderr.on('data', data => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding))); if (transport === TransportKind.ipc) { serverProcess.stdout.on('data', data => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding))); return Promise.resolve({ reader: new node_1.IPCMessageReader(serverProcess), writer: new node_1.IPCMessageWriter(serverProcess) }); } else { return Promise.resolve({ reader: new node_1.StreamMessageReader(serverProcess.stdout), writer: new node_1.StreamMessageWriter(serverProcess.stdin) }); } } else if (transport === TransportKind.pipe) { return node_1.createClientPipeTransport(pipeName).then((transport) => { let process = cp.spawn(runtime, args, execOptions); if (!process || !process.pid) { return Promise.reject(`Launching server using runtime ${runtime} failed.`); } this._serverProcess = process; process.stderr.on('data', data => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding))); process.stdout.on('data', data => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding))); return transport.onConnected().then((protocol) => { return { reader: protocol[0], writer: protocol[1] }; }); }); } else if (Transport.isSocket(transport)) { return node_1.createClientSocketTransport(transport.port).then((transport) => { let process = cp.spawn(runtime, args, execOptions); if (!process || !process.pid) { return Promise.reject(`Launching server using runtime ${runtime} failed.`); } this._serverProcess = process; process.stderr.on('data', data => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding))); process.stdout.on('data', data => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding))); return transport.onConnected().then((protocol) => { return { reader: protocol[0], writer: protocol[1] }; }); }); } } else { let pipeName = undefined; return new Promise((resolve, _reject) => { let args = node.args && node.args.slice() || []; if (transport === TransportKind.ipc) { args.push('--node-ipc'); } else if (transport === TransportKind.stdio) { args.push('--stdio'); } else if (transport === TransportKind.pipe) { pipeName = node_1.generateRandomPipeName(); args.push(`--pipe=${pipeName}`); } else if (Transport.isSocket(transport)) { args.push(`--socket=${transport.port}`); } args.push(`--clientProcessId=${process.pid.toString()}`); let options = node.options || Object.create(null); options.env = getEnvironment(options.env, true); options.execArgv = options.execArgv || []; options.cwd = serverWorkingDir; options.silent = true; if (transport === TransportKind.ipc || transport === TransportKind.stdio) { let sp = cp.fork(node.module, args || [], options); assertStdio(sp); this._serverProcess = sp; sp.stderr.on('data', data => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding))); if (transport === TransportKind.ipc) { sp.stdout.on('data', data => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding))); resolve({ reader: new node_1.IPCMessageReader(this._serverProcess), writer: new node_1.IPCMessageWriter(this._serverProcess) }); } else { resolve({ reader: new node_1.StreamMessageReader(sp.stdout), writer: new node_1.StreamMessageWriter(sp.stdin) }); } } else if (transport === TransportKind.pipe) { node_1.createClientPipeTransport(pipeName).then((transport) => { let sp = cp.fork(node.module, args || [], options); assertStdio(sp); this._serverProcess = sp; sp.stderr.on('data', data => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding))); sp.stdout.on('data', data => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding))); transport.onConnected().then((protocol) => { resolve({ reader: protocol[0], writer: protocol[1] }); }); }); } else if (Transport.isSocket(transport)) { node_1.createClientSocketTransport(transport.port).then((transport) => { let sp = cp.fork(node.module, args || [], options); assertStdio(sp); this._serverProcess = sp; sp.stderr.on('data', data => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding))); sp.stdout.on('data', data => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding))); transport.onConnected().then((protocol) => { resolve({ reader: protocol[0], writer: protocol[1] }); }); }); } }); } } else if (Executable.is(json) && json.command) { let command = json; let args = command.args || []; let options = Object.assign({}, command.options); options.cwd = options.cwd || serverWorkingDir; let serverProcess = cp.spawn(command.command, args, options); if (!serverProcess || !serverProcess.pid) { return Promise.reject(`Launching server using command ${command.command} failed.`); } serverProcess.stderr.on('data', data => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding))); this._serverProcess = serverProcess; this._isDetached = !!options.detached; return Promise.resolve({ reader: new node_1.StreamMessageReader(serverProcess.stdout), writer: new node_1.StreamMessageWriter(serverProcess.stdin) }); } return Promise.reject(new Error(`Unsupported server configuration ` + JSON.stringify(server, null, 4))); }); } _getRuntimePath(runtime, serverWorkingDirectory) { if (path.isAbsolute(runtime)) { return runtime; } const mainRootPath = this._mainGetRootPath(); if (mainRootPath !== undefined) { const result = path.join(mainRootPath, runtime); if (fs.existsSync(result)) { return result; } } if (serverWorkingDirectory !== undefined) { const result = path.join(serverWorkingDirectory, runtime); if (fs.existsSync(result)) { return result; } } return runtime; } _mainGetRootPath() { let folders = vscode_1.workspace.workspaceFolders; if (!folders || folders.length === 0) { return undefined; } let folder = folders[0]; if (folder.uri.scheme === 'file') { return folder.uri.fsPath; } return undefined; } _getServerWorkingDir(options) { let cwd = options && options.cwd; if (!cwd) { cwd = this.clientOptions.workspaceFolder ? this.clientOptions.workspaceFolder.uri.fsPath : this._mainGetRootPath(); } if (cwd) { // make sure the folder exists otherwise creating the process will fail return new Promise(s => { fs.lstat(cwd, (err, stats) => { s(!err && stats.isDirectory() ? cwd : undefined); }); }); } return Promise.resolve(undefined); } getLocale() { const envValue = process.env['VSCODE_NLS_CONFIG']; if (envValue === undefined) { return 'en'; } let config = undefined; try { config = JSON.parse(envValue); } catch (err) { } if (config === undefined || typeof config.locale !== 'string') { return 'en'; } return config.locale; } } exports.LanguageClient = LanguageClient; class SettingMonitor { constructor(_client, _setting) { this._client = _client; this._setting = _setting; this._listeners = []; } start() { vscode_1.workspace.onDidChangeConfiguration(this.onDidChangeConfiguration, this, this._listeners); this.onDidChangeConfiguration(); return new vscode_1.Disposable(() => { if (this._client.needsStop()) { this._client.stop(); } }); } onDidChangeConfiguration() { let index = this._setting.indexOf('.'); let primary = index >= 0 ? this._setting.substr(0, index) : this._setting; let rest = index >= 0 ? this._setting.substr(index + 1) : undefined; let enabled = rest ? vscode_1.workspace.getConfiguration(primary).get(rest, false) : vscode_1.workspace.getConfiguration(primary); if (enabled && this._client.needsStart()) { this._client.start(); } else if (!enabled && this._client.needsStop()) { this._client.stop(); } } } exports.SettingMonitor = SettingMonitor; //# sourceMappingURL=main.js.map /***/ }), /***/ 794: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.terminate = void 0; const cp = __webpack_require__(2081); const path_1 = __webpack_require__(1017); const isWindows = (process.platform === 'win32'); const isMacintosh = (process.platform === 'darwin'); const isLinux = (process.platform === 'linux'); function terminate(process, cwd) { if (isWindows) { try { // This we run in Atom execFileSync is available. // Ignore stderr since this is otherwise piped to parent.stderr // which might be already closed. let options = { stdio: ['pipe', 'pipe', 'ignore'] }; if (cwd) { options.cwd = cwd; } cp.execFileSync('taskkill', ['/T', '/F', '/PID', process.pid.toString()], options); return true; } catch (err) { return false; } } else if (isLinux || isMacintosh) { try { var cmd = path_1.join(__dirname, 'terminateProcess.sh'); var result = cp.spawnSync(cmd, [process.pid.toString()]); return result.error ? false : true; } catch (err) { return false; } } else { process.kill('SIGKILL'); return true; } } exports.terminate = terminate; //# sourceMappingURL=processes.js.map /***/ }), /***/ 2847: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ----------------------------------------------------------------------------------------- */ module.exports = __webpack_require__(2850); /***/ }), /***/ 1661: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __exportStar = (this && this.__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.LSPErrorCodes = exports.createProtocolConnection = void 0; __exportStar(__webpack_require__(4389), exports); __exportStar(__webpack_require__(1674), exports); __exportStar(__webpack_require__(6140), exports); __exportStar(__webpack_require__(542), exports); var connection_1 = __webpack_require__(3767); Object.defineProperty(exports, "createProtocolConnection", ({ enumerable: true, get: function () { return connection_1.createProtocolConnection; } })); var LSPErrorCodes; (function (LSPErrorCodes) { /** * This is the start range of LSP reserved error codes. * It doesn't denote a real error code. * * @since 3.16.0 */ LSPErrorCodes.lspReservedErrorRangeStart = -32899; LSPErrorCodes.ContentModified = -32801; LSPErrorCodes.RequestCancelled = -32800; /** * This is the end range of LSP reserved error codes. * It doesn't denote a real error code. * * @since 3.16.0 */ LSPErrorCodes.lspReservedErrorRangeEnd = -32800; })(LSPErrorCodes = exports.LSPErrorCodes || (exports.LSPErrorCodes = {})); //# sourceMappingURL=api.js.map /***/ }), /***/ 3767: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createProtocolConnection = void 0; const vscode_jsonrpc_1 = __webpack_require__(4389); function createProtocolConnection(input, output, logger, options) { if (vscode_jsonrpc_1.ConnectionStrategy.is(options)) { options = { connectionStrategy: options }; } return vscode_jsonrpc_1.createMessageConnection(input, output, logger, options); } exports.createProtocolConnection = createProtocolConnection; //# sourceMappingURL=connection.js.map /***/ }), /***/ 6140: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ProtocolNotificationType = exports.ProtocolNotificationType0 = exports.ProtocolRequestType = exports.ProtocolRequestType0 = exports.RegistrationType = void 0; const vscode_jsonrpc_1 = __webpack_require__(4389); class RegistrationType { constructor(method) { this.method = method; } } exports.RegistrationType = RegistrationType; class ProtocolRequestType0 extends vscode_jsonrpc_1.RequestType0 { constructor(method) { super(method); } } exports.ProtocolRequestType0 = ProtocolRequestType0; class ProtocolRequestType extends vscode_jsonrpc_1.RequestType { constructor(method) { super(method, vscode_jsonrpc_1.ParameterStructures.byName); } } exports.ProtocolRequestType = ProtocolRequestType; class ProtocolNotificationType0 extends vscode_jsonrpc_1.NotificationType0 { constructor(method) { super(method); } } exports.ProtocolNotificationType0 = ProtocolNotificationType0; class ProtocolNotificationType extends vscode_jsonrpc_1.NotificationType { constructor(method) { super(method, vscode_jsonrpc_1.ParameterStructures.byName); } } exports.ProtocolNotificationType = ProtocolNotificationType; // let x: ProtocolNotificationType; // let y: ProtocolNotificationType; // x = y; //# sourceMappingURL=messages.js.map /***/ }), /***/ 2918: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* -------------------------------------------------------------------------------------------- * Copyright (c) TypeFox and others. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CallHierarchyOutgoingCallsRequest = exports.CallHierarchyIncomingCallsRequest = exports.CallHierarchyPrepareRequest = void 0; const messages_1 = __webpack_require__(6140); /** * A request to result a `CallHierarchyItem` in a document at a given position. * Can be used as an input to a incoming or outgoing call hierarchy. * * @since 3.16.0 */ var CallHierarchyPrepareRequest; (function (CallHierarchyPrepareRequest) { CallHierarchyPrepareRequest.method = 'textDocument/prepareCallHierarchy'; CallHierarchyPrepareRequest.type = new messages_1.ProtocolRequestType(CallHierarchyPrepareRequest.method); })(CallHierarchyPrepareRequest = exports.CallHierarchyPrepareRequest || (exports.CallHierarchyPrepareRequest = {})); /** * A request to resolve the incoming calls for a given `CallHierarchyItem`. * * @since 3.16.0 */ var CallHierarchyIncomingCallsRequest; (function (CallHierarchyIncomingCallsRequest) { CallHierarchyIncomingCallsRequest.method = 'callHierarchy/incomingCalls'; CallHierarchyIncomingCallsRequest.type = new messages_1.ProtocolRequestType(CallHierarchyIncomingCallsRequest.method); })(CallHierarchyIncomingCallsRequest = exports.CallHierarchyIncomingCallsRequest || (exports.CallHierarchyIncomingCallsRequest = {})); /** * A request to resolve the outgoing calls for a given `CallHierarchyItem`. * * @since 3.16.0 */ var CallHierarchyOutgoingCallsRequest; (function (CallHierarchyOutgoingCallsRequest) { CallHierarchyOutgoingCallsRequest.method = 'callHierarchy/outgoingCalls'; CallHierarchyOutgoingCallsRequest.type = new messages_1.ProtocolRequestType(CallHierarchyOutgoingCallsRequest.method); })(CallHierarchyOutgoingCallsRequest = exports.CallHierarchyOutgoingCallsRequest || (exports.CallHierarchyOutgoingCallsRequest = {})); //# sourceMappingURL=protocol.callHierarchy.js.map /***/ }), /***/ 9891: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ColorPresentationRequest = exports.DocumentColorRequest = void 0; const messages_1 = __webpack_require__(6140); /** * A request to list all color symbols found in a given text document. The request's * parameter is of type [DocumentColorParams](#DocumentColorParams) the * response is of type [ColorInformation[]](#ColorInformation) or a Thenable * that resolves to such. */ var DocumentColorRequest; (function (DocumentColorRequest) { DocumentColorRequest.method = 'textDocument/documentColor'; DocumentColorRequest.type = new messages_1.ProtocolRequestType(DocumentColorRequest.method); })(DocumentColorRequest = exports.DocumentColorRequest || (exports.DocumentColorRequest = {})); /** * A request to list all presentation for a color. The request's * parameter is of type [ColorPresentationParams](#ColorPresentationParams) the * response is of type [ColorInformation[]](#ColorInformation) or a Thenable * that resolves to such. */ var ColorPresentationRequest; (function (ColorPresentationRequest) { ColorPresentationRequest.type = new messages_1.ProtocolRequestType('textDocument/colorPresentation'); })(ColorPresentationRequest = exports.ColorPresentationRequest || (exports.ColorPresentationRequest = {})); //# sourceMappingURL=protocol.colorProvider.js.map /***/ }), /***/ 5934: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ConfigurationRequest = void 0; const messages_1 = __webpack_require__(6140); /** * The 'workspace/configuration' request is sent from the server to the client to fetch a certain * configuration setting. * * This pull model replaces the old push model were the client signaled configuration change via an * event. If the server still needs to react to configuration changes (since the server caches the * result of `workspace/configuration` requests) the server should register for an empty configuration * change event and empty the cache if such an event is received. */ var ConfigurationRequest; (function (ConfigurationRequest) { ConfigurationRequest.type = new messages_1.ProtocolRequestType('workspace/configuration'); })(ConfigurationRequest = exports.ConfigurationRequest || (exports.ConfigurationRequest = {})); //# sourceMappingURL=protocol.configuration.js.map /***/ }), /***/ 764: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DeclarationRequest = void 0; const messages_1 = __webpack_require__(6140); // @ts-ignore: to avoid inlining LocatioLink as dynamic import let __noDynamicImport; /** * A request to resolve the type definition locations of a symbol at a given text * document position. The request's parameter is of type [TextDocumentPositioParams] * (#TextDocumentPositionParams) the response is of type [Declaration](#Declaration) * or a typed array of [DeclarationLink](#DeclarationLink) or a Thenable that resolves * to such. */ var DeclarationRequest; (function (DeclarationRequest) { DeclarationRequest.method = 'textDocument/declaration'; DeclarationRequest.type = new messages_1.ProtocolRequestType(DeclarationRequest.method); })(DeclarationRequest = exports.DeclarationRequest || (exports.DeclarationRequest = {})); //# sourceMappingURL=protocol.declaration.js.map /***/ }), /***/ 7846: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.WillDeleteFilesRequest = exports.DidDeleteFilesNotification = exports.DidRenameFilesNotification = exports.WillRenameFilesRequest = exports.DidCreateFilesNotification = exports.WillCreateFilesRequest = exports.FileOperationPatternKind = void 0; const messages_1 = __webpack_require__(6140); /** * A pattern kind describing if a glob pattern matches a file a folder or * both. * * @since 3.16.0 */ var FileOperationPatternKind; (function (FileOperationPatternKind) { /** * The pattern matches a file only. */ FileOperationPatternKind.file = 'file'; /** * The pattern matches a folder only. */ FileOperationPatternKind.folder = 'folder'; })(FileOperationPatternKind = exports.FileOperationPatternKind || (exports.FileOperationPatternKind = {})); /** * The will create files request is sent from the client to the server before files are actually * created as long as the creation is triggered from within the client. * * @since 3.16.0 */ var WillCreateFilesRequest; (function (WillCreateFilesRequest) { WillCreateFilesRequest.method = 'workspace/willCreateFiles'; WillCreateFilesRequest.type = new messages_1.ProtocolRequestType(WillCreateFilesRequest.method); })(WillCreateFilesRequest = exports.WillCreateFilesRequest || (exports.WillCreateFilesRequest = {})); /** * The did create files notification is sent from the client to the server when * files were created from within the client. * * @since 3.16.0 */ var DidCreateFilesNotification; (function (DidCreateFilesNotification) { DidCreateFilesNotification.method = 'workspace/didCreateFiles'; DidCreateFilesNotification.type = new messages_1.ProtocolNotificationType(DidCreateFilesNotification.method); })(DidCreateFilesNotification = exports.DidCreateFilesNotification || (exports.DidCreateFilesNotification = {})); /** * The will rename files request is sent from the client to the server before files are actually * renamed as long as the rename is triggered from within the client. * * @since 3.16.0 */ var WillRenameFilesRequest; (function (WillRenameFilesRequest) { WillRenameFilesRequest.method = 'workspace/willRenameFiles'; WillRenameFilesRequest.type = new messages_1.ProtocolRequestType(WillRenameFilesRequest.method); })(WillRenameFilesRequest = exports.WillRenameFilesRequest || (exports.WillRenameFilesRequest = {})); /** * The did rename files notification is sent from the client to the server when * files were renamed from within the client. * * @since 3.16.0 */ var DidRenameFilesNotification; (function (DidRenameFilesNotification) { DidRenameFilesNotification.method = 'workspace/didRenameFiles'; DidRenameFilesNotification.type = new messages_1.ProtocolNotificationType(DidRenameFilesNotification.method); })(DidRenameFilesNotification = exports.DidRenameFilesNotification || (exports.DidRenameFilesNotification = {})); /** * The will delete files request is sent from the client to the server before files are actually * deleted as long as the deletion is triggered from within the client. * * @since 3.16.0 */ var DidDeleteFilesNotification; (function (DidDeleteFilesNotification) { DidDeleteFilesNotification.method = 'workspace/didDeleteFiles'; DidDeleteFilesNotification.type = new messages_1.ProtocolNotificationType(DidDeleteFilesNotification.method); })(DidDeleteFilesNotification = exports.DidDeleteFilesNotification || (exports.DidDeleteFilesNotification = {})); /** * The did delete files notification is sent from the client to the server when * files were deleted from within the client. * * @since 3.16.0 */ var WillDeleteFilesRequest; (function (WillDeleteFilesRequest) { WillDeleteFilesRequest.method = 'workspace/willDeleteFiles'; WillDeleteFilesRequest.type = new messages_1.ProtocolRequestType(WillDeleteFilesRequest.method); })(WillDeleteFilesRequest = exports.WillDeleteFilesRequest || (exports.WillDeleteFilesRequest = {})); //# sourceMappingURL=protocol.fileOperations.js.map /***/ }), /***/ 3394: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.FoldingRangeRequest = exports.FoldingRangeKind = void 0; const messages_1 = __webpack_require__(6140); /** * Enum of known range kinds */ var FoldingRangeKind; (function (FoldingRangeKind) { /** * Folding range for a comment */ FoldingRangeKind["Comment"] = "comment"; /** * Folding range for a imports or includes */ FoldingRangeKind["Imports"] = "imports"; /** * Folding range for a region (e.g. `#region`) */ FoldingRangeKind["Region"] = "region"; })(FoldingRangeKind = exports.FoldingRangeKind || (exports.FoldingRangeKind = {})); /** * A request to provide folding ranges in a document. The request's * parameter is of type [FoldingRangeParams](#FoldingRangeParams), the * response is of type [FoldingRangeList](#FoldingRangeList) or a Thenable * that resolves to such. */ var FoldingRangeRequest; (function (FoldingRangeRequest) { FoldingRangeRequest.method = 'textDocument/foldingRange'; FoldingRangeRequest.type = new messages_1.ProtocolRequestType(FoldingRangeRequest.method); })(FoldingRangeRequest = exports.FoldingRangeRequest || (exports.FoldingRangeRequest = {})); //# sourceMappingURL=protocol.foldingRange.js.map /***/ }), /***/ 2122: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ImplementationRequest = void 0; const messages_1 = __webpack_require__(6140); // @ts-ignore: to avoid inlining LocatioLink as dynamic import let __noDynamicImport; /** * A request to resolve the implementation locations of a symbol at a given text * document position. The request's parameter is of type [TextDocumentPositioParams] * (#TextDocumentPositionParams) the response is of type [Definition](#Definition) or a * Thenable that resolves to such. */ var ImplementationRequest; (function (ImplementationRequest) { ImplementationRequest.method = 'textDocument/implementation'; ImplementationRequest.type = new messages_1.ProtocolRequestType(ImplementationRequest.method); })(ImplementationRequest = exports.ImplementationRequest || (exports.ImplementationRequest = {})); //# sourceMappingURL=protocol.implementation.js.map /***/ }), /***/ 542: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DocumentLinkRequest = exports.CodeLensRefreshRequest = exports.CodeLensResolveRequest = exports.CodeLensRequest = exports.WorkspaceSymbolRequest = exports.CodeActionResolveRequest = exports.CodeActionRequest = exports.DocumentSymbolRequest = exports.DocumentHighlightRequest = exports.ReferencesRequest = exports.DefinitionRequest = exports.SignatureHelpRequest = exports.SignatureHelpTriggerKind = exports.HoverRequest = exports.CompletionResolveRequest = exports.CompletionRequest = exports.CompletionTriggerKind = exports.PublishDiagnosticsNotification = exports.WatchKind = exports.FileChangeType = exports.DidChangeWatchedFilesNotification = exports.WillSaveTextDocumentWaitUntilRequest = exports.WillSaveTextDocumentNotification = exports.TextDocumentSaveReason = exports.DidSaveTextDocumentNotification = exports.DidCloseTextDocumentNotification = exports.DidChangeTextDocumentNotification = exports.TextDocumentContentChangeEvent = exports.DidOpenTextDocumentNotification = exports.TextDocumentSyncKind = exports.TelemetryEventNotification = exports.LogMessageNotification = exports.ShowMessageRequest = exports.ShowMessageNotification = exports.MessageType = exports.DidChangeConfigurationNotification = exports.ExitNotification = exports.ShutdownRequest = exports.InitializedNotification = exports.InitializeError = exports.InitializeRequest = exports.WorkDoneProgressOptions = exports.TextDocumentRegistrationOptions = exports.StaticRegistrationOptions = exports.FailureHandlingKind = exports.ResourceOperationKind = exports.UnregistrationRequest = exports.RegistrationRequest = exports.DocumentSelector = exports.DocumentFilter = void 0; exports.MonikerRequest = exports.MonikerKind = exports.UniquenessLevel = exports.WillDeleteFilesRequest = exports.DidDeleteFilesNotification = exports.WillRenameFilesRequest = exports.DidRenameFilesNotification = exports.WillCreateFilesRequest = exports.DidCreateFilesNotification = exports.FileOperationPatternKind = exports.LinkedEditingRangeRequest = exports.ShowDocumentRequest = exports.SemanticTokensRegistrationType = exports.SemanticTokensRefreshRequest = exports.SemanticTokensRangeRequest = exports.SemanticTokensDeltaRequest = exports.SemanticTokensRequest = exports.TokenFormat = exports.SemanticTokens = exports.SemanticTokenModifiers = exports.SemanticTokenTypes = exports.CallHierarchyPrepareRequest = exports.CallHierarchyOutgoingCallsRequest = exports.CallHierarchyIncomingCallsRequest = exports.WorkDoneProgressCancelNotification = exports.WorkDoneProgressCreateRequest = exports.WorkDoneProgress = exports.SelectionRangeRequest = exports.DeclarationRequest = exports.FoldingRangeRequest = exports.ColorPresentationRequest = exports.DocumentColorRequest = exports.ConfigurationRequest = exports.DidChangeWorkspaceFoldersNotification = exports.WorkspaceFoldersRequest = exports.TypeDefinitionRequest = exports.ImplementationRequest = exports.ApplyWorkspaceEditRequest = exports.ExecuteCommandRequest = exports.PrepareRenameRequest = exports.RenameRequest = exports.PrepareSupportDefaultBehavior = exports.DocumentOnTypeFormattingRequest = exports.DocumentRangeFormattingRequest = exports.DocumentFormattingRequest = exports.DocumentLinkResolveRequest = void 0; const Is = __webpack_require__(9533); const messages_1 = __webpack_require__(6140); const protocol_implementation_1 = __webpack_require__(2122); Object.defineProperty(exports, "ImplementationRequest", ({ enumerable: true, get: function () { return protocol_implementation_1.ImplementationRequest; } })); const protocol_typeDefinition_1 = __webpack_require__(1589); Object.defineProperty(exports, "TypeDefinitionRequest", ({ enumerable: true, get: function () { return protocol_typeDefinition_1.TypeDefinitionRequest; } })); const protocol_workspaceFolders_1 = __webpack_require__(3589); Object.defineProperty(exports, "WorkspaceFoldersRequest", ({ enumerable: true, get: function () { return protocol_workspaceFolders_1.WorkspaceFoldersRequest; } })); Object.defineProperty(exports, "DidChangeWorkspaceFoldersNotification", ({ enumerable: true, get: function () { return protocol_workspaceFolders_1.DidChangeWorkspaceFoldersNotification; } })); const protocol_configuration_1 = __webpack_require__(5934); Object.defineProperty(exports, "ConfigurationRequest", ({ enumerable: true, get: function () { return protocol_configuration_1.ConfigurationRequest; } })); const protocol_colorProvider_1 = __webpack_require__(9891); Object.defineProperty(exports, "DocumentColorRequest", ({ enumerable: true, get: function () { return protocol_colorProvider_1.DocumentColorRequest; } })); Object.defineProperty(exports, "ColorPresentationRequest", ({ enumerable: true, get: function () { return protocol_colorProvider_1.ColorPresentationRequest; } })); const protocol_foldingRange_1 = __webpack_require__(3394); Object.defineProperty(exports, "FoldingRangeRequest", ({ enumerable: true, get: function () { return protocol_foldingRange_1.FoldingRangeRequest; } })); const protocol_declaration_1 = __webpack_require__(764); Object.defineProperty(exports, "DeclarationRequest", ({ enumerable: true, get: function () { return protocol_declaration_1.DeclarationRequest; } })); const protocol_selectionRange_1 = __webpack_require__(5206); Object.defineProperty(exports, "SelectionRangeRequest", ({ enumerable: true, get: function () { return protocol_selectionRange_1.SelectionRangeRequest; } })); const protocol_progress_1 = __webpack_require__(1862); Object.defineProperty(exports, "WorkDoneProgress", ({ enumerable: true, get: function () { return protocol_progress_1.WorkDoneProgress; } })); Object.defineProperty(exports, "WorkDoneProgressCreateRequest", ({ enumerable: true, get: function () { return protocol_progress_1.WorkDoneProgressCreateRequest; } })); Object.defineProperty(exports, "WorkDoneProgressCancelNotification", ({ enumerable: true, get: function () { return protocol_progress_1.WorkDoneProgressCancelNotification; } })); const protocol_callHierarchy_1 = __webpack_require__(2918); Object.defineProperty(exports, "CallHierarchyIncomingCallsRequest", ({ enumerable: true, get: function () { return protocol_callHierarchy_1.CallHierarchyIncomingCallsRequest; } })); Object.defineProperty(exports, "CallHierarchyOutgoingCallsRequest", ({ enumerable: true, get: function () { return protocol_callHierarchy_1.CallHierarchyOutgoingCallsRequest; } })); Object.defineProperty(exports, "CallHierarchyPrepareRequest", ({ enumerable: true, get: function () { return protocol_callHierarchy_1.CallHierarchyPrepareRequest; } })); const protocol_semanticTokens_1 = __webpack_require__(9434); Object.defineProperty(exports, "SemanticTokenTypes", ({ enumerable: true, get: function () { return protocol_semanticTokens_1.SemanticTokenTypes; } })); Object.defineProperty(exports, "SemanticTokenModifiers", ({ enumerable: true, get: function () { return protocol_semanticTokens_1.SemanticTokenModifiers; } })); Object.defineProperty(exports, "SemanticTokens", ({ enumerable: true, get: function () { return protocol_semanticTokens_1.SemanticTokens; } })); Object.defineProperty(exports, "TokenFormat", ({ enumerable: true, get: function () { return protocol_semanticTokens_1.TokenFormat; } })); Object.defineProperty(exports, "SemanticTokensRequest", ({ enumerable: true, get: function () { return protocol_semanticTokens_1.SemanticTokensRequest; } })); Object.defineProperty(exports, "SemanticTokensDeltaRequest", ({ enumerable: true, get: function () { return protocol_semanticTokens_1.SemanticTokensDeltaRequest; } })); Object.defineProperty(exports, "SemanticTokensRangeRequest", ({ enumerable: true, get: function () { return protocol_semanticTokens_1.SemanticTokensRangeRequest; } })); Object.defineProperty(exports, "SemanticTokensRefreshRequest", ({ enumerable: true, get: function () { return protocol_semanticTokens_1.SemanticTokensRefreshRequest; } })); Object.defineProperty(exports, "SemanticTokensRegistrationType", ({ enumerable: true, get: function () { return protocol_semanticTokens_1.SemanticTokensRegistrationType; } })); const protocol_showDocument_1 = __webpack_require__(5726); Object.defineProperty(exports, "ShowDocumentRequest", ({ enumerable: true, get: function () { return protocol_showDocument_1.ShowDocumentRequest; } })); const protocol_linkedEditingRange_1 = __webpack_require__(6305); Object.defineProperty(exports, "LinkedEditingRangeRequest", ({ enumerable: true, get: function () { return protocol_linkedEditingRange_1.LinkedEditingRangeRequest; } })); const protocol_fileOperations_1 = __webpack_require__(7846); Object.defineProperty(exports, "FileOperationPatternKind", ({ enumerable: true, get: function () { return protocol_fileOperations_1.FileOperationPatternKind; } })); Object.defineProperty(exports, "DidCreateFilesNotification", ({ enumerable: true, get: function () { return protocol_fileOperations_1.DidCreateFilesNotification; } })); Object.defineProperty(exports, "WillCreateFilesRequest", ({ enumerable: true, get: function () { return protocol_fileOperations_1.WillCreateFilesRequest; } })); Object.defineProperty(exports, "DidRenameFilesNotification", ({ enumerable: true, get: function () { return protocol_fileOperations_1.DidRenameFilesNotification; } })); Object.defineProperty(exports, "WillRenameFilesRequest", ({ enumerable: true, get: function () { return protocol_fileOperations_1.WillRenameFilesRequest; } })); Object.defineProperty(exports, "DidDeleteFilesNotification", ({ enumerable: true, get: function () { return protocol_fileOperations_1.DidDeleteFilesNotification; } })); Object.defineProperty(exports, "WillDeleteFilesRequest", ({ enumerable: true, get: function () { return protocol_fileOperations_1.WillDeleteFilesRequest; } })); const protocol_moniker_1 = __webpack_require__(3443); Object.defineProperty(exports, "UniquenessLevel", ({ enumerable: true, get: function () { return protocol_moniker_1.UniquenessLevel; } })); Object.defineProperty(exports, "MonikerKind", ({ enumerable: true, get: function () { return protocol_moniker_1.MonikerKind; } })); Object.defineProperty(exports, "MonikerRequest", ({ enumerable: true, get: function () { return protocol_moniker_1.MonikerRequest; } })); // @ts-ignore: to avoid inlining LocationLink as dynamic import let __noDynamicImport; /** * The DocumentFilter namespace provides helper functions to work with * [DocumentFilter](#DocumentFilter) literals. */ var DocumentFilter; (function (DocumentFilter) { function is(value) { const candidate = value; return Is.string(candidate.language) || Is.string(candidate.scheme) || Is.string(candidate.pattern); } DocumentFilter.is = is; })(DocumentFilter = exports.DocumentFilter || (exports.DocumentFilter = {})); /** * The DocumentSelector namespace provides helper functions to work with * [DocumentSelector](#DocumentSelector)s. */ var DocumentSelector; (function (DocumentSelector) { function is(value) { if (!Array.isArray(value)) { return false; } for (let elem of value) { if (!Is.string(elem) && !DocumentFilter.is(elem)) { return false; } } return true; } DocumentSelector.is = is; })(DocumentSelector = exports.DocumentSelector || (exports.DocumentSelector = {})); /** * The `client/registerCapability` request is sent from the server to the client to register a new capability * handler on the client side. */ var RegistrationRequest; (function (RegistrationRequest) { RegistrationRequest.type = new messages_1.ProtocolRequestType('client/registerCapability'); })(RegistrationRequest = exports.RegistrationRequest || (exports.RegistrationRequest = {})); /** * The `client/unregisterCapability` request is sent from the server to the client to unregister a previously registered capability * handler on the client side. */ var UnregistrationRequest; (function (UnregistrationRequest) { UnregistrationRequest.type = new messages_1.ProtocolRequestType('client/unregisterCapability'); })(UnregistrationRequest = exports.UnregistrationRequest || (exports.UnregistrationRequest = {})); var ResourceOperationKind; (function (ResourceOperationKind) { /** * Supports creating new files and folders. */ ResourceOperationKind.Create = 'create'; /** * Supports renaming existing files and folders. */ ResourceOperationKind.Rename = 'rename'; /** * Supports deleting existing files and folders. */ ResourceOperationKind.Delete = 'delete'; })(ResourceOperationKind = exports.ResourceOperationKind || (exports.ResourceOperationKind = {})); var FailureHandlingKind; (function (FailureHandlingKind) { /** * Applying the workspace change is simply aborted if one of the changes provided * fails. All operations executed before the failing operation stay executed. */ FailureHandlingKind.Abort = 'abort'; /** * All operations are executed transactional. That means they either all * succeed or no changes at all are applied to the workspace. */ FailureHandlingKind.Transactional = 'transactional'; /** * If the workspace edit contains only textual file changes they are executed transactional. * If resource changes (create, rename or delete file) are part of the change the failure * handling strategy is abort. */ FailureHandlingKind.TextOnlyTransactional = 'textOnlyTransactional'; /** * The client tries to undo the operations already executed. But there is no * guarantee that this is succeeding. */ FailureHandlingKind.Undo = 'undo'; })(FailureHandlingKind = exports.FailureHandlingKind || (exports.FailureHandlingKind = {})); /** * The StaticRegistrationOptions namespace provides helper functions to work with * [StaticRegistrationOptions](#StaticRegistrationOptions) literals. */ var StaticRegistrationOptions; (function (StaticRegistrationOptions) { function hasId(value) { const candidate = value; return candidate && Is.string(candidate.id) && candidate.id.length > 0; } StaticRegistrationOptions.hasId = hasId; })(StaticRegistrationOptions = exports.StaticRegistrationOptions || (exports.StaticRegistrationOptions = {})); /** * The TextDocumentRegistrationOptions namespace provides helper functions to work with * [TextDocumentRegistrationOptions](#TextDocumentRegistrationOptions) literals. */ var TextDocumentRegistrationOptions; (function (TextDocumentRegistrationOptions) { function is(value) { const candidate = value; return candidate && (candidate.documentSelector === null || DocumentSelector.is(candidate.documentSelector)); } TextDocumentRegistrationOptions.is = is; })(TextDocumentRegistrationOptions = exports.TextDocumentRegistrationOptions || (exports.TextDocumentRegistrationOptions = {})); /** * The WorkDoneProgressOptions namespace provides helper functions to work with * [WorkDoneProgressOptions](#WorkDoneProgressOptions) literals. */ var WorkDoneProgressOptions; (function (WorkDoneProgressOptions) { function is(value) { const candidate = value; return Is.objectLiteral(candidate) && (candidate.workDoneProgress === undefined || Is.boolean(candidate.workDoneProgress)); } WorkDoneProgressOptions.is = is; function hasWorkDoneProgress(value) { const candidate = value; return candidate && Is.boolean(candidate.workDoneProgress); } WorkDoneProgressOptions.hasWorkDoneProgress = hasWorkDoneProgress; })(WorkDoneProgressOptions = exports.WorkDoneProgressOptions || (exports.WorkDoneProgressOptions = {})); /** * The initialize request is sent from the client to the server. * It is sent once as the request after starting up the server. * The requests parameter is of type [InitializeParams](#InitializeParams) * the response if of type [InitializeResult](#InitializeResult) of a Thenable that * resolves to such. */ var InitializeRequest; (function (InitializeRequest) { InitializeRequest.type = new messages_1.ProtocolRequestType('initialize'); })(InitializeRequest = exports.InitializeRequest || (exports.InitializeRequest = {})); /** * Known error codes for an `InitializeError`; */ var InitializeError; (function (InitializeError) { /** * If the protocol version provided by the client can't be handled by the server. * @deprecated This initialize error got replaced by client capabilities. There is * no version handshake in version 3.0x */ InitializeError.unknownProtocolVersion = 1; })(InitializeError = exports.InitializeError || (exports.InitializeError = {})); /** * The initialized notification is sent from the client to the * server after the client is fully initialized and the server * is allowed to send requests from the server to the client. */ var InitializedNotification; (function (InitializedNotification) { InitializedNotification.type = new messages_1.ProtocolNotificationType('initialized'); })(InitializedNotification = exports.InitializedNotification || (exports.InitializedNotification = {})); //---- Shutdown Method ---- /** * A shutdown request is sent from the client to the server. * It is sent once when the client decides to shutdown the * server. The only notification that is sent after a shutdown request * is the exit event. */ var ShutdownRequest; (function (ShutdownRequest) { ShutdownRequest.type = new messages_1.ProtocolRequestType0('shutdown'); })(ShutdownRequest = exports.ShutdownRequest || (exports.ShutdownRequest = {})); //---- Exit Notification ---- /** * The exit event is sent from the client to the server to * ask the server to exit its process. */ var ExitNotification; (function (ExitNotification) { ExitNotification.type = new messages_1.ProtocolNotificationType0('exit'); })(ExitNotification = exports.ExitNotification || (exports.ExitNotification = {})); /** * The configuration change notification is sent from the client to the server * when the client's configuration has changed. The notification contains * the changed configuration as defined by the language client. */ var DidChangeConfigurationNotification; (function (DidChangeConfigurationNotification) { DidChangeConfigurationNotification.type = new messages_1.ProtocolNotificationType('workspace/didChangeConfiguration'); })(DidChangeConfigurationNotification = exports.DidChangeConfigurationNotification || (exports.DidChangeConfigurationNotification = {})); //---- Message show and log notifications ---- /** * The message type */ var MessageType; (function (MessageType) { /** * An error message. */ MessageType.Error = 1; /** * A warning message. */ MessageType.Warning = 2; /** * An information message. */ MessageType.Info = 3; /** * A log message. */ MessageType.Log = 4; })(MessageType = exports.MessageType || (exports.MessageType = {})); /** * The show message notification is sent from a server to a client to ask * the client to display a particular message in the user interface. */ var ShowMessageNotification; (function (ShowMessageNotification) { ShowMessageNotification.type = new messages_1.ProtocolNotificationType('window/showMessage'); })(ShowMessageNotification = exports.ShowMessageNotification || (exports.ShowMessageNotification = {})); /** * The show message request is sent from the server to the client to show a message * and a set of options actions to the user. */ var ShowMessageRequest; (function (ShowMessageRequest) { ShowMessageRequest.type = new messages_1.ProtocolRequestType('window/showMessageRequest'); })(ShowMessageRequest = exports.ShowMessageRequest || (exports.ShowMessageRequest = {})); /** * The log message notification is sent from the server to the client to ask * the client to log a particular message. */ var LogMessageNotification; (function (LogMessageNotification) { LogMessageNotification.type = new messages_1.ProtocolNotificationType('window/logMessage'); })(LogMessageNotification = exports.LogMessageNotification || (exports.LogMessageNotification = {})); //---- Telemetry notification /** * The telemetry event notification is sent from the server to the client to ask * the client to log telemetry data. */ var TelemetryEventNotification; (function (TelemetryEventNotification) { TelemetryEventNotification.type = new messages_1.ProtocolNotificationType('telemetry/event'); })(TelemetryEventNotification = exports.TelemetryEventNotification || (exports.TelemetryEventNotification = {})); /** * Defines how the host (editor) should sync * document changes to the language server. */ var TextDocumentSyncKind; (function (TextDocumentSyncKind) { /** * Documents should not be synced at all. */ TextDocumentSyncKind.None = 0; /** * Documents are synced by always sending the full content * of the document. */ TextDocumentSyncKind.Full = 1; /** * Documents are synced by sending the full content on open. * After that only incremental updates to the document are * send. */ TextDocumentSyncKind.Incremental = 2; })(TextDocumentSyncKind = exports.TextDocumentSyncKind || (exports.TextDocumentSyncKind = {})); /** * The document open notification is sent from the client to the server to signal * newly opened text documents. The document's truth is now managed by the client * and the server must not try to read the document's truth using the document's * uri. Open in this sense means it is managed by the client. It doesn't necessarily * mean that its content is presented in an editor. An open notification must not * be sent more than once without a corresponding close notification send before. * This means open and close notification must be balanced and the max open count * is one. */ var DidOpenTextDocumentNotification; (function (DidOpenTextDocumentNotification) { DidOpenTextDocumentNotification.method = 'textDocument/didOpen'; DidOpenTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidOpenTextDocumentNotification.method); })(DidOpenTextDocumentNotification = exports.DidOpenTextDocumentNotification || (exports.DidOpenTextDocumentNotification = {})); var TextDocumentContentChangeEvent; (function (TextDocumentContentChangeEvent) { /** * Checks whether the information describes a delta event. */ function isIncremental(event) { let candidate = event; return candidate !== undefined && candidate !== null && typeof candidate.text === 'string' && candidate.range !== undefined && (candidate.rangeLength === undefined || typeof candidate.rangeLength === 'number'); } TextDocumentContentChangeEvent.isIncremental = isIncremental; /** * Checks whether the information describes a full replacement event. */ function isFull(event) { let candidate = event; return candidate !== undefined && candidate !== null && typeof candidate.text === 'string' && candidate.range === undefined && candidate.rangeLength === undefined; } TextDocumentContentChangeEvent.isFull = isFull; })(TextDocumentContentChangeEvent = exports.TextDocumentContentChangeEvent || (exports.TextDocumentContentChangeEvent = {})); /** * The document change notification is sent from the client to the server to signal * changes to a text document. */ var DidChangeTextDocumentNotification; (function (DidChangeTextDocumentNotification) { DidChangeTextDocumentNotification.method = 'textDocument/didChange'; DidChangeTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidChangeTextDocumentNotification.method); })(DidChangeTextDocumentNotification = exports.DidChangeTextDocumentNotification || (exports.DidChangeTextDocumentNotification = {})); /** * The document close notification is sent from the client to the server when * the document got closed in the client. The document's truth now exists where * the document's uri points to (e.g. if the document's uri is a file uri the * truth now exists on disk). As with the open notification the close notification * is about managing the document's content. Receiving a close notification * doesn't mean that the document was open in an editor before. A close * notification requires a previous open notification to be sent. */ var DidCloseTextDocumentNotification; (function (DidCloseTextDocumentNotification) { DidCloseTextDocumentNotification.method = 'textDocument/didClose'; DidCloseTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidCloseTextDocumentNotification.method); })(DidCloseTextDocumentNotification = exports.DidCloseTextDocumentNotification || (exports.DidCloseTextDocumentNotification = {})); /** * The document save notification is sent from the client to the server when * the document got saved in the client. */ var DidSaveTextDocumentNotification; (function (DidSaveTextDocumentNotification) { DidSaveTextDocumentNotification.method = 'textDocument/didSave'; DidSaveTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidSaveTextDocumentNotification.method); })(DidSaveTextDocumentNotification = exports.DidSaveTextDocumentNotification || (exports.DidSaveTextDocumentNotification = {})); /** * Represents reasons why a text document is saved. */ var TextDocumentSaveReason; (function (TextDocumentSaveReason) { /** * Manually triggered, e.g. by the user pressing save, by starting debugging, * or by an API call. */ TextDocumentSaveReason.Manual = 1; /** * Automatic after a delay. */ TextDocumentSaveReason.AfterDelay = 2; /** * When the editor lost focus. */ TextDocumentSaveReason.FocusOut = 3; })(TextDocumentSaveReason = exports.TextDocumentSaveReason || (exports.TextDocumentSaveReason = {})); /** * A document will save notification is sent from the client to the server before * the document is actually saved. */ var WillSaveTextDocumentNotification; (function (WillSaveTextDocumentNotification) { WillSaveTextDocumentNotification.method = 'textDocument/willSave'; WillSaveTextDocumentNotification.type = new messages_1.ProtocolNotificationType(WillSaveTextDocumentNotification.method); })(WillSaveTextDocumentNotification = exports.WillSaveTextDocumentNotification || (exports.WillSaveTextDocumentNotification = {})); /** * A document will save request is sent from the client to the server before * the document is actually saved. The request can return an array of TextEdits * which will be applied to the text document before it is saved. Please note that * clients might drop results if computing the text edits took too long or if a * server constantly fails on this request. This is done to keep the save fast and * reliable. */ var WillSaveTextDocumentWaitUntilRequest; (function (WillSaveTextDocumentWaitUntilRequest) { WillSaveTextDocumentWaitUntilRequest.method = 'textDocument/willSaveWaitUntil'; WillSaveTextDocumentWaitUntilRequest.type = new messages_1.ProtocolRequestType(WillSaveTextDocumentWaitUntilRequest.method); })(WillSaveTextDocumentWaitUntilRequest = exports.WillSaveTextDocumentWaitUntilRequest || (exports.WillSaveTextDocumentWaitUntilRequest = {})); /** * The watched files notification is sent from the client to the server when * the client detects changes to file watched by the language client. */ var DidChangeWatchedFilesNotification; (function (DidChangeWatchedFilesNotification) { DidChangeWatchedFilesNotification.type = new messages_1.ProtocolNotificationType('workspace/didChangeWatchedFiles'); })(DidChangeWatchedFilesNotification = exports.DidChangeWatchedFilesNotification || (exports.DidChangeWatchedFilesNotification = {})); /** * The file event type */ var FileChangeType; (function (FileChangeType) { /** * The file got created. */ FileChangeType.Created = 1; /** * The file got changed. */ FileChangeType.Changed = 2; /** * The file got deleted. */ FileChangeType.Deleted = 3; })(FileChangeType = exports.FileChangeType || (exports.FileChangeType = {})); var WatchKind; (function (WatchKind) { /** * Interested in create events. */ WatchKind.Create = 1; /** * Interested in change events */ WatchKind.Change = 2; /** * Interested in delete events */ WatchKind.Delete = 4; })(WatchKind = exports.WatchKind || (exports.WatchKind = {})); /** * Diagnostics notification are sent from the server to the client to signal * results of validation runs. */ var PublishDiagnosticsNotification; (function (PublishDiagnosticsNotification) { PublishDiagnosticsNotification.type = new messages_1.ProtocolNotificationType('textDocument/publishDiagnostics'); })(PublishDiagnosticsNotification = exports.PublishDiagnosticsNotification || (exports.PublishDiagnosticsNotification = {})); /** * How a completion was triggered */ var CompletionTriggerKind; (function (CompletionTriggerKind) { /** * Completion was triggered by typing an identifier (24x7 code * complete), manual invocation (e.g Ctrl+Space) or via API. */ CompletionTriggerKind.Invoked = 1; /** * Completion was triggered by a trigger character specified by * the `triggerCharacters` properties of the `CompletionRegistrationOptions`. */ CompletionTriggerKind.TriggerCharacter = 2; /** * Completion was re-triggered as current completion list is incomplete */ CompletionTriggerKind.TriggerForIncompleteCompletions = 3; })(CompletionTriggerKind = exports.CompletionTriggerKind || (exports.CompletionTriggerKind = {})); /** * Request to request completion at a given text document position. The request's * parameter is of type [TextDocumentPosition](#TextDocumentPosition) the response * is of type [CompletionItem[]](#CompletionItem) or [CompletionList](#CompletionList) * or a Thenable that resolves to such. * * The request can delay the computation of the [`detail`](#CompletionItem.detail) * and [`documentation`](#CompletionItem.documentation) properties to the `completionItem/resolve` * request. However, properties that are needed for the initial sorting and filtering, like `sortText`, * `filterText`, `insertText`, and `textEdit`, must not be changed during resolve. */ var CompletionRequest; (function (CompletionRequest) { CompletionRequest.method = 'textDocument/completion'; CompletionRequest.type = new messages_1.ProtocolRequestType(CompletionRequest.method); })(CompletionRequest = exports.CompletionRequest || (exports.CompletionRequest = {})); /** * Request to resolve additional information for a given completion item.The request's * parameter is of type [CompletionItem](#CompletionItem) the response * is of type [CompletionItem](#CompletionItem) or a Thenable that resolves to such. */ var CompletionResolveRequest; (function (CompletionResolveRequest) { CompletionResolveRequest.method = 'completionItem/resolve'; CompletionResolveRequest.type = new messages_1.ProtocolRequestType(CompletionResolveRequest.method); })(CompletionResolveRequest = exports.CompletionResolveRequest || (exports.CompletionResolveRequest = {})); /** * Request to request hover information at a given text document position. The request's * parameter is of type [TextDocumentPosition](#TextDocumentPosition) the response is of * type [Hover](#Hover) or a Thenable that resolves to such. */ var HoverRequest; (function (HoverRequest) { HoverRequest.method = 'textDocument/hover'; HoverRequest.type = new messages_1.ProtocolRequestType(HoverRequest.method); })(HoverRequest = exports.HoverRequest || (exports.HoverRequest = {})); /** * How a signature help was triggered. * * @since 3.15.0 */ var SignatureHelpTriggerKind; (function (SignatureHelpTriggerKind) { /** * Signature help was invoked manually by the user or by a command. */ SignatureHelpTriggerKind.Invoked = 1; /** * Signature help was triggered by a trigger character. */ SignatureHelpTriggerKind.TriggerCharacter = 2; /** * Signature help was triggered by the cursor moving or by the document content changing. */ SignatureHelpTriggerKind.ContentChange = 3; })(SignatureHelpTriggerKind = exports.SignatureHelpTriggerKind || (exports.SignatureHelpTriggerKind = {})); var SignatureHelpRequest; (function (SignatureHelpRequest) { SignatureHelpRequest.method = 'textDocument/signatureHelp'; SignatureHelpRequest.type = new messages_1.ProtocolRequestType(SignatureHelpRequest.method); })(SignatureHelpRequest = exports.SignatureHelpRequest || (exports.SignatureHelpRequest = {})); /** * A request to resolve the definition location of a symbol at a given text * document position. The request's parameter is of type [TextDocumentPosition] * (#TextDocumentPosition) the response is of either type [Definition](#Definition) * or a typed array of [DefinitionLink](#DefinitionLink) or a Thenable that resolves * to such. */ var DefinitionRequest; (function (DefinitionRequest) { DefinitionRequest.method = 'textDocument/definition'; DefinitionRequest.type = new messages_1.ProtocolRequestType(DefinitionRequest.method); })(DefinitionRequest = exports.DefinitionRequest || (exports.DefinitionRequest = {})); /** * A request to resolve project-wide references for the symbol denoted * by the given text document position. The request's parameter is of * type [ReferenceParams](#ReferenceParams) the response is of type * [Location[]](#Location) or a Thenable that resolves to such. */ var ReferencesRequest; (function (ReferencesRequest) { ReferencesRequest.method = 'textDocument/references'; ReferencesRequest.type = new messages_1.ProtocolRequestType(ReferencesRequest.method); })(ReferencesRequest = exports.ReferencesRequest || (exports.ReferencesRequest = {})); /** * Request to resolve a [DocumentHighlight](#DocumentHighlight) for a given * text document position. The request's parameter is of type [TextDocumentPosition] * (#TextDocumentPosition) the request response is of type [DocumentHighlight[]] * (#DocumentHighlight) or a Thenable that resolves to such. */ var DocumentHighlightRequest; (function (DocumentHighlightRequest) { DocumentHighlightRequest.method = 'textDocument/documentHighlight'; DocumentHighlightRequest.type = new messages_1.ProtocolRequestType(DocumentHighlightRequest.method); })(DocumentHighlightRequest = exports.DocumentHighlightRequest || (exports.DocumentHighlightRequest = {})); /** * A request to list all symbols found in a given text document. The request's * parameter is of type [TextDocumentIdentifier](#TextDocumentIdentifier) the * response is of type [SymbolInformation[]](#SymbolInformation) or a Thenable * that resolves to such. */ var DocumentSymbolRequest; (function (DocumentSymbolRequest) { DocumentSymbolRequest.method = 'textDocument/documentSymbol'; DocumentSymbolRequest.type = new messages_1.ProtocolRequestType(DocumentSymbolRequest.method); })(DocumentSymbolRequest = exports.DocumentSymbolRequest || (exports.DocumentSymbolRequest = {})); /** * A request to provide commands for the given text document and range. */ var CodeActionRequest; (function (CodeActionRequest) { CodeActionRequest.method = 'textDocument/codeAction'; CodeActionRequest.type = new messages_1.ProtocolRequestType(CodeActionRequest.method); })(CodeActionRequest = exports.CodeActionRequest || (exports.CodeActionRequest = {})); /** * Request to resolve additional information for a given code action.The request's * parameter is of type [CodeAction](#CodeAction) the response * is of type [CodeAction](#CodeAction) or a Thenable that resolves to such. */ var CodeActionResolveRequest; (function (CodeActionResolveRequest) { CodeActionResolveRequest.method = 'codeAction/resolve'; CodeActionResolveRequest.type = new messages_1.ProtocolRequestType(CodeActionResolveRequest.method); })(CodeActionResolveRequest = exports.CodeActionResolveRequest || (exports.CodeActionResolveRequest = {})); /** * A request to list project-wide symbols matching the query string given * by the [WorkspaceSymbolParams](#WorkspaceSymbolParams). The response is * of type [SymbolInformation[]](#SymbolInformation) or a Thenable that * resolves to such. */ var WorkspaceSymbolRequest; (function (WorkspaceSymbolRequest) { WorkspaceSymbolRequest.method = 'workspace/symbol'; WorkspaceSymbolRequest.type = new messages_1.ProtocolRequestType(WorkspaceSymbolRequest.method); })(WorkspaceSymbolRequest = exports.WorkspaceSymbolRequest || (exports.WorkspaceSymbolRequest = {})); /** * A request to provide code lens for the given text document. */ var CodeLensRequest; (function (CodeLensRequest) { CodeLensRequest.method = 'textDocument/codeLens'; CodeLensRequest.type = new messages_1.ProtocolRequestType(CodeLensRequest.method); })(CodeLensRequest = exports.CodeLensRequest || (exports.CodeLensRequest = {})); /** * A request to resolve a command for a given code lens. */ var CodeLensResolveRequest; (function (CodeLensResolveRequest) { CodeLensResolveRequest.method = 'codeLens/resolve'; CodeLensResolveRequest.type = new messages_1.ProtocolRequestType(CodeLensResolveRequest.method); })(CodeLensResolveRequest = exports.CodeLensResolveRequest || (exports.CodeLensResolveRequest = {})); /** * A request to refresh all code actions * * @since 3.16.0 */ var CodeLensRefreshRequest; (function (CodeLensRefreshRequest) { CodeLensRefreshRequest.method = `workspace/codeLens/refresh`; CodeLensRefreshRequest.type = new messages_1.ProtocolRequestType0(CodeLensRefreshRequest.method); })(CodeLensRefreshRequest = exports.CodeLensRefreshRequest || (exports.CodeLensRefreshRequest = {})); /** * A request to provide document links */ var DocumentLinkRequest; (function (DocumentLinkRequest) { DocumentLinkRequest.method = 'textDocument/documentLink'; DocumentLinkRequest.type = new messages_1.ProtocolRequestType(DocumentLinkRequest.method); })(DocumentLinkRequest = exports.DocumentLinkRequest || (exports.DocumentLinkRequest = {})); /** * Request to resolve additional information for a given document link. The request's * parameter is of type [DocumentLink](#DocumentLink) the response * is of type [DocumentLink](#DocumentLink) or a Thenable that resolves to such. */ var DocumentLinkResolveRequest; (function (DocumentLinkResolveRequest) { DocumentLinkResolveRequest.method = 'documentLink/resolve'; DocumentLinkResolveRequest.type = new messages_1.ProtocolRequestType(DocumentLinkResolveRequest.method); })(DocumentLinkResolveRequest = exports.DocumentLinkResolveRequest || (exports.DocumentLinkResolveRequest = {})); /** * A request to to format a whole document. */ var DocumentFormattingRequest; (function (DocumentFormattingRequest) { DocumentFormattingRequest.method = 'textDocument/formatting'; DocumentFormattingRequest.type = new messages_1.ProtocolRequestType(DocumentFormattingRequest.method); })(DocumentFormattingRequest = exports.DocumentFormattingRequest || (exports.DocumentFormattingRequest = {})); /** * A request to to format a range in a document. */ var DocumentRangeFormattingRequest; (function (DocumentRangeFormattingRequest) { DocumentRangeFormattingRequest.method = 'textDocument/rangeFormatting'; DocumentRangeFormattingRequest.type = new messages_1.ProtocolRequestType(DocumentRangeFormattingRequest.method); })(DocumentRangeFormattingRequest = exports.DocumentRangeFormattingRequest || (exports.DocumentRangeFormattingRequest = {})); /** * A request to format a document on type. */ var DocumentOnTypeFormattingRequest; (function (DocumentOnTypeFormattingRequest) { DocumentOnTypeFormattingRequest.method = 'textDocument/onTypeFormatting'; DocumentOnTypeFormattingRequest.type = new messages_1.ProtocolRequestType(DocumentOnTypeFormattingRequest.method); })(DocumentOnTypeFormattingRequest = exports.DocumentOnTypeFormattingRequest || (exports.DocumentOnTypeFormattingRequest = {})); //---- Rename ---------------------------------------------- var PrepareSupportDefaultBehavior; (function (PrepareSupportDefaultBehavior) { /** * The client's default behavior is to select the identifier * according the to language's syntax rule. */ PrepareSupportDefaultBehavior.Identifier = 1; })(PrepareSupportDefaultBehavior = exports.PrepareSupportDefaultBehavior || (exports.PrepareSupportDefaultBehavior = {})); /** * A request to rename a symbol. */ var RenameRequest; (function (RenameRequest) { RenameRequest.method = 'textDocument/rename'; RenameRequest.type = new messages_1.ProtocolRequestType(RenameRequest.method); })(RenameRequest = exports.RenameRequest || (exports.RenameRequest = {})); /** * A request to test and perform the setup necessary for a rename. * * @since 3.16 - support for default behavior */ var PrepareRenameRequest; (function (PrepareRenameRequest) { PrepareRenameRequest.method = 'textDocument/prepareRename'; PrepareRenameRequest.type = new messages_1.ProtocolRequestType(PrepareRenameRequest.method); })(PrepareRenameRequest = exports.PrepareRenameRequest || (exports.PrepareRenameRequest = {})); /** * A request send from the client to the server to execute a command. The request might return * a workspace edit which the client will apply to the workspace. */ var ExecuteCommandRequest; (function (ExecuteCommandRequest) { ExecuteCommandRequest.type = new messages_1.ProtocolRequestType('workspace/executeCommand'); })(ExecuteCommandRequest = exports.ExecuteCommandRequest || (exports.ExecuteCommandRequest = {})); /** * A request sent from the server to the client to modified certain resources. */ var ApplyWorkspaceEditRequest; (function (ApplyWorkspaceEditRequest) { ApplyWorkspaceEditRequest.type = new messages_1.ProtocolRequestType('workspace/applyEdit'); })(ApplyWorkspaceEditRequest = exports.ApplyWorkspaceEditRequest || (exports.ApplyWorkspaceEditRequest = {})); //# sourceMappingURL=protocol.js.map /***/ }), /***/ 6305: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.LinkedEditingRangeRequest = void 0; const messages_1 = __webpack_require__(6140); /** * A request to provide ranges that can be edited together. * * @since 3.16.0 */ var LinkedEditingRangeRequest; (function (LinkedEditingRangeRequest) { LinkedEditingRangeRequest.method = 'textDocument/linkedEditingRange'; LinkedEditingRangeRequest.type = new messages_1.ProtocolRequestType(LinkedEditingRangeRequest.method); })(LinkedEditingRangeRequest = exports.LinkedEditingRangeRequest || (exports.LinkedEditingRangeRequest = {})); //# sourceMappingURL=protocol.linkedEditingRange.js.map /***/ }), /***/ 3443: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.MonikerRequest = exports.MonikerKind = exports.UniquenessLevel = void 0; const messages_1 = __webpack_require__(6140); /** * Moniker uniqueness level to define scope of the moniker. * * @since 3.16.0 */ var UniquenessLevel; (function (UniquenessLevel) { /** * The moniker is only unique inside a document */ UniquenessLevel["document"] = "document"; /** * The moniker is unique inside a project for which a dump got created */ UniquenessLevel["project"] = "project"; /** * The moniker is unique inside the group to which a project belongs */ UniquenessLevel["group"] = "group"; /** * The moniker is unique inside the moniker scheme. */ UniquenessLevel["scheme"] = "scheme"; /** * The moniker is globally unique */ UniquenessLevel["global"] = "global"; })(UniquenessLevel = exports.UniquenessLevel || (exports.UniquenessLevel = {})); /** * The moniker kind. * * @since 3.16.0 */ var MonikerKind; (function (MonikerKind) { /** * The moniker represent a symbol that is imported into a project */ MonikerKind["import"] = "import"; /** * The moniker represents a symbol that is exported from a project */ MonikerKind["export"] = "export"; /** * The moniker represents a symbol that is local to a project (e.g. a local * variable of a function, a class not visible outside the project, ...) */ MonikerKind["local"] = "local"; })(MonikerKind = exports.MonikerKind || (exports.MonikerKind = {})); /** * A request to get the moniker of a symbol at a given text document position. * The request parameter is of type [TextDocumentPositionParams](#TextDocumentPositionParams). * The response is of type [Moniker[]](#Moniker[]) or `null`. */ var MonikerRequest; (function (MonikerRequest) { MonikerRequest.method = 'textDocument/moniker'; MonikerRequest.type = new messages_1.ProtocolRequestType(MonikerRequest.method); })(MonikerRequest = exports.MonikerRequest || (exports.MonikerRequest = {})); //# sourceMappingURL=protocol.moniker.js.map /***/ }), /***/ 1862: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.WorkDoneProgressCancelNotification = exports.WorkDoneProgressCreateRequest = exports.WorkDoneProgress = void 0; const vscode_jsonrpc_1 = __webpack_require__(4389); const messages_1 = __webpack_require__(6140); var WorkDoneProgress; (function (WorkDoneProgress) { WorkDoneProgress.type = new vscode_jsonrpc_1.ProgressType(); function is(value) { return value === WorkDoneProgress.type; } WorkDoneProgress.is = is; })(WorkDoneProgress = exports.WorkDoneProgress || (exports.WorkDoneProgress = {})); /** * The `window/workDoneProgress/create` request is sent from the server to the client to initiate progress * reporting from the server. */ var WorkDoneProgressCreateRequest; (function (WorkDoneProgressCreateRequest) { WorkDoneProgressCreateRequest.type = new messages_1.ProtocolRequestType('window/workDoneProgress/create'); })(WorkDoneProgressCreateRequest = exports.WorkDoneProgressCreateRequest || (exports.WorkDoneProgressCreateRequest = {})); /** * The `window/workDoneProgress/cancel` notification is sent from the client to the server to cancel a progress * initiated on the server side. */ var WorkDoneProgressCancelNotification; (function (WorkDoneProgressCancelNotification) { WorkDoneProgressCancelNotification.type = new messages_1.ProtocolNotificationType('window/workDoneProgress/cancel'); })(WorkDoneProgressCancelNotification = exports.WorkDoneProgressCancelNotification || (exports.WorkDoneProgressCancelNotification = {})); //# sourceMappingURL=protocol.progress.js.map /***/ }), /***/ 5206: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.SelectionRangeRequest = void 0; const messages_1 = __webpack_require__(6140); /** * A request to provide selection ranges in a document. The request's * parameter is of type [SelectionRangeParams](#SelectionRangeParams), the * response is of type [SelectionRange[]](#SelectionRange[]) or a Thenable * that resolves to such. */ var SelectionRangeRequest; (function (SelectionRangeRequest) { SelectionRangeRequest.method = 'textDocument/selectionRange'; SelectionRangeRequest.type = new messages_1.ProtocolRequestType(SelectionRangeRequest.method); })(SelectionRangeRequest = exports.SelectionRangeRequest || (exports.SelectionRangeRequest = {})); //# sourceMappingURL=protocol.selectionRange.js.map /***/ }), /***/ 9434: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.SemanticTokensRefreshRequest = exports.SemanticTokensRangeRequest = exports.SemanticTokensDeltaRequest = exports.SemanticTokensRequest = exports.SemanticTokensRegistrationType = exports.TokenFormat = exports.SemanticTokens = exports.SemanticTokenModifiers = exports.SemanticTokenTypes = void 0; const messages_1 = __webpack_require__(6140); /** * A set of predefined token types. This set is not fixed * an clients can specify additional token types via the * corresponding client capabilities. * * @since 3.16.0 */ var SemanticTokenTypes; (function (SemanticTokenTypes) { SemanticTokenTypes["namespace"] = "namespace"; /** * Represents a generic type. Acts as a fallback for types which can't be mapped to * a specific type like class or enum. */ SemanticTokenTypes["type"] = "type"; SemanticTokenTypes["class"] = "class"; SemanticTokenTypes["enum"] = "enum"; SemanticTokenTypes["interface"] = "interface"; SemanticTokenTypes["struct"] = "struct"; SemanticTokenTypes["typeParameter"] = "typeParameter"; SemanticTokenTypes["parameter"] = "parameter"; SemanticTokenTypes["variable"] = "variable"; SemanticTokenTypes["property"] = "property"; SemanticTokenTypes["enumMember"] = "enumMember"; SemanticTokenTypes["event"] = "event"; SemanticTokenTypes["function"] = "function"; SemanticTokenTypes["method"] = "method"; SemanticTokenTypes["macro"] = "macro"; SemanticTokenTypes["keyword"] = "keyword"; SemanticTokenTypes["modifier"] = "modifier"; SemanticTokenTypes["comment"] = "comment"; SemanticTokenTypes["string"] = "string"; SemanticTokenTypes["number"] = "number"; SemanticTokenTypes["regexp"] = "regexp"; SemanticTokenTypes["operator"] = "operator"; })(SemanticTokenTypes = exports.SemanticTokenTypes || (exports.SemanticTokenTypes = {})); /** * A set of predefined token modifiers. This set is not fixed * an clients can specify additional token types via the * corresponding client capabilities. * * @since 3.16.0 */ var SemanticTokenModifiers; (function (SemanticTokenModifiers) { SemanticTokenModifiers["declaration"] = "declaration"; SemanticTokenModifiers["definition"] = "definition"; SemanticTokenModifiers["readonly"] = "readonly"; SemanticTokenModifiers["static"] = "static"; SemanticTokenModifiers["deprecated"] = "deprecated"; SemanticTokenModifiers["abstract"] = "abstract"; SemanticTokenModifiers["async"] = "async"; SemanticTokenModifiers["modification"] = "modification"; SemanticTokenModifiers["documentation"] = "documentation"; SemanticTokenModifiers["defaultLibrary"] = "defaultLibrary"; })(SemanticTokenModifiers = exports.SemanticTokenModifiers || (exports.SemanticTokenModifiers = {})); /** * @since 3.16.0 */ var SemanticTokens; (function (SemanticTokens) { function is(value) { const candidate = value; return candidate !== undefined && (candidate.resultId === undefined || typeof candidate.resultId === 'string') && Array.isArray(candidate.data) && (candidate.data.length === 0 || typeof candidate.data[0] === 'number'); } SemanticTokens.is = is; })(SemanticTokens = exports.SemanticTokens || (exports.SemanticTokens = {})); //------- 'textDocument/semanticTokens' ----- var TokenFormat; (function (TokenFormat) { TokenFormat.Relative = 'relative'; })(TokenFormat = exports.TokenFormat || (exports.TokenFormat = {})); var SemanticTokensRegistrationType; (function (SemanticTokensRegistrationType) { SemanticTokensRegistrationType.method = 'textDocument/semanticTokens'; SemanticTokensRegistrationType.type = new messages_1.RegistrationType(SemanticTokensRegistrationType.method); })(SemanticTokensRegistrationType = exports.SemanticTokensRegistrationType || (exports.SemanticTokensRegistrationType = {})); /** * @since 3.16.0 */ var SemanticTokensRequest; (function (SemanticTokensRequest) { SemanticTokensRequest.method = 'textDocument/semanticTokens/full'; SemanticTokensRequest.type = new messages_1.ProtocolRequestType(SemanticTokensRequest.method); })(SemanticTokensRequest = exports.SemanticTokensRequest || (exports.SemanticTokensRequest = {})); /** * @since 3.16.0 */ var SemanticTokensDeltaRequest; (function (SemanticTokensDeltaRequest) { SemanticTokensDeltaRequest.method = 'textDocument/semanticTokens/full/delta'; SemanticTokensDeltaRequest.type = new messages_1.ProtocolRequestType(SemanticTokensDeltaRequest.method); })(SemanticTokensDeltaRequest = exports.SemanticTokensDeltaRequest || (exports.SemanticTokensDeltaRequest = {})); /** * @since 3.16.0 */ var SemanticTokensRangeRequest; (function (SemanticTokensRangeRequest) { SemanticTokensRangeRequest.method = 'textDocument/semanticTokens/range'; SemanticTokensRangeRequest.type = new messages_1.ProtocolRequestType(SemanticTokensRangeRequest.method); })(SemanticTokensRangeRequest = exports.SemanticTokensRangeRequest || (exports.SemanticTokensRangeRequest = {})); /** * @since 3.16.0 */ var SemanticTokensRefreshRequest; (function (SemanticTokensRefreshRequest) { SemanticTokensRefreshRequest.method = `workspace/semanticTokens/refresh`; SemanticTokensRefreshRequest.type = new messages_1.ProtocolRequestType0(SemanticTokensRefreshRequest.method); })(SemanticTokensRefreshRequest = exports.SemanticTokensRefreshRequest || (exports.SemanticTokensRefreshRequest = {})); //# sourceMappingURL=protocol.semanticTokens.js.map /***/ }), /***/ 5726: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ShowDocumentRequest = void 0; const messages_1 = __webpack_require__(6140); /** * A request to show a document. This request might open an * external program depending on the value of the URI to open. * For example a request to open `https://code.visualstudio.com/` * will very likely open the URI in a WEB browser. * * @since 3.16.0 */ var ShowDocumentRequest; (function (ShowDocumentRequest) { ShowDocumentRequest.method = 'window/showDocument'; ShowDocumentRequest.type = new messages_1.ProtocolRequestType(ShowDocumentRequest.method); })(ShowDocumentRequest = exports.ShowDocumentRequest || (exports.ShowDocumentRequest = {})); //# sourceMappingURL=protocol.showDocument.js.map /***/ }), /***/ 1589: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.TypeDefinitionRequest = void 0; const messages_1 = __webpack_require__(6140); // @ts-ignore: to avoid inlining LocatioLink as dynamic import let __noDynamicImport; /** * A request to resolve the type definition locations of a symbol at a given text * document position. The request's parameter is of type [TextDocumentPositioParams] * (#TextDocumentPositionParams) the response is of type [Definition](#Definition) or a * Thenable that resolves to such. */ var TypeDefinitionRequest; (function (TypeDefinitionRequest) { TypeDefinitionRequest.method = 'textDocument/typeDefinition'; TypeDefinitionRequest.type = new messages_1.ProtocolRequestType(TypeDefinitionRequest.method); })(TypeDefinitionRequest = exports.TypeDefinitionRequest || (exports.TypeDefinitionRequest = {})); //# sourceMappingURL=protocol.typeDefinition.js.map /***/ }), /***/ 3589: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DidChangeWorkspaceFoldersNotification = exports.WorkspaceFoldersRequest = void 0; const messages_1 = __webpack_require__(6140); /** * The `workspace/workspaceFolders` is sent from the server to the client to fetch the open workspace folders. */ var WorkspaceFoldersRequest; (function (WorkspaceFoldersRequest) { WorkspaceFoldersRequest.type = new messages_1.ProtocolRequestType0('workspace/workspaceFolders'); })(WorkspaceFoldersRequest = exports.WorkspaceFoldersRequest || (exports.WorkspaceFoldersRequest = {})); /** * The `workspace/didChangeWorkspaceFolders` notification is sent from the client to the server when the workspace * folder configuration changes. */ var DidChangeWorkspaceFoldersNotification; (function (DidChangeWorkspaceFoldersNotification) { DidChangeWorkspaceFoldersNotification.type = new messages_1.ProtocolNotificationType('workspace/didChangeWorkspaceFolders'); })(DidChangeWorkspaceFoldersNotification = exports.DidChangeWorkspaceFoldersNotification || (exports.DidChangeWorkspaceFoldersNotification = {})); //# sourceMappingURL=protocol.workspaceFolders.js.map /***/ }), /***/ 9533: /***/ ((__unused_webpack_module, exports) => { "use strict"; /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.objectLiteral = exports.typedArray = exports.stringArray = exports.array = exports.func = exports.error = exports.number = exports.string = exports.boolean = void 0; function boolean(value) { return value === true || value === false; } exports.boolean = boolean; function string(value) { return typeof value === 'string' || value instanceof String; } exports.string = string; function number(value) { return typeof value === 'number' || value instanceof Number; } exports.number = number; function error(value) { return value instanceof Error; } exports.error = error; function func(value) { return typeof value === 'function'; } exports.func = func; function array(value) { return Array.isArray(value); } exports.array = array; function stringArray(value) { return array(value) && value.every(elem => string(elem)); } exports.stringArray = stringArray; function typedArray(value, check) { return Array.isArray(value) && value.every(check); } exports.typedArray = typedArray; function objectLiteral(value) { // Strictly speaking class instances pass this check as well. Since the LSP // doesn't use classes we ignore this for now. If we do we need to add something // like this: `Object.getPrototypeOf(Object.getPrototypeOf(x)) === null` return value !== null && typeof value === 'object'; } exports.objectLiteral = objectLiteral; //# sourceMappingURL=is.js.map /***/ }), /***/ 273: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __exportStar = (this && this.__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.createProtocolConnection = void 0; const node_1 = __webpack_require__(5028); __exportStar(__webpack_require__(5028), exports); __exportStar(__webpack_require__(1661), exports); function createProtocolConnection(input, output, logger, options) { return node_1.createMessageConnection(input, output, logger, options); } exports.createProtocolConnection = createProtocolConnection; //# sourceMappingURL=main.js.map /***/ }), /***/ 6560: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ----------------------------------------------------------------------------------------- */ module.exports = __webpack_require__(273); /***/ }), /***/ 1674: /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "integer": () => (/* binding */ integer), /* harmony export */ "uinteger": () => (/* binding */ uinteger), /* harmony export */ "Position": () => (/* binding */ Position), /* harmony export */ "Range": () => (/* binding */ Range), /* harmony export */ "Location": () => (/* binding */ Location), /* harmony export */ "LocationLink": () => (/* binding */ LocationLink), /* harmony export */ "Color": () => (/* binding */ Color), /* harmony export */ "ColorInformation": () => (/* binding */ ColorInformation), /* harmony export */ "ColorPresentation": () => (/* binding */ ColorPresentation), /* harmony export */ "FoldingRangeKind": () => (/* binding */ FoldingRangeKind), /* harmony export */ "FoldingRange": () => (/* binding */ FoldingRange), /* harmony export */ "DiagnosticRelatedInformation": () => (/* binding */ DiagnosticRelatedInformation), /* harmony export */ "DiagnosticSeverity": () => (/* binding */ DiagnosticSeverity), /* harmony export */ "DiagnosticTag": () => (/* binding */ DiagnosticTag), /* harmony export */ "CodeDescription": () => (/* binding */ CodeDescription), /* harmony export */ "Diagnostic": () => (/* binding */ Diagnostic), /* harmony export */ "Command": () => (/* binding */ Command), /* harmony export */ "TextEdit": () => (/* binding */ TextEdit), /* harmony export */ "ChangeAnnotation": () => (/* binding */ ChangeAnnotation), /* harmony export */ "ChangeAnnotationIdentifier": () => (/* binding */ ChangeAnnotationIdentifier), /* harmony export */ "AnnotatedTextEdit": () => (/* binding */ AnnotatedTextEdit), /* harmony export */ "TextDocumentEdit": () => (/* binding */ TextDocumentEdit), /* harmony export */ "CreateFile": () => (/* binding */ CreateFile), /* harmony export */ "RenameFile": () => (/* binding */ RenameFile), /* harmony export */ "DeleteFile": () => (/* binding */ DeleteFile), /* harmony export */ "WorkspaceEdit": () => (/* binding */ WorkspaceEdit), /* harmony export */ "WorkspaceChange": () => (/* binding */ WorkspaceChange), /* harmony export */ "TextDocumentIdentifier": () => (/* binding */ TextDocumentIdentifier), /* harmony export */ "VersionedTextDocumentIdentifier": () => (/* binding */ VersionedTextDocumentIdentifier), /* harmony export */ "OptionalVersionedTextDocumentIdentifier": () => (/* binding */ OptionalVersionedTextDocumentIdentifier), /* harmony export */ "TextDocumentItem": () => (/* binding */ TextDocumentItem), /* harmony export */ "MarkupKind": () => (/* binding */ MarkupKind), /* harmony export */ "MarkupContent": () => (/* binding */ MarkupContent), /* harmony export */ "CompletionItemKind": () => (/* binding */ CompletionItemKind), /* harmony export */ "InsertTextFormat": () => (/* binding */ InsertTextFormat), /* harmony export */ "CompletionItemTag": () => (/* binding */ CompletionItemTag), /* harmony export */ "InsertReplaceEdit": () => (/* binding */ InsertReplaceEdit), /* harmony export */ "InsertTextMode": () => (/* binding */ InsertTextMode), /* harmony export */ "CompletionItem": () => (/* binding */ CompletionItem), /* harmony export */ "CompletionList": () => (/* binding */ CompletionList), /* harmony export */ "MarkedString": () => (/* binding */ MarkedString), /* harmony export */ "Hover": () => (/* binding */ Hover), /* harmony export */ "ParameterInformation": () => (/* binding */ ParameterInformation), /* harmony export */ "SignatureInformation": () => (/* binding */ SignatureInformation), /* harmony export */ "DocumentHighlightKind": () => (/* binding */ DocumentHighlightKind), /* harmony export */ "DocumentHighlight": () => (/* binding */ DocumentHighlight), /* harmony export */ "SymbolKind": () => (/* binding */ SymbolKind), /* harmony export */ "SymbolTag": () => (/* binding */ SymbolTag), /* harmony export */ "SymbolInformation": () => (/* binding */ SymbolInformation), /* harmony export */ "DocumentSymbol": () => (/* binding */ DocumentSymbol), /* harmony export */ "CodeActionKind": () => (/* binding */ CodeActionKind), /* harmony export */ "CodeActionContext": () => (/* binding */ CodeActionContext), /* harmony export */ "CodeAction": () => (/* binding */ CodeAction), /* harmony export */ "CodeLens": () => (/* binding */ CodeLens), /* harmony export */ "FormattingOptions": () => (/* binding */ FormattingOptions), /* harmony export */ "DocumentLink": () => (/* binding */ DocumentLink), /* harmony export */ "SelectionRange": () => (/* binding */ SelectionRange), /* harmony export */ "EOL": () => (/* binding */ EOL), /* harmony export */ "TextDocument": () => (/* binding */ TextDocument) /* harmony export */ }); /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ var integer; (function (integer) { integer.MIN_VALUE = -2147483648; integer.MAX_VALUE = 2147483647; })(integer || (integer = {})); var uinteger; (function (uinteger) { uinteger.MIN_VALUE = 0; uinteger.MAX_VALUE = 2147483647; })(uinteger || (uinteger = {})); /** * The Position namespace provides helper functions to work with * [Position](#Position) literals. */ var Position; (function (Position) { /** * Creates a new Position literal from the given line and character. * @param line The position's line. * @param character The position's character. */ function create(line, character) { if (line === Number.MAX_VALUE) { line = uinteger.MAX_VALUE; } if (character === Number.MAX_VALUE) { character = uinteger.MAX_VALUE; } return { line: line, character: character }; } Position.create = create; /** * Checks whether the given literal conforms to the [Position](#Position) interface. */ function is(value) { var candidate = value; return Is.objectLiteral(candidate) && Is.uinteger(candidate.line) && Is.uinteger(candidate.character); } Position.is = is; })(Position || (Position = {})); /** * The Range namespace provides helper functions to work with * [Range](#Range) literals. */ var Range; (function (Range) { function create(one, two, three, four) { if (Is.uinteger(one) && Is.uinteger(two) && Is.uinteger(three) && Is.uinteger(four)) { return { start: Position.create(one, two), end: Position.create(three, four) }; } else if (Position.is(one) && Position.is(two)) { return { start: one, end: two }; } else { throw new Error("Range#create called with invalid arguments[" + one + ", " + two + ", " + three + ", " + four + "]"); } } Range.create = create; /** * Checks whether the given literal conforms to the [Range](#Range) interface. */ function is(value) { var candidate = value; return Is.objectLiteral(candidate) && Position.is(candidate.start) && Position.is(candidate.end); } Range.is = is; })(Range || (Range = {})); /** * The Location namespace provides helper functions to work with * [Location](#Location) literals. */ var Location; (function (Location) { /** * Creates a Location literal. * @param uri The location's uri. * @param range The location's range. */ function create(uri, range) { return { uri: uri, range: range }; } Location.create = create; /** * Checks whether the given literal conforms to the [Location](#Location) interface. */ function is(value) { var candidate = value; return Is.defined(candidate) && Range.is(candidate.range) && (Is.string(candidate.uri) || Is.undefined(candidate.uri)); } Location.is = is; })(Location || (Location = {})); /** * The LocationLink namespace provides helper functions to work with * [LocationLink](#LocationLink) literals. */ var LocationLink; (function (LocationLink) { /** * Creates a LocationLink literal. * @param targetUri The definition's uri. * @param targetRange The full range of the definition. * @param targetSelectionRange The span of the symbol definition at the target. * @param originSelectionRange The span of the symbol being defined in the originating source file. */ function create(targetUri, targetRange, targetSelectionRange, originSelectionRange) { return { targetUri: targetUri, targetRange: targetRange, targetSelectionRange: targetSelectionRange, originSelectionRange: originSelectionRange }; } LocationLink.create = create; /** * Checks whether the given literal conforms to the [LocationLink](#LocationLink) interface. */ function is(value) { var candidate = value; return Is.defined(candidate) && Range.is(candidate.targetRange) && Is.string(candidate.targetUri) && (Range.is(candidate.targetSelectionRange) || Is.undefined(candidate.targetSelectionRange)) && (Range.is(candidate.originSelectionRange) || Is.undefined(candidate.originSelectionRange)); } LocationLink.is = is; })(LocationLink || (LocationLink = {})); /** * The Color namespace provides helper functions to work with * [Color](#Color) literals. */ var Color; (function (Color) { /** * Creates a new Color literal. */ function create(red, green, blue, alpha) { return { red: red, green: green, blue: blue, alpha: alpha, }; } Color.create = create; /** * Checks whether the given literal conforms to the [Color](#Color) interface. */ function is(value) { var candidate = value; return Is.numberRange(candidate.red, 0, 1) && Is.numberRange(candidate.green, 0, 1) && Is.numberRange(candidate.blue, 0, 1) && Is.numberRange(candidate.alpha, 0, 1); } Color.is = is; })(Color || (Color = {})); /** * The ColorInformation namespace provides helper functions to work with * [ColorInformation](#ColorInformation) literals. */ var ColorInformation; (function (ColorInformation) { /** * Creates a new ColorInformation literal. */ function create(range, color) { return { range: range, color: color, }; } ColorInformation.create = create; /** * Checks whether the given literal conforms to the [ColorInformation](#ColorInformation) interface. */ function is(value) { var candidate = value; return Range.is(candidate.range) && Color.is(candidate.color); } ColorInformation.is = is; })(ColorInformation || (ColorInformation = {})); /** * The Color namespace provides helper functions to work with * [ColorPresentation](#ColorPresentation) literals. */ var ColorPresentation; (function (ColorPresentation) { /** * Creates a new ColorInformation literal. */ function create(label, textEdit, additionalTextEdits) { return { label: label, textEdit: textEdit, additionalTextEdits: additionalTextEdits, }; } ColorPresentation.create = create; /** * Checks whether the given literal conforms to the [ColorInformation](#ColorInformation) interface. */ function is(value) { var candidate = value; return Is.string(candidate.label) && (Is.undefined(candidate.textEdit) || TextEdit.is(candidate)) && (Is.undefined(candidate.additionalTextEdits) || Is.typedArray(candidate.additionalTextEdits, TextEdit.is)); } ColorPresentation.is = is; })(ColorPresentation || (ColorPresentation = {})); /** * Enum of known range kinds */ var FoldingRangeKind; (function (FoldingRangeKind) { /** * Folding range for a comment */ FoldingRangeKind["Comment"] = "comment"; /** * Folding range for a imports or includes */ FoldingRangeKind["Imports"] = "imports"; /** * Folding range for a region (e.g. `#region`) */ FoldingRangeKind["Region"] = "region"; })(FoldingRangeKind || (FoldingRangeKind = {})); /** * The folding range namespace provides helper functions to work with * [FoldingRange](#FoldingRange) literals. */ var FoldingRange; (function (FoldingRange) { /** * Creates a new FoldingRange literal. */ function create(startLine, endLine, startCharacter, endCharacter, kind) { var result = { startLine: startLine, endLine: endLine }; if (Is.defined(startCharacter)) { result.startCharacter = startCharacter; } if (Is.defined(endCharacter)) { result.endCharacter = endCharacter; } if (Is.defined(kind)) { result.kind = kind; } return result; } FoldingRange.create = create; /** * Checks whether the given literal conforms to the [FoldingRange](#FoldingRange) interface. */ function is(value) { var candidate = value; return Is.uinteger(candidate.startLine) && Is.uinteger(candidate.startLine) && (Is.undefined(candidate.startCharacter) || Is.uinteger(candidate.startCharacter)) && (Is.undefined(candidate.endCharacter) || Is.uinteger(candidate.endCharacter)) && (Is.undefined(candidate.kind) || Is.string(candidate.kind)); } FoldingRange.is = is; })(FoldingRange || (FoldingRange = {})); /** * The DiagnosticRelatedInformation namespace provides helper functions to work with * [DiagnosticRelatedInformation](#DiagnosticRelatedInformation) literals. */ var DiagnosticRelatedInformation; (function (DiagnosticRelatedInformation) { /** * Creates a new DiagnosticRelatedInformation literal. */ function create(location, message) { return { location: location, message: message }; } DiagnosticRelatedInformation.create = create; /** * Checks whether the given literal conforms to the [DiagnosticRelatedInformation](#DiagnosticRelatedInformation) interface. */ function is(value) { var candidate = value; return Is.defined(candidate) && Location.is(candidate.location) && Is.string(candidate.message); } DiagnosticRelatedInformation.is = is; })(DiagnosticRelatedInformation || (DiagnosticRelatedInformation = {})); /** * The diagnostic's severity. */ var DiagnosticSeverity; (function (DiagnosticSeverity) { /** * Reports an error. */ DiagnosticSeverity.Error = 1; /** * Reports a warning. */ DiagnosticSeverity.Warning = 2; /** * Reports an information. */ DiagnosticSeverity.Information = 3; /** * Reports a hint. */ DiagnosticSeverity.Hint = 4; })(DiagnosticSeverity || (DiagnosticSeverity = {})); /** * The diagnostic tags. * * @since 3.15.0 */ var DiagnosticTag; (function (DiagnosticTag) { /** * Unused or unnecessary code. * * Clients are allowed to render diagnostics with this tag faded out instead of having * an error squiggle. */ DiagnosticTag.Unnecessary = 1; /** * Deprecated or obsolete code. * * Clients are allowed to rendered diagnostics with this tag strike through. */ DiagnosticTag.Deprecated = 2; })(DiagnosticTag || (DiagnosticTag = {})); /** * The CodeDescription namespace provides functions to deal with descriptions for diagnostic codes. * * @since 3.16.0 */ var CodeDescription; (function (CodeDescription) { function is(value) { var candidate = value; return candidate !== undefined && candidate !== null && Is.string(candidate.href); } CodeDescription.is = is; })(CodeDescription || (CodeDescription = {})); /** * The Diagnostic namespace provides helper functions to work with * [Diagnostic](#Diagnostic) literals. */ var Diagnostic; (function (Diagnostic) { /** * Creates a new Diagnostic literal. */ function create(range, message, severity, code, source, relatedInformation) { var result = { range: range, message: message }; if (Is.defined(severity)) { result.severity = severity; } if (Is.defined(code)) { result.code = code; } if (Is.defined(source)) { result.source = source; } if (Is.defined(relatedInformation)) { result.relatedInformation = relatedInformation; } return result; } Diagnostic.create = create; /** * Checks whether the given literal conforms to the [Diagnostic](#Diagnostic) interface. */ function is(value) { var _a; var candidate = value; return Is.defined(candidate) && Range.is(candidate.range) && Is.string(candidate.message) && (Is.number(candidate.severity) || Is.undefined(candidate.severity)) && (Is.integer(candidate.code) || Is.string(candidate.code) || Is.undefined(candidate.code)) && (Is.undefined(candidate.codeDescription) || (Is.string((_a = candidate.codeDescription) === null || _a === void 0 ? void 0 : _a.href))) && (Is.string(candidate.source) || Is.undefined(candidate.source)) && (Is.undefined(candidate.relatedInformation) || Is.typedArray(candidate.relatedInformation, DiagnosticRelatedInformation.is)); } Diagnostic.is = is; })(Diagnostic || (Diagnostic = {})); /** * The Command namespace provides helper functions to work with * [Command](#Command) literals. */ var Command; (function (Command) { /** * Creates a new Command literal. */ function create(title, command) { var args = []; for (var _i = 2; _i < arguments.length; _i++) { args[_i - 2] = arguments[_i]; } var result = { title: title, command: command }; if (Is.defined(args) && args.length > 0) { result.arguments = args; } return result; } Command.create = create; /** * Checks whether the given literal conforms to the [Command](#Command) interface. */ function is(value) { var candidate = value; return Is.defined(candidate) && Is.string(candidate.title) && Is.string(candidate.command); } Command.is = is; })(Command || (Command = {})); /** * The TextEdit namespace provides helper function to create replace, * insert and delete edits more easily. */ var TextEdit; (function (TextEdit) { /** * Creates a replace text edit. * @param range The range of text to be replaced. * @param newText The new text. */ function replace(range, newText) { return { range: range, newText: newText }; } TextEdit.replace = replace; /** * Creates a insert text edit. * @param position The position to insert the text at. * @param newText The text to be inserted. */ function insert(position, newText) { return { range: { start: position, end: position }, newText: newText }; } TextEdit.insert = insert; /** * Creates a delete text edit. * @param range The range of text to be deleted. */ function del(range) { return { range: range, newText: '' }; } TextEdit.del = del; function is(value) { var candidate = value; return Is.objectLiteral(candidate) && Is.string(candidate.newText) && Range.is(candidate.range); } TextEdit.is = is; })(TextEdit || (TextEdit = {})); var ChangeAnnotation; (function (ChangeAnnotation) { function create(label, needsConfirmation, description) { var result = { label: label }; if (needsConfirmation !== undefined) { result.needsConfirmation = needsConfirmation; } if (description !== undefined) { result.description = description; } return result; } ChangeAnnotation.create = create; function is(value) { var candidate = value; return candidate !== undefined && Is.objectLiteral(candidate) && Is.string(candidate.label) && (Is.boolean(candidate.needsConfirmation) || candidate.needsConfirmation === undefined) && (Is.string(candidate.description) || candidate.description === undefined); } ChangeAnnotation.is = is; })(ChangeAnnotation || (ChangeAnnotation = {})); var ChangeAnnotationIdentifier; (function (ChangeAnnotationIdentifier) { function is(value) { var candidate = value; return typeof candidate === 'string'; } ChangeAnnotationIdentifier.is = is; })(ChangeAnnotationIdentifier || (ChangeAnnotationIdentifier = {})); var AnnotatedTextEdit; (function (AnnotatedTextEdit) { /** * Creates an annotated replace text edit. * * @param range The range of text to be replaced. * @param newText The new text. * @param annotation The annotation. */ function replace(range, newText, annotation) { return { range: range, newText: newText, annotationId: annotation }; } AnnotatedTextEdit.replace = replace; /** * Creates an annotated insert text edit. * * @param position The position to insert the text at. * @param newText The text to be inserted. * @param annotation The annotation. */ function insert(position, newText, annotation) { return { range: { start: position, end: position }, newText: newText, annotationId: annotation }; } AnnotatedTextEdit.insert = insert; /** * Creates an annotated delete text edit. * * @param range The range of text to be deleted. * @param annotation The annotation. */ function del(range, annotation) { return { range: range, newText: '', annotationId: annotation }; } AnnotatedTextEdit.del = del; function is(value) { var candidate = value; return TextEdit.is(candidate) && (ChangeAnnotation.is(candidate.annotationId) || ChangeAnnotationIdentifier.is(candidate.annotationId)); } AnnotatedTextEdit.is = is; })(AnnotatedTextEdit || (AnnotatedTextEdit = {})); /** * The TextDocumentEdit namespace provides helper function to create * an edit that manipulates a text document. */ var TextDocumentEdit; (function (TextDocumentEdit) { /** * Creates a new `TextDocumentEdit` */ function create(textDocument, edits) { return { textDocument: textDocument, edits: edits }; } TextDocumentEdit.create = create; function is(value) { var candidate = value; return Is.defined(candidate) && OptionalVersionedTextDocumentIdentifier.is(candidate.textDocument) && Array.isArray(candidate.edits); } TextDocumentEdit.is = is; })(TextDocumentEdit || (TextDocumentEdit = {})); var CreateFile; (function (CreateFile) { function create(uri, options, annotation) { var result = { kind: 'create', uri: uri }; if (options !== undefined && (options.overwrite !== undefined || options.ignoreIfExists !== undefined)) { result.options = options; } if (annotation !== undefined) { result.annotationId = annotation; } return result; } CreateFile.create = create; function is(value) { var candidate = value; return candidate && candidate.kind === 'create' && Is.string(candidate.uri) && (candidate.options === undefined || ((candidate.options.overwrite === undefined || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === undefined || Is.boolean(candidate.options.ignoreIfExists)))) && (candidate.annotationId === undefined || ChangeAnnotationIdentifier.is(candidate.annotationId)); } CreateFile.is = is; })(CreateFile || (CreateFile = {})); var RenameFile; (function (RenameFile) { function create(oldUri, newUri, options, annotation) { var result = { kind: 'rename', oldUri: oldUri, newUri: newUri }; if (options !== undefined && (options.overwrite !== undefined || options.ignoreIfExists !== undefined)) { result.options = options; } if (annotation !== undefined) { result.annotationId = annotation; } return result; } RenameFile.create = create; function is(value) { var candidate = value; return candidate && candidate.kind === 'rename' && Is.string(candidate.oldUri) && Is.string(candidate.newUri) && (candidate.options === undefined || ((candidate.options.overwrite === undefined || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === undefined || Is.boolean(candidate.options.ignoreIfExists)))) && (candidate.annotationId === undefined || ChangeAnnotationIdentifier.is(candidate.annotationId)); } RenameFile.is = is; })(RenameFile || (RenameFile = {})); var DeleteFile; (function (DeleteFile) { function create(uri, options, annotation) { var result = { kind: 'delete', uri: uri }; if (options !== undefined && (options.recursive !== undefined || options.ignoreIfNotExists !== undefined)) { result.options = options; } if (annotation !== undefined) { result.annotationId = annotation; } return result; } DeleteFile.create = create; function is(value) { var candidate = value; return candidate && candidate.kind === 'delete' && Is.string(candidate.uri) && (candidate.options === undefined || ((candidate.options.recursive === undefined || Is.boolean(candidate.options.recursive)) && (candidate.options.ignoreIfNotExists === undefined || Is.boolean(candidate.options.ignoreIfNotExists)))) && (candidate.annotationId === undefined || ChangeAnnotationIdentifier.is(candidate.annotationId)); } DeleteFile.is = is; })(DeleteFile || (DeleteFile = {})); var WorkspaceEdit; (function (WorkspaceEdit) { function is(value) { var candidate = value; return candidate && (candidate.changes !== undefined || candidate.documentChanges !== undefined) && (candidate.documentChanges === undefined || candidate.documentChanges.every(function (change) { if (Is.string(change.kind)) { return CreateFile.is(change) || RenameFile.is(change) || DeleteFile.is(change); } else { return TextDocumentEdit.is(change); } })); } WorkspaceEdit.is = is; })(WorkspaceEdit || (WorkspaceEdit = {})); var TextEditChangeImpl = /** @class */ (function () { function TextEditChangeImpl(edits, changeAnnotations) { this.edits = edits; this.changeAnnotations = changeAnnotations; } TextEditChangeImpl.prototype.insert = function (position, newText, annotation) { var edit; var id; if (annotation === undefined) { edit = TextEdit.insert(position, newText); } else if (ChangeAnnotationIdentifier.is(annotation)) { id = annotation; edit = AnnotatedTextEdit.insert(position, newText, annotation); } else { this.assertChangeAnnotations(this.changeAnnotations); id = this.changeAnnotations.manage(annotation); edit = AnnotatedTextEdit.insert(position, newText, id); } this.edits.push(edit); if (id !== undefined) { return id; } }; TextEditChangeImpl.prototype.replace = function (range, newText, annotation) { var edit; var id; if (annotation === undefined) { edit = TextEdit.replace(range, newText); } else if (ChangeAnnotationIdentifier.is(annotation)) { id = annotation; edit = AnnotatedTextEdit.replace(range, newText, annotation); } else { this.assertChangeAnnotations(this.changeAnnotations); id = this.changeAnnotations.manage(annotation); edit = AnnotatedTextEdit.replace(range, newText, id); } this.edits.push(edit); if (id !== undefined) { return id; } }; TextEditChangeImpl.prototype.delete = function (range, annotation) { var edit; var id; if (annotation === undefined) { edit = TextEdit.del(range); } else if (ChangeAnnotationIdentifier.is(annotation)) { id = annotation; edit = AnnotatedTextEdit.del(range, annotation); } else { this.assertChangeAnnotations(this.changeAnnotations); id = this.changeAnnotations.manage(annotation); edit = AnnotatedTextEdit.del(range, id); } this.edits.push(edit); if (id !== undefined) { return id; } }; TextEditChangeImpl.prototype.add = function (edit) { this.edits.push(edit); }; TextEditChangeImpl.prototype.all = function () { return this.edits; }; TextEditChangeImpl.prototype.clear = function () { this.edits.splice(0, this.edits.length); }; TextEditChangeImpl.prototype.assertChangeAnnotations = function (value) { if (value === undefined) { throw new Error("Text edit change is not configured to manage change annotations."); } }; return TextEditChangeImpl; }()); /** * A helper class */ var ChangeAnnotations = /** @class */ (function () { function ChangeAnnotations(annotations) { this._annotations = annotations === undefined ? Object.create(null) : annotations; this._counter = 0; this._size = 0; } ChangeAnnotations.prototype.all = function () { return this._annotations; }; Object.defineProperty(ChangeAnnotations.prototype, "size", { get: function () { return this._size; }, enumerable: false, configurable: true }); ChangeAnnotations.prototype.manage = function (idOrAnnotation, annotation) { var id; if (ChangeAnnotationIdentifier.is(idOrAnnotation)) { id = idOrAnnotation; } else { id = this.nextId(); annotation = idOrAnnotation; } if (this._annotations[id] !== undefined) { throw new Error("Id " + id + " is already in use."); } if (annotation === undefined) { throw new Error("No annotation provided for id " + id); } this._annotations[id] = annotation; this._size++; return id; }; ChangeAnnotations.prototype.nextId = function () { this._counter++; return this._counter.toString(); }; return ChangeAnnotations; }()); /** * A workspace change helps constructing changes to a workspace. */ var WorkspaceChange = /** @class */ (function () { function WorkspaceChange(workspaceEdit) { var _this = this; this._textEditChanges = Object.create(null); if (workspaceEdit !== undefined) { this._workspaceEdit = workspaceEdit; if (workspaceEdit.documentChanges) { this._changeAnnotations = new ChangeAnnotations(workspaceEdit.changeAnnotations); workspaceEdit.changeAnnotations = this._changeAnnotations.all(); workspaceEdit.documentChanges.forEach(function (change) { if (TextDocumentEdit.is(change)) { var textEditChange = new TextEditChangeImpl(change.edits, _this._changeAnnotations); _this._textEditChanges[change.textDocument.uri] = textEditChange; } }); } else if (workspaceEdit.changes) { Object.keys(workspaceEdit.changes).forEach(function (key) { var textEditChange = new TextEditChangeImpl(workspaceEdit.changes[key]); _this._textEditChanges[key] = textEditChange; }); } } else { this._workspaceEdit = {}; } } Object.defineProperty(WorkspaceChange.prototype, "edit", { /** * Returns the underlying [WorkspaceEdit](#WorkspaceEdit) literal * use to be returned from a workspace edit operation like rename. */ get: function () { this.initDocumentChanges(); if (this._changeAnnotations !== undefined) { if (this._changeAnnotations.size === 0) { this._workspaceEdit.changeAnnotations = undefined; } else { this._workspaceEdit.changeAnnotations = this._changeAnnotations.all(); } } return this._workspaceEdit; }, enumerable: false, configurable: true }); WorkspaceChange.prototype.getTextEditChange = function (key) { if (OptionalVersionedTextDocumentIdentifier.is(key)) { this.initDocumentChanges(); if (this._workspaceEdit.documentChanges === undefined) { throw new Error('Workspace edit is not configured for document changes.'); } var textDocument = { uri: key.uri, version: key.version }; var result = this._textEditChanges[textDocument.uri]; if (!result) { var edits = []; var textDocumentEdit = { textDocument: textDocument, edits: edits }; this._workspaceEdit.documentChanges.push(textDocumentEdit); result = new TextEditChangeImpl(edits, this._changeAnnotations); this._textEditChanges[textDocument.uri] = result; } return result; } else { this.initChanges(); if (this._workspaceEdit.changes === undefined) { throw new Error('Workspace edit is not configured for normal text edit changes.'); } var result = this._textEditChanges[key]; if (!result) { var edits = []; this._workspaceEdit.changes[key] = edits; result = new TextEditChangeImpl(edits); this._textEditChanges[key] = result; } return result; } }; WorkspaceChange.prototype.initDocumentChanges = function () { if (this._workspaceEdit.documentChanges === undefined && this._workspaceEdit.changes === undefined) { this._changeAnnotations = new ChangeAnnotations(); this._workspaceEdit.documentChanges = []; this._workspaceEdit.changeAnnotations = this._changeAnnotations.all(); } }; WorkspaceChange.prototype.initChanges = function () { if (this._workspaceEdit.documentChanges === undefined && this._workspaceEdit.changes === undefined) { this._workspaceEdit.changes = Object.create(null); } }; WorkspaceChange.prototype.createFile = function (uri, optionsOrAnnotation, options) { this.initDocumentChanges(); if (this._workspaceEdit.documentChanges === undefined) { throw new Error('Workspace edit is not configured for document changes.'); } var annotation; if (ChangeAnnotation.is(optionsOrAnnotation) || ChangeAnnotationIdentifier.is(optionsOrAnnotation)) { annotation = optionsOrAnnotation; } else { options = optionsOrAnnotation; } var operation; var id; if (annotation === undefined) { operation = CreateFile.create(uri, options); } else { id = ChangeAnnotationIdentifier.is(annotation) ? annotation : this._changeAnnotations.manage(annotation); operation = CreateFile.create(uri, options, id); } this._workspaceEdit.documentChanges.push(operation); if (id !== undefined) { return id; } }; WorkspaceChange.prototype.renameFile = function (oldUri, newUri, optionsOrAnnotation, options) { this.initDocumentChanges(); if (this._workspaceEdit.documentChanges === undefined) { throw new Error('Workspace edit is not configured for document changes.'); } var annotation; if (ChangeAnnotation.is(optionsOrAnnotation) || ChangeAnnotationIdentifier.is(optionsOrAnnotation)) { annotation = optionsOrAnnotation; } else { options = optionsOrAnnotation; } var operation; var id; if (annotation === undefined) { operation = RenameFile.create(oldUri, newUri, options); } else { id = ChangeAnnotationIdentifier.is(annotation) ? annotation : this._changeAnnotations.manage(annotation); operation = RenameFile.create(oldUri, newUri, options, id); } this._workspaceEdit.documentChanges.push(operation); if (id !== undefined) { return id; } }; WorkspaceChange.prototype.deleteFile = function (uri, optionsOrAnnotation, options) { this.initDocumentChanges(); if (this._workspaceEdit.documentChanges === undefined) { throw new Error('Workspace edit is not configured for document changes.'); } var annotation; if (ChangeAnnotation.is(optionsOrAnnotation) || ChangeAnnotationIdentifier.is(optionsOrAnnotation)) { annotation = optionsOrAnnotation; } else { options = optionsOrAnnotation; } var operation; var id; if (annotation === undefined) { operation = DeleteFile.create(uri, options); } else { id = ChangeAnnotationIdentifier.is(annotation) ? annotation : this._changeAnnotations.manage(annotation); operation = DeleteFile.create(uri, options, id); } this._workspaceEdit.documentChanges.push(operation); if (id !== undefined) { return id; } }; return WorkspaceChange; }()); /** * The TextDocumentIdentifier namespace provides helper functions to work with * [TextDocumentIdentifier](#TextDocumentIdentifier) literals. */ var TextDocumentIdentifier; (function (TextDocumentIdentifier) { /** * Creates a new TextDocumentIdentifier literal. * @param uri The document's uri. */ function create(uri) { return { uri: uri }; } TextDocumentIdentifier.create = create; /** * Checks whether the given literal conforms to the [TextDocumentIdentifier](#TextDocumentIdentifier) interface. */ function is(value) { var candidate = value; return Is.defined(candidate) && Is.string(candidate.uri); } TextDocumentIdentifier.is = is; })(TextDocumentIdentifier || (TextDocumentIdentifier = {})); /** * The VersionedTextDocumentIdentifier namespace provides helper functions to work with * [VersionedTextDocumentIdentifier](#VersionedTextDocumentIdentifier) literals. */ var VersionedTextDocumentIdentifier; (function (VersionedTextDocumentIdentifier) { /** * Creates a new VersionedTextDocumentIdentifier literal. * @param uri The document's uri. * @param uri The document's text. */ function create(uri, version) { return { uri: uri, version: version }; } VersionedTextDocumentIdentifier.create = create; /** * Checks whether the given literal conforms to the [VersionedTextDocumentIdentifier](#VersionedTextDocumentIdentifier) interface. */ function is(value) { var candidate = value; return Is.defined(candidate) && Is.string(candidate.uri) && Is.integer(candidate.version); } VersionedTextDocumentIdentifier.is = is; })(VersionedTextDocumentIdentifier || (VersionedTextDocumentIdentifier = {})); /** * The OptionalVersionedTextDocumentIdentifier namespace provides helper functions to work with * [OptionalVersionedTextDocumentIdentifier](#OptionalVersionedTextDocumentIdentifier) literals. */ var OptionalVersionedTextDocumentIdentifier; (function (OptionalVersionedTextDocumentIdentifier) { /** * Creates a new OptionalVersionedTextDocumentIdentifier literal. * @param uri The document's uri. * @param uri The document's text. */ function create(uri, version) { return { uri: uri, version: version }; } OptionalVersionedTextDocumentIdentifier.create = create; /** * Checks whether the given literal conforms to the [OptionalVersionedTextDocumentIdentifier](#OptionalVersionedTextDocumentIdentifier) interface. */ function is(value) { var candidate = value; return Is.defined(candidate) && Is.string(candidate.uri) && (candidate.version === null || Is.integer(candidate.version)); } OptionalVersionedTextDocumentIdentifier.is = is; })(OptionalVersionedTextDocumentIdentifier || (OptionalVersionedTextDocumentIdentifier = {})); /** * The TextDocumentItem namespace provides helper functions to work with * [TextDocumentItem](#TextDocumentItem) literals. */ var TextDocumentItem; (function (TextDocumentItem) { /** * Creates a new TextDocumentItem literal. * @param uri The document's uri. * @param languageId The document's language identifier. * @param version The document's version number. * @param text The document's text. */ function create(uri, languageId, version, text) { return { uri: uri, languageId: languageId, version: version, text: text }; } TextDocumentItem.create = create; /** * Checks whether the given literal conforms to the [TextDocumentItem](#TextDocumentItem) interface. */ function is(value) { var candidate = value; return Is.defined(candidate) && Is.string(candidate.uri) && Is.string(candidate.languageId) && Is.integer(candidate.version) && Is.string(candidate.text); } TextDocumentItem.is = is; })(TextDocumentItem || (TextDocumentItem = {})); /** * Describes the content type that a client supports in various * result literals like `Hover`, `ParameterInfo` or `CompletionItem`. * * Please note that `MarkupKinds` must not start with a `$`. This kinds * are reserved for internal usage. */ var MarkupKind; (function (MarkupKind) { /** * Plain text is supported as a content format */ MarkupKind.PlainText = 'plaintext'; /** * Markdown is supported as a content format */ MarkupKind.Markdown = 'markdown'; })(MarkupKind || (MarkupKind = {})); (function (MarkupKind) { /** * Checks whether the given value is a value of the [MarkupKind](#MarkupKind) type. */ function is(value) { var candidate = value; return candidate === MarkupKind.PlainText || candidate === MarkupKind.Markdown; } MarkupKind.is = is; })(MarkupKind || (MarkupKind = {})); var MarkupContent; (function (MarkupContent) { /** * Checks whether the given value conforms to the [MarkupContent](#MarkupContent) interface. */ function is(value) { var candidate = value; return Is.objectLiteral(value) && MarkupKind.is(candidate.kind) && Is.string(candidate.value); } MarkupContent.is = is; })(MarkupContent || (MarkupContent = {})); /** * The kind of a completion entry. */ var CompletionItemKind; (function (CompletionItemKind) { CompletionItemKind.Text = 1; CompletionItemKind.Method = 2; CompletionItemKind.Function = 3; CompletionItemKind.Constructor = 4; CompletionItemKind.Field = 5; CompletionItemKind.Variable = 6; CompletionItemKind.Class = 7; CompletionItemKind.Interface = 8; CompletionItemKind.Module = 9; CompletionItemKind.Property = 10; CompletionItemKind.Unit = 11; CompletionItemKind.Value = 12; CompletionItemKind.Enum = 13; CompletionItemKind.Keyword = 14; CompletionItemKind.Snippet = 15; CompletionItemKind.Color = 16; CompletionItemKind.File = 17; CompletionItemKind.Reference = 18; CompletionItemKind.Folder = 19; CompletionItemKind.EnumMember = 20; CompletionItemKind.Constant = 21; CompletionItemKind.Struct = 22; CompletionItemKind.Event = 23; CompletionItemKind.Operator = 24; CompletionItemKind.TypeParameter = 25; })(CompletionItemKind || (CompletionItemKind = {})); /** * Defines whether the insert text in a completion item should be interpreted as * plain text or a snippet. */ var InsertTextFormat; (function (InsertTextFormat) { /** * The primary text to be inserted is treated as a plain string. */ InsertTextFormat.PlainText = 1; /** * The primary text to be inserted is treated as a snippet. * * A snippet can define tab stops and placeholders with `$1`, `$2` * and `${3:foo}`. `$0` defines the final tab stop, it defaults to * the end of the snippet. Placeholders with equal identifiers are linked, * that is typing in one will update others too. * * See also: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#snippet_syntax */ InsertTextFormat.Snippet = 2; })(InsertTextFormat || (InsertTextFormat = {})); /** * Completion item tags are extra annotations that tweak the rendering of a completion * item. * * @since 3.15.0 */ var CompletionItemTag; (function (CompletionItemTag) { /** * Render a completion as obsolete, usually using a strike-out. */ CompletionItemTag.Deprecated = 1; })(CompletionItemTag || (CompletionItemTag = {})); /** * The InsertReplaceEdit namespace provides functions to deal with insert / replace edits. * * @since 3.16.0 */ var InsertReplaceEdit; (function (InsertReplaceEdit) { /** * Creates a new insert / replace edit */ function create(newText, insert, replace) { return { newText: newText, insert: insert, replace: replace }; } InsertReplaceEdit.create = create; /** * Checks whether the given literal conforms to the [InsertReplaceEdit](#InsertReplaceEdit) interface. */ function is(value) { var candidate = value; return candidate && Is.string(candidate.newText) && Range.is(candidate.insert) && Range.is(candidate.replace); } InsertReplaceEdit.is = is; })(InsertReplaceEdit || (InsertReplaceEdit = {})); /** * How whitespace and indentation is handled during completion * item insertion. * * @since 3.16.0 */ var InsertTextMode; (function (InsertTextMode) { /** * The insertion or replace strings is taken as it is. If the * value is multi line the lines below the cursor will be * inserted using the indentation defined in the string value. * The client will not apply any kind of adjustments to the * string. */ InsertTextMode.asIs = 1; /** * The editor adjusts leading whitespace of new lines so that * they match the indentation up to the cursor of the line for * which the item is accepted. * * Consider a line like this: <2tabs><3tabs>foo. Accepting a * multi line completion item is indented using 2 tabs and all * following lines inserted will be indented using 2 tabs as well. */ InsertTextMode.adjustIndentation = 2; })(InsertTextMode || (InsertTextMode = {})); /** * The CompletionItem namespace provides functions to deal with * completion items. */ var CompletionItem; (function (CompletionItem) { /** * Create a completion item and seed it with a label. * @param label The completion item's label */ function create(label) { return { label: label }; } CompletionItem.create = create; })(CompletionItem || (CompletionItem = {})); /** * The CompletionList namespace provides functions to deal with * completion lists. */ var CompletionList; (function (CompletionList) { /** * Creates a new completion list. * * @param items The completion items. * @param isIncomplete The list is not complete. */ function create(items, isIncomplete) { return { items: items ? items : [], isIncomplete: !!isIncomplete }; } CompletionList.create = create; })(CompletionList || (CompletionList = {})); var MarkedString; (function (MarkedString) { /** * Creates a marked string from plain text. * * @param plainText The plain text. */ function fromPlainText(plainText) { return plainText.replace(/[\\`*_{}[\]()#+\-.!]/g, '\\$&'); // escape markdown syntax tokens: http://daringfireball.net/projects/markdown/syntax#backslash } MarkedString.fromPlainText = fromPlainText; /** * Checks whether the given value conforms to the [MarkedString](#MarkedString) type. */ function is(value) { var candidate = value; return Is.string(candidate) || (Is.objectLiteral(candidate) && Is.string(candidate.language) && Is.string(candidate.value)); } MarkedString.is = is; })(MarkedString || (MarkedString = {})); var Hover; (function (Hover) { /** * Checks whether the given value conforms to the [Hover](#Hover) interface. */ function is(value) { var candidate = value; return !!candidate && Is.objectLiteral(candidate) && (MarkupContent.is(candidate.contents) || MarkedString.is(candidate.contents) || Is.typedArray(candidate.contents, MarkedString.is)) && (value.range === undefined || Range.is(value.range)); } Hover.is = is; })(Hover || (Hover = {})); /** * The ParameterInformation namespace provides helper functions to work with * [ParameterInformation](#ParameterInformation) literals. */ var ParameterInformation; (function (ParameterInformation) { /** * Creates a new parameter information literal. * * @param label A label string. * @param documentation A doc string. */ function create(label, documentation) { return documentation ? { label: label, documentation: documentation } : { label: label }; } ParameterInformation.create = create; })(ParameterInformation || (ParameterInformation = {})); /** * The SignatureInformation namespace provides helper functions to work with * [SignatureInformation](#SignatureInformation) literals. */ var SignatureInformation; (function (SignatureInformation) { function create(label, documentation) { var parameters = []; for (var _i = 2; _i < arguments.length; _i++) { parameters[_i - 2] = arguments[_i]; } var result = { label: label }; if (Is.defined(documentation)) { result.documentation = documentation; } if (Is.defined(parameters)) { result.parameters = parameters; } else { result.parameters = []; } return result; } SignatureInformation.create = create; })(SignatureInformation || (SignatureInformation = {})); /** * A document highlight kind. */ var DocumentHighlightKind; (function (DocumentHighlightKind) { /** * A textual occurrence. */ DocumentHighlightKind.Text = 1; /** * Read-access of a symbol, like reading a variable. */ DocumentHighlightKind.Read = 2; /** * Write-access of a symbol, like writing to a variable. */ DocumentHighlightKind.Write = 3; })(DocumentHighlightKind || (DocumentHighlightKind = {})); /** * DocumentHighlight namespace to provide helper functions to work with * [DocumentHighlight](#DocumentHighlight) literals. */ var DocumentHighlight; (function (DocumentHighlight) { /** * Create a DocumentHighlight object. * @param range The range the highlight applies to. */ function create(range, kind) { var result = { range: range }; if (Is.number(kind)) { result.kind = kind; } return result; } DocumentHighlight.create = create; })(DocumentHighlight || (DocumentHighlight = {})); /** * A symbol kind. */ var SymbolKind; (function (SymbolKind) { SymbolKind.File = 1; SymbolKind.Module = 2; SymbolKind.Namespace = 3; SymbolKind.Package = 4; SymbolKind.Class = 5; SymbolKind.Method = 6; SymbolKind.Property = 7; SymbolKind.Field = 8; SymbolKind.Constructor = 9; SymbolKind.Enum = 10; SymbolKind.Interface = 11; SymbolKind.Function = 12; SymbolKind.Variable = 13; SymbolKind.Constant = 14; SymbolKind.String = 15; SymbolKind.Number = 16; SymbolKind.Boolean = 17; SymbolKind.Array = 18; SymbolKind.Object = 19; SymbolKind.Key = 20; SymbolKind.Null = 21; SymbolKind.EnumMember = 22; SymbolKind.Struct = 23; SymbolKind.Event = 24; SymbolKind.Operator = 25; SymbolKind.TypeParameter = 26; })(SymbolKind || (SymbolKind = {})); /** * Symbol tags are extra annotations that tweak the rendering of a symbol. * @since 3.16 */ var SymbolTag; (function (SymbolTag) { /** * Render a symbol as obsolete, usually using a strike-out. */ SymbolTag.Deprecated = 1; })(SymbolTag || (SymbolTag = {})); var SymbolInformation; (function (SymbolInformation) { /** * Creates a new symbol information literal. * * @param name The name of the symbol. * @param kind The kind of the symbol. * @param range The range of the location of the symbol. * @param uri The resource of the location of symbol, defaults to the current document. * @param containerName The name of the symbol containing the symbol. */ function create(name, kind, range, uri, containerName) { var result = { name: name, kind: kind, location: { uri: uri, range: range } }; if (containerName) { result.containerName = containerName; } return result; } SymbolInformation.create = create; })(SymbolInformation || (SymbolInformation = {})); var DocumentSymbol; (function (DocumentSymbol) { /** * Creates a new symbol information literal. * * @param name The name of the symbol. * @param detail The detail of the symbol. * @param kind The kind of the symbol. * @param range The range of the symbol. * @param selectionRange The selectionRange of the symbol. * @param children Children of the symbol. */ function create(name, detail, kind, range, selectionRange, children) { var result = { name: name, detail: detail, kind: kind, range: range, selectionRange: selectionRange }; if (children !== undefined) { result.children = children; } return result; } DocumentSymbol.create = create; /** * Checks whether the given literal conforms to the [DocumentSymbol](#DocumentSymbol) interface. */ function is(value) { var candidate = value; return candidate && Is.string(candidate.name) && Is.number(candidate.kind) && Range.is(candidate.range) && Range.is(candidate.selectionRange) && (candidate.detail === undefined || Is.string(candidate.detail)) && (candidate.deprecated === undefined || Is.boolean(candidate.deprecated)) && (candidate.children === undefined || Array.isArray(candidate.children)) && (candidate.tags === undefined || Array.isArray(candidate.tags)); } DocumentSymbol.is = is; })(DocumentSymbol || (DocumentSymbol = {})); /** * A set of predefined code action kinds */ var CodeActionKind; (function (CodeActionKind) { /** * Empty kind. */ CodeActionKind.Empty = ''; /** * Base kind for quickfix actions: 'quickfix' */ CodeActionKind.QuickFix = 'quickfix'; /** * Base kind for refactoring actions: 'refactor' */ CodeActionKind.Refactor = 'refactor'; /** * Base kind for refactoring extraction actions: 'refactor.extract' * * Example extract actions: * * - Extract method * - Extract function * - Extract variable * - Extract interface from class * - ... */ CodeActionKind.RefactorExtract = 'refactor.extract'; /** * Base kind for refactoring inline actions: 'refactor.inline' * * Example inline actions: * * - Inline function * - Inline variable * - Inline constant * - ... */ CodeActionKind.RefactorInline = 'refactor.inline'; /** * Base kind for refactoring rewrite actions: 'refactor.rewrite' * * Example rewrite actions: * * - Convert JavaScript function to class * - Add or remove parameter * - Encapsulate field * - Make method static * - Move method to base class * - ... */ CodeActionKind.RefactorRewrite = 'refactor.rewrite'; /** * Base kind for source actions: `source` * * Source code actions apply to the entire file. */ CodeActionKind.Source = 'source'; /** * Base kind for an organize imports source action: `source.organizeImports` */ CodeActionKind.SourceOrganizeImports = 'source.organizeImports'; /** * Base kind for auto-fix source actions: `source.fixAll`. * * Fix all actions automatically fix errors that have a clear fix that do not require user input. * They should not suppress errors or perform unsafe fixes such as generating new types or classes. * * @since 3.15.0 */ CodeActionKind.SourceFixAll = 'source.fixAll'; })(CodeActionKind || (CodeActionKind = {})); /** * The CodeActionContext namespace provides helper functions to work with * [CodeActionContext](#CodeActionContext) literals. */ var CodeActionContext; (function (CodeActionContext) { /** * Creates a new CodeActionContext literal. */ function create(diagnostics, only) { var result = { diagnostics: diagnostics }; if (only !== undefined && only !== null) { result.only = only; } return result; } CodeActionContext.create = create; /** * Checks whether the given literal conforms to the [CodeActionContext](#CodeActionContext) interface. */ function is(value) { var candidate = value; return Is.defined(candidate) && Is.typedArray(candidate.diagnostics, Diagnostic.is) && (candidate.only === undefined || Is.typedArray(candidate.only, Is.string)); } CodeActionContext.is = is; })(CodeActionContext || (CodeActionContext = {})); var CodeAction; (function (CodeAction) { function create(title, kindOrCommandOrEdit, kind) { var result = { title: title }; var checkKind = true; if (typeof kindOrCommandOrEdit === 'string') { checkKind = false; result.kind = kindOrCommandOrEdit; } else if (Command.is(kindOrCommandOrEdit)) { result.command = kindOrCommandOrEdit; } else { result.edit = kindOrCommandOrEdit; } if (checkKind && kind !== undefined) { result.kind = kind; } return result; } CodeAction.create = create; function is(value) { var candidate = value; return candidate && Is.string(candidate.title) && (candidate.diagnostics === undefined || Is.typedArray(candidate.diagnostics, Diagnostic.is)) && (candidate.kind === undefined || Is.string(candidate.kind)) && (candidate.edit !== undefined || candidate.command !== undefined) && (candidate.command === undefined || Command.is(candidate.command)) && (candidate.isPreferred === undefined || Is.boolean(candidate.isPreferred)) && (candidate.edit === undefined || WorkspaceEdit.is(candidate.edit)); } CodeAction.is = is; })(CodeAction || (CodeAction = {})); /** * The CodeLens namespace provides helper functions to work with * [CodeLens](#CodeLens) literals. */ var CodeLens; (function (CodeLens) { /** * Creates a new CodeLens literal. */ function create(range, data) { var result = { range: range }; if (Is.defined(data)) { result.data = data; } return result; } CodeLens.create = create; /** * Checks whether the given literal conforms to the [CodeLens](#CodeLens) interface. */ function is(value) { var candidate = value; return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.command) || Command.is(candidate.command)); } CodeLens.is = is; })(CodeLens || (CodeLens = {})); /** * The FormattingOptions namespace provides helper functions to work with * [FormattingOptions](#FormattingOptions) literals. */ var FormattingOptions; (function (FormattingOptions) { /** * Creates a new FormattingOptions literal. */ function create(tabSize, insertSpaces) { return { tabSize: tabSize, insertSpaces: insertSpaces }; } FormattingOptions.create = create; /** * Checks whether the given literal conforms to the [FormattingOptions](#FormattingOptions) interface. */ function is(value) { var candidate = value; return Is.defined(candidate) && Is.uinteger(candidate.tabSize) && Is.boolean(candidate.insertSpaces); } FormattingOptions.is = is; })(FormattingOptions || (FormattingOptions = {})); /** * The DocumentLink namespace provides helper functions to work with * [DocumentLink](#DocumentLink) literals. */ var DocumentLink; (function (DocumentLink) { /** * Creates a new DocumentLink literal. */ function create(range, target, data) { return { range: range, target: target, data: data }; } DocumentLink.create = create; /** * Checks whether the given literal conforms to the [DocumentLink](#DocumentLink) interface. */ function is(value) { var candidate = value; return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.target) || Is.string(candidate.target)); } DocumentLink.is = is; })(DocumentLink || (DocumentLink = {})); /** * The SelectionRange namespace provides helper function to work with * SelectionRange literals. */ var SelectionRange; (function (SelectionRange) { /** * Creates a new SelectionRange * @param range the range. * @param parent an optional parent. */ function create(range, parent) { return { range: range, parent: parent }; } SelectionRange.create = create; function is(value) { var candidate = value; return candidate !== undefined && Range.is(candidate.range) && (candidate.parent === undefined || SelectionRange.is(candidate.parent)); } SelectionRange.is = is; })(SelectionRange || (SelectionRange = {})); var EOL = ['\n', '\r\n', '\r']; /** * @deprecated Use the text document from the new vscode-languageserver-textdocument package. */ var TextDocument; (function (TextDocument) { /** * Creates a new ITextDocument literal from the given uri and content. * @param uri The document's uri. * @param languageId The document's language Id. * @param content The document's content. */ function create(uri, languageId, version, content) { return new FullTextDocument(uri, languageId, version, content); } TextDocument.create = create; /** * Checks whether the given literal conforms to the [ITextDocument](#ITextDocument) interface. */ function is(value) { var candidate = value; return Is.defined(candidate) && Is.string(candidate.uri) && (Is.undefined(candidate.languageId) || Is.string(candidate.languageId)) && Is.uinteger(candidate.lineCount) && Is.func(candidate.getText) && Is.func(candidate.positionAt) && Is.func(candidate.offsetAt) ? true : false; } TextDocument.is = is; function applyEdits(document, edits) { var text = document.getText(); var sortedEdits = mergeSort(edits, function (a, b) { var diff = a.range.start.line - b.range.start.line; if (diff === 0) { return a.range.start.character - b.range.start.character; } return diff; }); var lastModifiedOffset = text.length; for (var i = sortedEdits.length - 1; i >= 0; i--) { var e = sortedEdits[i]; var startOffset = document.offsetAt(e.range.start); var endOffset = document.offsetAt(e.range.end); if (endOffset <= lastModifiedOffset) { text = text.substring(0, startOffset) + e.newText + text.substring(endOffset, text.length); } else { throw new Error('Overlapping edit'); } lastModifiedOffset = startOffset; } return text; } TextDocument.applyEdits = applyEdits; function mergeSort(data, compare) { if (data.length <= 1) { // sorted return data; } var p = (data.length / 2) | 0; var left = data.slice(0, p); var right = data.slice(p); mergeSort(left, compare); mergeSort(right, compare); var leftIdx = 0; var rightIdx = 0; var i = 0; while (leftIdx < left.length && rightIdx < right.length) { var ret = compare(left[leftIdx], right[rightIdx]); if (ret <= 0) { // smaller_equal -> take left to preserve order data[i++] = left[leftIdx++]; } else { // greater -> take right data[i++] = right[rightIdx++]; } } while (leftIdx < left.length) { data[i++] = left[leftIdx++]; } while (rightIdx < right.length) { data[i++] = right[rightIdx++]; } return data; } })(TextDocument || (TextDocument = {})); /** * @deprecated Use the text document from the new vscode-languageserver-textdocument package. */ var FullTextDocument = /** @class */ (function () { function FullTextDocument(uri, languageId, version, content) { this._uri = uri; this._languageId = languageId; this._version = version; this._content = content; this._lineOffsets = undefined; } Object.defineProperty(FullTextDocument.prototype, "uri", { get: function () { return this._uri; }, enumerable: false, configurable: true }); Object.defineProperty(FullTextDocument.prototype, "languageId", { get: function () { return this._languageId; }, enumerable: false, configurable: true }); Object.defineProperty(FullTextDocument.prototype, "version", { get: function () { return this._version; }, enumerable: false, configurable: true }); FullTextDocument.prototype.getText = function (range) { if (range) { var start = this.offsetAt(range.start); var end = this.offsetAt(range.end); return this._content.substring(start, end); } return this._content; }; FullTextDocument.prototype.update = function (event, version) { this._content = event.text; this._version = version; this._lineOffsets = undefined; }; FullTextDocument.prototype.getLineOffsets = function () { if (this._lineOffsets === undefined) { var lineOffsets = []; var text = this._content; var isLineStart = true; for (var i = 0; i < text.length; i++) { if (isLineStart) { lineOffsets.push(i); isLineStart = false; } var ch = text.charAt(i); isLineStart = (ch === '\r' || ch === '\n'); if (ch === '\r' && i + 1 < text.length && text.charAt(i + 1) === '\n') { i++; } } if (isLineStart && text.length > 0) { lineOffsets.push(text.length); } this._lineOffsets = lineOffsets; } return this._lineOffsets; }; FullTextDocument.prototype.positionAt = function (offset) { offset = Math.max(Math.min(offset, this._content.length), 0); var lineOffsets = this.getLineOffsets(); var low = 0, high = lineOffsets.length; if (high === 0) { return Position.create(0, offset); } while (low < high) { var mid = Math.floor((low + high) / 2); if (lineOffsets[mid] > offset) { high = mid; } else { low = mid + 1; } } // low is the least x for which the line offset is larger than the current offset // or array.length if no line offset is larger than the current offset var line = low - 1; return Position.create(line, offset - lineOffsets[line]); }; FullTextDocument.prototype.offsetAt = function (position) { var lineOffsets = this.getLineOffsets(); if (position.line >= lineOffsets.length) { return this._content.length; } else if (position.line < 0) { return 0; } var lineOffset = lineOffsets[position.line]; var nextLineOffset = (position.line + 1 < lineOffsets.length) ? lineOffsets[position.line + 1] : this._content.length; return Math.max(Math.min(lineOffset + position.character, nextLineOffset), lineOffset); }; Object.defineProperty(FullTextDocument.prototype, "lineCount", { get: function () { return this.getLineOffsets().length; }, enumerable: false, configurable: true }); return FullTextDocument; }()); var Is; (function (Is) { var toString = Object.prototype.toString; function defined(value) { return typeof value !== 'undefined'; } Is.defined = defined; function undefined(value) { return typeof value === 'undefined'; } Is.undefined = undefined; function boolean(value) { return value === true || value === false; } Is.boolean = boolean; function string(value) { return toString.call(value) === '[object String]'; } Is.string = string; function number(value) { return toString.call(value) === '[object Number]'; } Is.number = number; function numberRange(value, min, max) { return toString.call(value) === '[object Number]' && min <= value && value <= max; } Is.numberRange = numberRange; function integer(value) { return toString.call(value) === '[object Number]' && -2147483648 <= value && value <= 2147483647; } Is.integer = integer; function uinteger(value) { return toString.call(value) === '[object Number]' && 0 <= value && value <= 2147483647; } Is.uinteger = uinteger; function func(value) { return toString.call(value) === '[object Function]'; } Is.func = func; function objectLiteral(value) { // Strictly speaking class instances pass this check as well. Since the LSP // doesn't use classes we ignore this for now. If we do we need to add something // like this: `Object.getPrototypeOf(Object.getPrototypeOf(x)) === null` return value !== null && typeof value === 'object'; } Is.objectLiteral = objectLiteral; function typedArray(value, check) { return Array.isArray(value) && value.every(check); } Is.typedArray = typedArray; })(Is || (Is = {})); /***/ }), /***/ 2479: /***/ ((module) => { // 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. module.exports = 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 } } /***/ }), /***/ 9602: /***/ ((module) => { "use strict"; module.exports = function (Yallist) { Yallist.prototype[Symbol.iterator] = function* () { for (let walker = this.head; walker; walker = walker.next) { yield walker.value } } } /***/ }), /***/ 4411: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; module.exports = 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 __webpack_require__(9602)(Yallist) } catch (er) {} /***/ }), /***/ 7766: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { var fs = __webpack_require__(7147); var zlib = __webpack_require__(9796); var fd_slicer = __webpack_require__(8913); var crc32 = __webpack_require__(2779); var util = __webpack_require__(3837); var EventEmitter = (__webpack_require__(2361).EventEmitter); var Transform = (__webpack_require__(2781).Transform); var PassThrough = (__webpack_require__(2781).PassThrough); var Writable = (__webpack_require__(2781).Writable); exports.open = open; exports.fromFd = fromFd; exports.fromBuffer = fromBuffer; exports.fromRandomAccessReader = fromRandomAccessReader; exports.dosDateTimeToDate = dosDateTimeToDate; exports.validateFileName = validateFileName; exports.ZipFile = ZipFile; exports.Entry = Entry; exports.RandomAccessReader = RandomAccessReader; function open(path, options, callback) { if (typeof options === "function") { callback = options; options = null; } if (options == null) options = {}; if (options.autoClose == null) options.autoClose = true; if (options.lazyEntries == null) options.lazyEntries = false; if (options.decodeStrings == null) options.decodeStrings = true; if (options.validateEntrySizes == null) options.validateEntrySizes = true; if (options.strictFileNames == null) options.strictFileNames = false; if (callback == null) callback = defaultCallback; fs.open(path, "r", function(err, fd) { if (err) return callback(err); fromFd(fd, options, function(err, zipfile) { if (err) fs.close(fd, defaultCallback); callback(err, zipfile); }); }); } function fromFd(fd, options, callback) { if (typeof options === "function") { callback = options; options = null; } if (options == null) options = {}; if (options.autoClose == null) options.autoClose = false; if (options.lazyEntries == null) options.lazyEntries = false; if (options.decodeStrings == null) options.decodeStrings = true; if (options.validateEntrySizes == null) options.validateEntrySizes = true; if (options.strictFileNames == null) options.strictFileNames = false; if (callback == null) callback = defaultCallback; fs.fstat(fd, function(err, stats) { if (err) return callback(err); var reader = fd_slicer.createFromFd(fd, {autoClose: true}); fromRandomAccessReader(reader, stats.size, options, callback); }); } function fromBuffer(buffer, options, callback) { if (typeof options === "function") { callback = options; options = null; } if (options == null) options = {}; options.autoClose = false; if (options.lazyEntries == null) options.lazyEntries = false; if (options.decodeStrings == null) options.decodeStrings = true; if (options.validateEntrySizes == null) options.validateEntrySizes = true; if (options.strictFileNames == null) options.strictFileNames = false; // limit the max chunk size. see https://github.com/thejoshwolfe/yauzl/issues/87 var reader = fd_slicer.createFromBuffer(buffer, {maxChunkSize: 0x10000}); fromRandomAccessReader(reader, buffer.length, options, callback); } function fromRandomAccessReader(reader, totalSize, options, callback) { if (typeof options === "function") { callback = options; options = null; } if (options == null) options = {}; if (options.autoClose == null) options.autoClose = true; if (options.lazyEntries == null) options.lazyEntries = false; if (options.decodeStrings == null) options.decodeStrings = true; var decodeStrings = !!options.decodeStrings; if (options.validateEntrySizes == null) options.validateEntrySizes = true; if (options.strictFileNames == null) options.strictFileNames = false; if (callback == null) callback = defaultCallback; if (typeof totalSize !== "number") throw new Error("expected totalSize parameter to be a number"); if (totalSize > Number.MAX_SAFE_INTEGER) { throw new Error("zip file too large. only file sizes up to 2^52 are supported due to JavaScript's Number type being an IEEE 754 double."); } // the matching unref() call is in zipfile.close() reader.ref(); // eocdr means End of Central Directory Record. // search backwards for the eocdr signature. // the last field of the eocdr is a variable-length comment. // the comment size is encoded in a 2-byte field in the eocdr, which we can't find without trudging backwards through the comment to find it. // as a consequence of this design decision, it's possible to have ambiguous zip file metadata if a coherent eocdr was in the comment. // we search backwards for a eocdr signature, and hope that whoever made the zip file was smart enough to forbid the eocdr signature in the comment. var eocdrWithoutCommentSize = 22; var maxCommentSize = 0xffff; // 2-byte size var bufferSize = Math.min(eocdrWithoutCommentSize + maxCommentSize, totalSize); var buffer = newBuffer(bufferSize); var bufferReadStart = totalSize - buffer.length; readAndAssertNoEof(reader, buffer, 0, bufferSize, bufferReadStart, function(err) { if (err) return callback(err); for (var i = bufferSize - eocdrWithoutCommentSize; i >= 0; i -= 1) { if (buffer.readUInt32LE(i) !== 0x06054b50) continue; // found eocdr var eocdrBuffer = buffer.slice(i); // 0 - End of central directory signature = 0x06054b50 // 4 - Number of this disk var diskNumber = eocdrBuffer.readUInt16LE(4); if (diskNumber !== 0) { return callback(new Error("multi-disk zip files are not supported: found disk number: " + diskNumber)); } // 6 - Disk where central directory starts // 8 - Number of central directory records on this disk // 10 - Total number of central directory records var entryCount = eocdrBuffer.readUInt16LE(10); // 12 - Size of central directory (bytes) // 16 - Offset of start of central directory, relative to start of archive var centralDirectoryOffset = eocdrBuffer.readUInt32LE(16); // 20 - Comment length var commentLength = eocdrBuffer.readUInt16LE(20); var expectedCommentLength = eocdrBuffer.length - eocdrWithoutCommentSize; if (commentLength !== expectedCommentLength) { return callback(new Error("invalid comment length. expected: " + expectedCommentLength + ". found: " + commentLength)); } // 22 - Comment // the encoding is always cp437. var comment = decodeStrings ? decodeBuffer(eocdrBuffer, 22, eocdrBuffer.length, false) : eocdrBuffer.slice(22); if (!(entryCount === 0xffff || centralDirectoryOffset === 0xffffffff)) { return callback(null, new ZipFile(reader, centralDirectoryOffset, totalSize, entryCount, comment, options.autoClose, options.lazyEntries, decodeStrings, options.validateEntrySizes, options.strictFileNames)); } // ZIP64 format // ZIP64 Zip64 end of central directory locator var zip64EocdlBuffer = newBuffer(20); var zip64EocdlOffset = bufferReadStart + i - zip64EocdlBuffer.length; readAndAssertNoEof(reader, zip64EocdlBuffer, 0, zip64EocdlBuffer.length, zip64EocdlOffset, function(err) { if (err) return callback(err); // 0 - zip64 end of central dir locator signature = 0x07064b50 if (zip64EocdlBuffer.readUInt32LE(0) !== 0x07064b50) { return callback(new Error("invalid zip64 end of central directory locator signature")); } // 4 - number of the disk with the start of the zip64 end of central directory // 8 - relative offset of the zip64 end of central directory record var zip64EocdrOffset = readUInt64LE(zip64EocdlBuffer, 8); // 16 - total number of disks // ZIP64 end of central directory record var zip64EocdrBuffer = newBuffer(56); readAndAssertNoEof(reader, zip64EocdrBuffer, 0, zip64EocdrBuffer.length, zip64EocdrOffset, function(err) { if (err) return callback(err); // 0 - zip64 end of central dir signature 4 bytes (0x06064b50) if (zip64EocdrBuffer.readUInt32LE(0) !== 0x06064b50) { return callback(new Error("invalid zip64 end of central directory record signature")); } // 4 - size of zip64 end of central directory record 8 bytes // 12 - version made by 2 bytes // 14 - version needed to extract 2 bytes // 16 - number of this disk 4 bytes // 20 - number of the disk with the start of the central directory 4 bytes // 24 - total number of entries in the central directory on this disk 8 bytes // 32 - total number of entries in the central directory 8 bytes entryCount = readUInt64LE(zip64EocdrBuffer, 32); // 40 - size of the central directory 8 bytes // 48 - offset of start of central directory with respect to the starting disk number 8 bytes centralDirectoryOffset = readUInt64LE(zip64EocdrBuffer, 48); // 56 - zip64 extensible data sector (variable size) return callback(null, new ZipFile(reader, centralDirectoryOffset, totalSize, entryCount, comment, options.autoClose, options.lazyEntries, decodeStrings, options.validateEntrySizes, options.strictFileNames)); }); }); return; } callback(new Error("end of central directory record signature not found")); }); } util.inherits(ZipFile, EventEmitter); function ZipFile(reader, centralDirectoryOffset, fileSize, entryCount, comment, autoClose, lazyEntries, decodeStrings, validateEntrySizes, strictFileNames) { var self = this; EventEmitter.call(self); self.reader = reader; // forward close events self.reader.on("error", function(err) { // error closing the fd emitError(self, err); }); self.reader.once("close", function() { self.emit("close"); }); self.readEntryCursor = centralDirectoryOffset; self.fileSize = fileSize; self.entryCount = entryCount; self.comment = comment; self.entriesRead = 0; self.autoClose = !!autoClose; self.lazyEntries = !!lazyEntries; self.decodeStrings = !!decodeStrings; self.validateEntrySizes = !!validateEntrySizes; self.strictFileNames = !!strictFileNames; self.isOpen = true; self.emittedError = false; if (!self.lazyEntries) self._readEntry(); } ZipFile.prototype.close = function() { if (!this.isOpen) return; this.isOpen = false; this.reader.unref(); }; function emitErrorAndAutoClose(self, err) { if (self.autoClose) self.close(); emitError(self, err); } function emitError(self, err) { if (self.emittedError) return; self.emittedError = true; self.emit("error", err); } ZipFile.prototype.readEntry = function() { if (!this.lazyEntries) throw new Error("readEntry() called without lazyEntries:true"); this._readEntry(); }; ZipFile.prototype._readEntry = function() { var self = this; if (self.entryCount === self.entriesRead) { // done with metadata setImmediate(function() { if (self.autoClose) self.close(); if (self.emittedError) return; self.emit("end"); }); return; } if (self.emittedError) return; var buffer = newBuffer(46); readAndAssertNoEof(self.reader, buffer, 0, buffer.length, self.readEntryCursor, function(err) { if (err) return emitErrorAndAutoClose(self, err); if (self.emittedError) return; var entry = new Entry(); // 0 - Central directory file header signature var signature = buffer.readUInt32LE(0); if (signature !== 0x02014b50) return emitErrorAndAutoClose(self, new Error("invalid central directory file header signature: 0x" + signature.toString(16))); // 4 - Version made by entry.versionMadeBy = buffer.readUInt16LE(4); // 6 - Version needed to extract (minimum) entry.versionNeededToExtract = buffer.readUInt16LE(6); // 8 - General purpose bit flag entry.generalPurposeBitFlag = buffer.readUInt16LE(8); // 10 - Compression method entry.compressionMethod = buffer.readUInt16LE(10); // 12 - File last modification time entry.lastModFileTime = buffer.readUInt16LE(12); // 14 - File last modification date entry.lastModFileDate = buffer.readUInt16LE(14); // 16 - CRC-32 entry.crc32 = buffer.readUInt32LE(16); // 20 - Compressed size entry.compressedSize = buffer.readUInt32LE(20); // 24 - Uncompressed size entry.uncompressedSize = buffer.readUInt32LE(24); // 28 - File name length (n) entry.fileNameLength = buffer.readUInt16LE(28); // 30 - Extra field length (m) entry.extraFieldLength = buffer.readUInt16LE(30); // 32 - File comment length (k) entry.fileCommentLength = buffer.readUInt16LE(32); // 34 - Disk number where file starts // 36 - Internal file attributes entry.internalFileAttributes = buffer.readUInt16LE(36); // 38 - External file attributes entry.externalFileAttributes = buffer.readUInt32LE(38); // 42 - Relative offset of local file header entry.relativeOffsetOfLocalHeader = buffer.readUInt32LE(42); if (entry.generalPurposeBitFlag & 0x40) return emitErrorAndAutoClose(self, new Error("strong encryption is not supported")); self.readEntryCursor += 46; buffer = newBuffer(entry.fileNameLength + entry.extraFieldLength + entry.fileCommentLength); readAndAssertNoEof(self.reader, buffer, 0, buffer.length, self.readEntryCursor, function(err) { if (err) return emitErrorAndAutoClose(self, err); if (self.emittedError) return; // 46 - File name var isUtf8 = (entry.generalPurposeBitFlag & 0x800) !== 0; entry.fileName = self.decodeStrings ? decodeBuffer(buffer, 0, entry.fileNameLength, isUtf8) : buffer.slice(0, entry.fileNameLength); // 46+n - Extra field var fileCommentStart = entry.fileNameLength + entry.extraFieldLength; var extraFieldBuffer = buffer.slice(entry.fileNameLength, fileCommentStart); entry.extraFields = []; var i = 0; while (i < extraFieldBuffer.length - 3) { var headerId = extraFieldBuffer.readUInt16LE(i + 0); var dataSize = extraFieldBuffer.readUInt16LE(i + 2); var dataStart = i + 4; var dataEnd = dataStart + dataSize; if (dataEnd > extraFieldBuffer.length) return emitErrorAndAutoClose(self, new Error("extra field length exceeds extra field buffer size")); var dataBuffer = newBuffer(dataSize); extraFieldBuffer.copy(dataBuffer, 0, dataStart, dataEnd); entry.extraFields.push({ id: headerId, data: dataBuffer, }); i = dataEnd; } // 46+n+m - File comment entry.fileComment = self.decodeStrings ? decodeBuffer(buffer, fileCommentStart, fileCommentStart + entry.fileCommentLength, isUtf8) : buffer.slice(fileCommentStart, fileCommentStart + entry.fileCommentLength); // compatibility hack for https://github.com/thejoshwolfe/yauzl/issues/47 entry.comment = entry.fileComment; self.readEntryCursor += buffer.length; self.entriesRead += 1; if (entry.uncompressedSize === 0xffffffff || entry.compressedSize === 0xffffffff || entry.relativeOffsetOfLocalHeader === 0xffffffff) { // ZIP64 format // find the Zip64 Extended Information Extra Field var zip64EiefBuffer = null; for (var i = 0; i < entry.extraFields.length; i++) { var extraField = entry.extraFields[i]; if (extraField.id === 0x0001) { zip64EiefBuffer = extraField.data; break; } } if (zip64EiefBuffer == null) { return emitErrorAndAutoClose(self, new Error("expected zip64 extended information extra field")); } var index = 0; // 0 - Original Size 8 bytes if (entry.uncompressedSize === 0xffffffff) { if (index + 8 > zip64EiefBuffer.length) { return emitErrorAndAutoClose(self, new Error("zip64 extended information extra field does not include uncompressed size")); } entry.uncompressedSize = readUInt64LE(zip64EiefBuffer, index); index += 8; } // 8 - Compressed Size 8 bytes if (entry.compressedSize === 0xffffffff) { if (index + 8 > zip64EiefBuffer.length) { return emitErrorAndAutoClose(self, new Error("zip64 extended information extra field does not include compressed size")); } entry.compressedSize = readUInt64LE(zip64EiefBuffer, index); index += 8; } // 16 - Relative Header Offset 8 bytes if (entry.relativeOffsetOfLocalHeader === 0xffffffff) { if (index + 8 > zip64EiefBuffer.length) { return emitErrorAndAutoClose(self, new Error("zip64 extended information extra field does not include relative header offset")); } entry.relativeOffsetOfLocalHeader = readUInt64LE(zip64EiefBuffer, index); index += 8; } // 24 - Disk Start Number 4 bytes } // check for Info-ZIP Unicode Path Extra Field (0x7075) // see https://github.com/thejoshwolfe/yauzl/issues/33 if (self.decodeStrings) { for (var i = 0; i < entry.extraFields.length; i++) { var extraField = entry.extraFields[i]; if (extraField.id === 0x7075) { if (extraField.data.length < 6) { // too short to be meaningful continue; } // Version 1 byte version of this extra field, currently 1 if (extraField.data.readUInt8(0) !== 1) { // > Changes may not be backward compatible so this extra // > field should not be used if the version is not recognized. continue; } // NameCRC32 4 bytes File Name Field CRC32 Checksum var oldNameCrc32 = extraField.data.readUInt32LE(1); if (crc32.unsigned(buffer.slice(0, entry.fileNameLength)) !== oldNameCrc32) { // > If the CRC check fails, this UTF-8 Path Extra Field should be // > ignored and the File Name field in the header should be used instead. continue; } // UnicodeName Variable UTF-8 version of the entry File Name entry.fileName = decodeBuffer(extraField.data, 5, extraField.data.length, true); break; } } } // validate file size if (self.validateEntrySizes && entry.compressionMethod === 0) { var expectedCompressedSize = entry.uncompressedSize; if (entry.isEncrypted()) { // traditional encryption prefixes the file data with a header expectedCompressedSize += 12; } if (entry.compressedSize !== expectedCompressedSize) { var msg = "compressed/uncompressed size mismatch for stored file: " + entry.compressedSize + " != " + entry.uncompressedSize; return emitErrorAndAutoClose(self, new Error(msg)); } } if (self.decodeStrings) { if (!self.strictFileNames) { // allow backslash entry.fileName = entry.fileName.replace(/\\/g, "/"); } var errorMessage = validateFileName(entry.fileName, self.validateFileNameOptions); if (errorMessage != null) return emitErrorAndAutoClose(self, new Error(errorMessage)); } self.emit("entry", entry); if (!self.lazyEntries) self._readEntry(); }); }); }; ZipFile.prototype.openReadStream = function(entry, options, callback) { var self = this; // parameter validation var relativeStart = 0; var relativeEnd = entry.compressedSize; if (callback == null) { callback = options; options = {}; } else { // validate options that the caller has no excuse to get wrong if (options.decrypt != null) { if (!entry.isEncrypted()) { throw new Error("options.decrypt can only be specified for encrypted entries"); } if (options.decrypt !== false) throw new Error("invalid options.decrypt value: " + options.decrypt); if (entry.isCompressed()) { if (options.decompress !== false) throw new Error("entry is encrypted and compressed, and options.decompress !== false"); } } if (options.decompress != null) { if (!entry.isCompressed()) { throw new Error("options.decompress can only be specified for compressed entries"); } if (!(options.decompress === false || options.decompress === true)) { throw new Error("invalid options.decompress value: " + options.decompress); } } if (options.start != null || options.end != null) { if (entry.isCompressed() && options.decompress !== false) { throw new Error("start/end range not allowed for compressed entry without options.decompress === false"); } if (entry.isEncrypted() && options.decrypt !== false) { throw new Error("start/end range not allowed for encrypted entry without options.decrypt === false"); } } if (options.start != null) { relativeStart = options.start; if (relativeStart < 0) throw new Error("options.start < 0"); if (relativeStart > entry.compressedSize) throw new Error("options.start > entry.compressedSize"); } if (options.end != null) { relativeEnd = options.end; if (relativeEnd < 0) throw new Error("options.end < 0"); if (relativeEnd > entry.compressedSize) throw new Error("options.end > entry.compressedSize"); if (relativeEnd < relativeStart) throw new Error("options.end < options.start"); } } // any further errors can either be caused by the zipfile, // or were introduced in a minor version of yauzl, // so should be passed to the client rather than thrown. if (!self.isOpen) return callback(new Error("closed")); if (entry.isEncrypted()) { if (options.decrypt !== false) return callback(new Error("entry is encrypted, and options.decrypt !== false")); } // make sure we don't lose the fd before we open the actual read stream self.reader.ref(); var buffer = newBuffer(30); readAndAssertNoEof(self.reader, buffer, 0, buffer.length, entry.relativeOffsetOfLocalHeader, function(err) { try { if (err) return callback(err); // 0 - Local file header signature = 0x04034b50 var signature = buffer.readUInt32LE(0); if (signature !== 0x04034b50) { return callback(new Error("invalid local file header signature: 0x" + signature.toString(16))); } // all this should be redundant // 4 - Version needed to extract (minimum) // 6 - General purpose bit flag // 8 - Compression method // 10 - File last modification time // 12 - File last modification date // 14 - CRC-32 // 18 - Compressed size // 22 - Uncompressed size // 26 - File name length (n) var fileNameLength = buffer.readUInt16LE(26); // 28 - Extra field length (m) var extraFieldLength = buffer.readUInt16LE(28); // 30 - File name // 30+n - Extra field var localFileHeaderEnd = entry.relativeOffsetOfLocalHeader + buffer.length + fileNameLength + extraFieldLength; var decompress; if (entry.compressionMethod === 0) { // 0 - The file is stored (no compression) decompress = false; } else if (entry.compressionMethod === 8) { // 8 - The file is Deflated decompress = options.decompress != null ? options.decompress : true; } else { return callback(new Error("unsupported compression method: " + entry.compressionMethod)); } var fileDataStart = localFileHeaderEnd; var fileDataEnd = fileDataStart + entry.compressedSize; if (entry.compressedSize !== 0) { // bounds check now, because the read streams will probably not complain loud enough. // since we're dealing with an unsigned offset plus an unsigned size, // we only have 1 thing to check for. if (fileDataEnd > self.fileSize) { return callback(new Error("file data overflows file bounds: " + fileDataStart + " + " + entry.compressedSize + " > " + self.fileSize)); } } var readStream = self.reader.createReadStream({ start: fileDataStart + relativeStart, end: fileDataStart + relativeEnd, }); var endpointStream = readStream; if (decompress) { var destroyed = false; var inflateFilter = zlib.createInflateRaw(); readStream.on("error", function(err) { // setImmediate here because errors can be emitted during the first call to pipe() setImmediate(function() { if (!destroyed) inflateFilter.emit("error", err); }); }); readStream.pipe(inflateFilter); if (self.validateEntrySizes) { endpointStream = new AssertByteCountStream(entry.uncompressedSize); inflateFilter.on("error", function(err) { // forward zlib errors to the client-visible stream setImmediate(function() { if (!destroyed) endpointStream.emit("error", err); }); }); inflateFilter.pipe(endpointStream); } else { // the zlib filter is the client-visible stream endpointStream = inflateFilter; } // this is part of yauzl's API, so implement this function on the client-visible stream endpointStream.destroy = function() { destroyed = true; if (inflateFilter !== endpointStream) inflateFilter.unpipe(endpointStream); readStream.unpipe(inflateFilter); // TODO: the inflateFilter may cause a memory leak. see Issue #27. readStream.destroy(); }; } callback(null, endpointStream); } finally { self.reader.unref(); } }); }; function Entry() { } Entry.prototype.getLastModDate = function() { return dosDateTimeToDate(this.lastModFileDate, this.lastModFileTime); }; Entry.prototype.isEncrypted = function() { return (this.generalPurposeBitFlag & 0x1) !== 0; }; Entry.prototype.isCompressed = function() { return this.compressionMethod === 8; }; function dosDateTimeToDate(date, time) { var day = date & 0x1f; // 1-31 var month = (date >> 5 & 0xf) - 1; // 1-12, 0-11 var year = (date >> 9 & 0x7f) + 1980; // 0-128, 1980-2108 var millisecond = 0; var second = (time & 0x1f) * 2; // 0-29, 0-58 (even numbers) var minute = time >> 5 & 0x3f; // 0-59 var hour = time >> 11 & 0x1f; // 0-23 return new Date(year, month, day, hour, minute, second, millisecond); } function validateFileName(fileName) { if (fileName.indexOf("\\") !== -1) { return "invalid characters in fileName: " + fileName; } if (/^[a-zA-Z]:/.test(fileName) || /^\//.test(fileName)) { return "absolute path: " + fileName; } if (fileName.split("/").indexOf("..") !== -1) { return "invalid relative path: " + fileName; } // all good return null; } function readAndAssertNoEof(reader, buffer, offset, length, position, callback) { if (length === 0) { // fs.read will throw an out-of-bounds error if you try to read 0 bytes from a 0 byte file return setImmediate(function() { callback(null, newBuffer(0)); }); } reader.read(buffer, offset, length, position, function(err, bytesRead) { if (err) return callback(err); if (bytesRead < length) { return callback(new Error("unexpected EOF")); } callback(); }); } util.inherits(AssertByteCountStream, Transform); function AssertByteCountStream(byteCount) { Transform.call(this); this.actualByteCount = 0; this.expectedByteCount = byteCount; } AssertByteCountStream.prototype._transform = function(chunk, encoding, cb) { this.actualByteCount += chunk.length; if (this.actualByteCount > this.expectedByteCount) { var msg = "too many bytes in the stream. expected " + this.expectedByteCount + ". got at least " + this.actualByteCount; return cb(new Error(msg)); } cb(null, chunk); }; AssertByteCountStream.prototype._flush = function(cb) { if (this.actualByteCount < this.expectedByteCount) { var msg = "not enough bytes in the stream. expected " + this.expectedByteCount + ". got only " + this.actualByteCount; return cb(new Error(msg)); } cb(); }; util.inherits(RandomAccessReader, EventEmitter); function RandomAccessReader() { EventEmitter.call(this); this.refCount = 0; } RandomAccessReader.prototype.ref = function() { this.refCount += 1; }; RandomAccessReader.prototype.unref = function() { var self = this; self.refCount -= 1; if (self.refCount > 0) return; if (self.refCount < 0) throw new Error("invalid unref"); self.close(onCloseDone); function onCloseDone(err) { if (err) return self.emit('error', err); self.emit('close'); } }; RandomAccessReader.prototype.createReadStream = function(options) { var start = options.start; var end = options.end; if (start === end) { var emptyStream = new PassThrough(); setImmediate(function() { emptyStream.end(); }); return emptyStream; } var stream = this._readStreamForRange(start, end); var destroyed = false; var refUnrefFilter = new RefUnrefFilter(this); stream.on("error", function(err) { setImmediate(function() { if (!destroyed) refUnrefFilter.emit("error", err); }); }); refUnrefFilter.destroy = function() { stream.unpipe(refUnrefFilter); refUnrefFilter.unref(); stream.destroy(); }; var byteCounter = new AssertByteCountStream(end - start); refUnrefFilter.on("error", function(err) { setImmediate(function() { if (!destroyed) byteCounter.emit("error", err); }); }); byteCounter.destroy = function() { destroyed = true; refUnrefFilter.unpipe(byteCounter); refUnrefFilter.destroy(); }; return stream.pipe(refUnrefFilter).pipe(byteCounter); }; RandomAccessReader.prototype._readStreamForRange = function(start, end) { throw new Error("not implemented"); }; RandomAccessReader.prototype.read = function(buffer, offset, length, position, callback) { var readStream = this.createReadStream({start: position, end: position + length}); var writeStream = new Writable(); var written = 0; writeStream._write = function(chunk, encoding, cb) { chunk.copy(buffer, offset + written, 0, chunk.length); written += chunk.length; cb(); }; writeStream.on("finish", callback); readStream.on("error", function(error) { callback(error); }); readStream.pipe(writeStream); }; RandomAccessReader.prototype.close = function(callback) { setImmediate(callback); }; util.inherits(RefUnrefFilter, PassThrough); function RefUnrefFilter(context) { PassThrough.call(this); this.context = context; this.context.ref(); this.unreffedYet = false; } RefUnrefFilter.prototype._flush = function(cb) { this.unref(); cb(); }; RefUnrefFilter.prototype.unref = function(cb) { if (this.unreffedYet) return; this.unreffedYet = true; this.context.unref(); }; var cp437 = '\u0000☺☻♥♦♣♠•◘○◙♂♀♪♫☼►◄↕‼¶§▬↨↑↓→←∟↔▲▼ !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~⌂ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ '; function decodeBuffer(buffer, start, end, isUtf8) { if (isUtf8) { return buffer.toString("utf8", start, end); } else { var result = ""; for (var i = start; i < end; i++) { result += cp437[buffer[i]]; } return result; } } function readUInt64LE(buffer, offset) { // there is no native function for this, because we can't actually store 64-bit integers precisely. // after 53 bits, JavaScript's Number type (IEEE 754 double) can't store individual integers anymore. // but since 53 bits is a whole lot more than 32 bits, we do our best anyway. var lower32 = buffer.readUInt32LE(offset); var upper32 = buffer.readUInt32LE(offset + 4); // we can't use bitshifting here, because JavaScript bitshifting only works on 32-bit integers. return upper32 * 0x100000000 + lower32; // as long as we're bounds checking the result of this function against the total file size, // we'll catch any overflow errors, because we already made sure the total file size was within reason. } // Node 10 deprecated new Buffer(). var newBuffer; if (typeof Buffer.allocUnsafe === "function") { newBuffer = function(len) { return Buffer.allocUnsafe(len); }; } else { newBuffer = function(len) { return new Buffer(len); }; } function defaultCallback(err) { if (err) throw err; } /***/ }), /***/ 9496: /***/ ((module) => { "use strict"; module.exports = require("vscode"); /***/ }), /***/ 9491: /***/ ((module) => { "use strict"; module.exports = require("assert"); /***/ }), /***/ 4300: /***/ ((module) => { "use strict"; module.exports = require("buffer"); /***/ }), /***/ 2081: /***/ ((module) => { "use strict"; module.exports = require("child_process"); /***/ }), /***/ 6113: /***/ ((module) => { "use strict"; module.exports = require("crypto"); /***/ }), /***/ 2361: /***/ ((module) => { "use strict"; module.exports = require("events"); /***/ }), /***/ 7147: /***/ ((module) => { "use strict"; module.exports = require("fs"); /***/ }), /***/ 5687: /***/ ((module) => { "use strict"; module.exports = require("https"); /***/ }), /***/ 1808: /***/ ((module) => { "use strict"; module.exports = require("net"); /***/ }), /***/ 2037: /***/ ((module) => { "use strict"; module.exports = require("os"); /***/ }), /***/ 1017: /***/ ((module) => { "use strict"; module.exports = require("path"); /***/ }), /***/ 2781: /***/ ((module) => { "use strict"; module.exports = require("stream"); /***/ }), /***/ 1576: /***/ ((module) => { "use strict"; module.exports = require("string_decoder"); /***/ }), /***/ 6224: /***/ ((module) => { "use strict"; module.exports = require("tty"); /***/ }), /***/ 7310: /***/ ((module) => { "use strict"; module.exports = require("url"); /***/ }), /***/ 3837: /***/ ((module) => { "use strict"; module.exports = require("util"); /***/ }), /***/ 9796: /***/ ((module) => { "use strict"; module.exports = require("zlib"); /***/ }) /******/ }); /************************************************************************/ /******/ // The module cache /******/ var __webpack_module_cache__ = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ var cachedModule = __webpack_module_cache__[moduleId]; /******/ if (cachedModule !== undefined) { /******/ return cachedModule.exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = __webpack_module_cache__[moduleId] = { /******/ // no module.id needed /******/ // no module.loaded needed /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /************************************************************************/ /******/ /* webpack/runtime/define property getters */ /******/ (() => { /******/ // define getter functions for harmony exports /******/ __webpack_require__.d = (exports, definition) => { /******/ for(var key in definition) { /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) { /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }); /******/ } /******/ } /******/ }; /******/ })(); /******/ /******/ /* webpack/runtime/hasOwnProperty shorthand */ /******/ (() => { /******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) /******/ })(); /******/ /******/ /* webpack/runtime/make namespace object */ /******/ (() => { /******/ // define __esModule on exports /******/ __webpack_require__.r = (exports) => { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ })(); /******/ /************************************************************************/ /******/ /******/ // startup /******/ // Load entry module and return exports /******/ // This entry module is referenced by other modules so it can't be inlined /******/ var __webpack_exports__ = __webpack_require__(7015); /******/ module.exports = __webpack_exports__; /******/ /******/ })() ; //# sourceMappingURL=extension.js.map